diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 5b5d969db..71db8c2a3 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,5 +1,5 @@ ############################################################################## -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and BLT +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and BLT # project contributors. See the LICENSE file for details. ############################################################################## @@ -33,6 +33,7 @@ stages: # This is where jobs are included include: - - local: .gitlab/build_quartz.yml - local: .gitlab/build_lassen.yml - - local: .gitlab/build_tioga.yml + - local: .gitlab/build_quartz.yml +# white238: Turned off while tioga is down for maintenance and is fickle +# - local: .gitlab/build_tioga.yml diff --git a/.gitlab/build_lassen.yml b/.gitlab/build_lassen.yml index f4c98271e..08bf4b474 100644 --- a/.gitlab/build_lassen.yml +++ b/.gitlab/build_lassen.yml @@ -15,7 +15,7 @@ .with_cuda: before_script: - module load cmake/3.18.0 - - module load cuda/11.1.1 + - module load cuda/11.2.0 #### # Template @@ -28,32 +28,22 @@ #### # Build jobs -lassen-clang_upstream_link_with_nvcc: +lassen-clang_10.0.1_nvcc_c++14_export_tpls: variables: - HOST_CONFIG: "clang@upstream_link_with_nvcc.cmake" + HOST_CONFIG: "clang@10.0.1_nvcc_c++14_export_tpls.cmake" extends: [.build_on_lassen, .with_cuda] -lassen-clang_upstream_nvcc_c++17: +lassen-clang_10.0.1_nvcc_c++14_xlf: variables: - HOST_CONFIG: "clang@upstream_nvcc_c++17.cmake" + HOST_CONFIG: "clang@10.0.1_nvcc_c++14_xlf.cmake" extends: [.build_on_lassen, .with_cuda] -lassen-clang_upstream_nvcc_c++17_no_separable: +lassen-clang_10.0.1_nvcc_c++17: variables: - HOST_CONFIG: "clang@upstream_nvcc_c++17_no_separable.cmake" + HOST_CONFIG: "clang@10.0.1_nvcc_c++17.cmake" extends: [.build_on_lassen, .with_cuda] -lassen-clang_upstream_nvcc_c++14_export_tpls: +lassen-clang_10.0.1_nvcc_c++17_no_separable: variables: - HOST_CONFIG: "clang@upstream_nvcc_c++14-export-tpls.cmake" - extends: [.build_on_lassen, .with_cuda] - -lassen-clang_upstream_nvcc_xlf: - variables: - HOST_CONFIG: "clang@upstream_nvcc_xlf.cmake" - extends: [.build_on_lassen, .with_cuda] - -lassen-pgi_20.4_nvcc: - variables: - HOST_CONFIG: "pgi@20.4_nvcc.cmake" + HOST_CONFIG: "clang@10.0.1_nvcc_c++17_no_separable.cmake" extends: [.build_on_lassen, .with_cuda] diff --git a/.gitlab/build_quartz.yml b/.gitlab/build_quartz.yml index b9e49288f..5e3c9f69b 100644 --- a/.gitlab/build_quartz.yml +++ b/.gitlab/build_quartz.yml @@ -45,37 +45,22 @@ quartz_release: #### # Build jobs -quartz-clang_4_0_0_libcxx: +quartz-clang_14_0_6: variables: - HOST_CONFIG: "clang@4.0.0-libcxx.cmake" + HOST_CONFIG: "clang@14.0.6.cmake" extends: [.build_on_quartz] -quartz-clang_6_0_0_static_analysis: +quartz-gcc_10_3_1: variables: - HOST_CONFIG: "clang@6.0.0-static-analysis.cmake" + HOST_CONFIG: "gcc@10.3.1.cmake" extends: [.build_on_quartz] -quartz-gcc_8_3_1: +quartz-gcc_10_3_1-export-tpls: variables: - HOST_CONFIG: "gcc@8.3.1.cmake" + HOST_CONFIG: "gcc@10.3.1-export-tpls.cmake" extends: [.build_on_quartz] -quartz-gcc_8_3_1_export_tpls: +quartz-intel_2022_1_0_cxx17: variables: - HOST_CONFIG: "gcc@8.3.1-export-tpls.cmake" - extends: [.build_on_quartz] - -quartz-inteloneapi_2021_3: - variables: - HOST_CONFIG: "intel-oneapi@2021.3.cmake" - extends: [.build_on_quartz] - -quartz-inteloneapi_2021_3_cxx17: - variables: - HOST_CONFIG: "intel-oneapi@2021.3-c++17.cmake" - extends: [.build_on_quartz] - -quartz-pgi_20_1: - variables: - HOST_CONFIG: "pgi@20.1.cmake" + HOST_CONFIG: "intel@2022.1.0-c++17.cmake" extends: [.build_on_quartz] diff --git a/.mailmap b/.mailmap index 781ba0da1..f99ac90c6 100644 --- a/.mailmap +++ b/.mailmap @@ -1,12 +1,16 @@ +Alan Dayton Alan Dayton <6393677+adayton1@users.noreply.github.com> +Alex Tyler Chapman Alex Tyler Chapman <100869159+chapman39@users.noreply.github.com> Alfredo Metere Alfredo Metere Alfredo Metere metere1llnl <51676123+metere1llnl@users.noreply.github.com> Benjamin Curtice Corbett Ben Corbett <32752943+corbett5@users.noreply.github.com> +Brian Manh Hien Han Brian Han Burl M. Hall BurlMHall <47543546+BurlMHall@users.noreply.github.com> Daniel Taller Danny Taller <66029857+dtaller@users.noreply.github.com> Geoffrey Oxberry Geoffrey M Oxberry Geoffrey Oxberry Geoffrey M. Oxberry George Zagaris George Zagaris Jason Burmark Jason Burmark +Johann Dahm Johann Dahm Josh Essman Josh Essman <68349992+joshessman-llnl@users.noreply.github.com> Keith Healy keithhealy <50376825+keithhealy@users.noreply.github.com> Kenneth Weiss Kenny Weiss @@ -21,4 +25,5 @@ Peter B. Robinson robinspb Randolph Settgast Randolph R. Settgast Randolph R. Settgast Randolph R. Settgast Randolph Settgast -Johann Dahm Johann Dahm +Steve Abbott Steve Abbott + diff --git a/LICENSE b/LICENSE index 8e4df6528..039a20b01 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC. +Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC. All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index 7142d55ba..d9cb9c001 100644 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -9,6 +9,26 @@ The project release numbers follow [Semantic Versioning](http://semver.org/spec/ ## [Unreleased] - Release date yyyy-mm-dd +## [Version 0.5.3] - Release date 2023-06-05 + +### Changed +- Updated Googletest to main from 04/13/2023. + Commit: [12a5852e451baabc79c63a86c634912c563d57bc](https://github.com/google/googletest/commit/12a5852e451baabc79c63a86c634912c563d57bc). + Note: this version of Googletest requires C++14, and PGI is not supported. If you are using PGI, set ENABLE_GTEST OFF. +- Updated GoogleBenchmark to 1.8 + +### Added +- Added `blt_print_variables` macro to print variables in current scope, with regex filtering on variable names and values +- Added `DEPENDS_ON` optional parameter to `blt_check_code_compiles` macro to allow for checking if a feature is available in a third-party imported target. +- Added `CONFIGURATIONS` and `OMP_NUM_THREADS` options to `blt_add_benchmark` + +### Fixed +- Guard HIP compiler flag ``--rocm-path=/path/to/rocm`` against Crayftn compiler earlier than 15.0.0. +- Fix doubling of `INTERFACE_INCLUDE_DIRECTORIES` in `blt_patch_target(... TREAT_INCLUDES_AS_SYSTEM true)`. + +### Removed +- Removed tracking all sources in a project via ``${PROJECT_NAME}_ALL_SOURCES``. + ## [Version 0.5.2] - Release date 2022-10-05 ### Added @@ -268,7 +288,8 @@ The project release numbers follow [Semantic Versioning](http://semver.org/spec/ -[Unreleased]: https://github.com/LLNL/blt/compare/v0.5.2...develop +[Unreleased]: https://github.com/LLNL/blt/compare/v0.5.3...develop +[Version 0.5.3]: https://github.com/LLNL/blt/compare/v0.5.2...v0.5.3 [Version 0.5.2]: https://github.com/LLNL/blt/compare/v0.5.1...v0.5.2 [Version 0.5.1]: https://github.com/LLNL/blt/compare/v0.5.0...v0.5.1 [Version 0.5.0]: https://github.com/LLNL/blt/compare/v0.4.1...v0.5.0 diff --git a/SetupBLT.cmake b/SetupBLT.cmake index 9de833e14..9c6af9296 100644 --- a/SetupBLT.cmake +++ b/SetupBLT.cmake @@ -1,10 +1,10 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) if (NOT BLT_LOADED) - set(BLT_VERSION "0.5.2" CACHE STRING "") + set(BLT_VERSION "0.5.3" CACHE STRING "") mark_as_advanced(BLT_VERSION) message(STATUS "BLT Version: ${BLT_VERSION}") diff --git a/azure-pipelines.yml b/azure-pipelines.yml index fdde52e81..22e051e64 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -7,44 +7,36 @@ variables: DOCKER_FLAGS: "--user='root' -v `pwd`:/blt -w /blt/build $(Compiler_ImageName)" C_COMPILERS: "-DCMAKE_C_COMPILER=$(C_COMPILER) -DCMAKE_CXX_COMPILER=$(CXX_COMPILER)" MPI_FLAGS: '-DENABLE_MPI=ON -DMPI_C_COMPILER=$(MPI_DIR)/bin/mpicc -DMPI_CXX_COMPILER=$(MPI_DIR)/bin/mpicxx -DMPIEXEC=$(MPI_DIR)/bin/mpiexec -DMPIEXEC_NUMPROC_FLAG=-n' + # Use the 'axom/tpls' images because they contain mpi and fortran + GCC11_IMAGENAME: 'axom/tpls:gcc-11_02-02-23_01h-47m' + CLANG10_IMAGENAME: 'axom/tpls:clang-10_02-02-23_01h-47m' + VM_ImageName: 'ubuntu-20.04' strategy: matrix: - linux_gcc8: - VM_ImageName: 'ubuntu-20.04' - Compiler_ImageName: 'axom/tpls:gcc-8_10-21-21_21h-28m' - C_COMPILER: '/usr/bin/gcc' - CXX_COMPILER: '/usr/bin/g++' - CMAKE_BIN_DIR: '/usr/bin' - MPI_DIR: '/usr' - CMAKE_FLAGS: '$(C_COMPILERS) $(MPI_FLAGS) -DENABLE_GTEST_DEATH_TESTS=OFF -DENABLE_OPENMP=ON' linux_gcc11: - VM_ImageName: 'ubuntu-20.04' - Compiler_ImageName: 'axom/tpls:gcc-11_01-27-22_05h-56m' + Compiler_ImageName: '$(GCC11_IMAGENAME)' C_COMPILER: '/usr/bin/gcc' CXX_COMPILER: '/usr/bin/g++' CMAKE_BIN_DIR: '/usr/bin' MPI_DIR: '/usr' CMAKE_FLAGS: '$(C_COMPILERS) $(MPI_FLAGS) -DENABLE_GTEST_DEATH_TESTS=OFF -DENABLE_OPENMP=ON' linux_gcc11_benchmarks: - VM_ImageName: 'ubuntu-20.04' - Compiler_ImageName: 'axom/tpls:gcc-11_01-27-22_05h-56m' + Compiler_ImageName: '$(GCC11_IMAGENAME)' C_COMPILER: '/usr/bin/gcc' CXX_COMPILER: '/usr/bin/g++' CMAKE_BIN_DIR: '/usr/bin' MPI_DIR: '/usr' CMAKE_FLAGS: '$(C_COMPILERS) $(MPI_FLAGS) -DENABLE_GTEST_DEATH_TESTS=OFF -DENABLE_OPENMP=ON -DENABLE_BENCHMARKS=ON' linux_gcc11_gmock: - VM_ImageName: 'ubuntu-20.04' - Compiler_ImageName: 'axom/tpls:gcc-11_01-27-22_05h-56m' + Compiler_ImageName: '$(GCC11_IMAGENAME)' C_COMPILER: '/usr/bin/gcc' CXX_COMPILER: '/usr/bin/g++' CMAKE_BIN_DIR: '/usr/bin' MPI_DIR: '/usr' CMAKE_FLAGS: '$(C_COMPILERS) $(MPI_FLAGS) -DENABLE_GTEST_DEATH_TESTS=OFF -DENABLE_OPENMP=ON -DENABLE_GMOCK=ON' linux_clang10: - VM_ImageName: 'ubuntu-18.04' - Compiler_ImageName: 'axom/tpls:clang-10_10-21-21_21h-28m' + Compiler_ImageName: '$(CLANG10_IMAGENAME)' C_COMPILER: '/usr/bin/clang' CXX_COMPILER: '/usr/bin/clang++' CMAKE_BIN_DIR: '/usr/bin' @@ -54,7 +46,7 @@ strategy: VM_ImageName: 'macos-12' CMAKE_FLAGS: '' windows: - VM_ImageName: 'windows-2019' + VM_ImageName: 'windows-2022' CMAKE_FLAGS: '' pool: diff --git a/cmake/BLTGitMacros.cmake b/cmake/BLTGitMacros.cmake index ce47a35bb..695c3ffcf 100644 --- a/cmake/BLTGitMacros.cmake +++ b/cmake/BLTGitMacros.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/BLTMacros.cmake b/cmake/BLTMacros.cmake index 5601933f5..34b77b28e 100644 --- a/cmake/BLTMacros.cmake +++ b/cmake/BLTMacros.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -480,18 +480,8 @@ macro(blt_patch_target) endif() endif() - # PGI does not support -isystem - if( (${arg_TREAT_INCLUDES_AS_SYSTEM}) AND (NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "PGI")) - get_target_property(_target_includes ${arg_NAME} INTERFACE_INCLUDE_DIRECTORIES) - # Don't copy if the target had no include directories - if(_target_includes) - if(_standard_lib_interface) - target_include_directories(${arg_NAME} SYSTEM ${_scope} ${_target_includes}) - else() - set_property(TARGET ${arg_NAME} PROPERTY - INTERFACE_SYSTEM_INCLUDE_DIRECTORIES ${_target_includes}) - endif() - endif() + if(${arg_TREAT_INCLUDES_AS_SYSTEM}) + blt_convert_to_system_includes(TARGET ${arg_NAME}) endif() # FIXME: Is this all that's needed? @@ -725,8 +715,6 @@ macro(blt_add_library) blt_set_target_folder(TARGET ${arg_NAME} FOLDER "${arg_FOLDER}") endif() - blt_update_project_sources( TARGET_SOURCES ${arg_SOURCES} ${arg_HEADERS}) - if ( arg_SOURCES ) # Don't clean header-only libraries because you would have to handle # the white-list of properties that are allowed @@ -831,8 +819,6 @@ macro(blt_add_executable) blt_set_target_folder(TARGET ${arg_NAME} FOLDER "${arg_FOLDER}") endif() - blt_update_project_sources( TARGET_SOURCES ${arg_SOURCES} ${arg_HEADERS} ) - blt_clean_target(TARGET ${arg_NAME}) endmacro(blt_add_executable) @@ -929,15 +915,17 @@ endmacro(blt_add_test) ##------------------------------------------------------------------------------ ## blt_add_benchmark( NAME [name] ## COMMAND [command] -## NUM_MPI_TASKS [n]) +## NUM_MPI_TASKS [n] +## NUM_OMP_THREADS [n] +## CONFIGURATIONS [config1 [config2...]]) ## ## Adds a benchmark to the project. ##------------------------------------------------------------------------------ macro(blt_add_benchmark) set(options) - set(singleValueArgs NAME NUM_MPI_TASKS) - set(multiValueArgs COMMAND) + set(singleValueArgs NAME NUM_MPI_TASKS NUM_OMP_THREADS) + set(multiValueArgs COMMAND CONFIGURATIONS) ## parse the arguments to the macro cmake_parse_arguments(arg @@ -945,10 +933,11 @@ macro(blt_add_benchmark) # The 'CONFIGURATIONS Benchmark' line excludes benchmarks # from the general list of tests - blt_add_test( NAME ${arg_NAME} - COMMAND ${arg_COMMAND} - NUM_MPI_TASKS ${arg_NUM_MPI_TASKS} - CONFIGURATIONS Benchmark) + blt_add_test( NAME ${arg_NAME} + COMMAND ${arg_COMMAND} + NUM_MPI_TASKS ${arg_NUM_MPI_TASKS} + NUM_OMP_THREADS ${arg_NUM_OMP_THREADS} + CONFIGURATIONS Benchmark ${arg_CONFIGURATIONS}) endmacro(blt_add_benchmark) @@ -1363,6 +1352,134 @@ macro(blt_print_target_properties) endmacro(blt_print_target_properties) +##------------------------------------------------------------------------------ +## blt_print_variables([NAME_REGEX ] +## [VALUE_REGEX ] +## [IGNORE_CASE]) +## +## Prints all (or filtered) variables and their values in the current scope. +## +## Defaults: +## The regexes are case-sensitive unless the IGNORE_CASE option is supplied +## NAME_REGEX = .* (print every property name) +## VALUE_REGEX = .* (print every property value) +## +##------------------------------------------------------------------------------ +macro(blt_print_variables) + + set(options IGNORE_CASE) + set(singleValuedArgs NAME_REGEX VALUE_REGEX) + set(multiValuedArgs) + + # parse and initialize arguments to the macro + cmake_parse_arguments(arg + "${options}" "${singleValuedArgs}" "${multiValuedArgs}" ${ARGN}) + + + message(STATUS "[blt_print_variables] The following variables are defined at the calling site in '${CMAKE_CURRENT_LIST_FILE}' -- ") + + if(NOT DEFINED arg_IGNORE_CASE) + set(arg_IGNORE_CASE FALSE) + endif() + + if(arg_IGNORE_CASE) + set(_case_sensitivity "case insensitive") + else() + set(_case_sensitivity "case sensitive") + endif() + + if(DEFINED arg_NAME_REGEX) + message(STATUS "[blt_print_variables] matching NAME_REGEX '${arg_NAME_REGEX}' (${_case_sensitivity})") + else() + set(arg_NAME_REGEX ".*") + endif() + + if(DEFINED arg_VALUE_REGEX) + message(STATUS "[blt_print_variables] matching VALUE_REGEX '${arg_VALUE_REGEX}' (${_case_sensitivity})") + else() + set(arg_VALUE_REGEX ".*") + endif() + + + # Note: 'if(DEFINED CACHE{var})' is only avaliable in CMake@3.14+ + set(_has_defined_cache FALSE) + if( ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.14.0") + set(_has_defined_cache TRUE) + endif() + + # Start with a sorted, unique list of all variables + get_cmake_property(_vars VARIABLES) + list (SORT _vars) + list (REMOVE_DUPLICATES _vars) + + # Filter and print each variable + foreach (_v ${_vars}) + # Apply regex to variable name, accounting for case sensitivity + set(_match_name FALSE) + if(arg_IGNORE_CASE) + string(TOUPPER ${_v} _v_upper) + string(REGEX MATCH ${arg_NAME_REGEX} _match_upper ${_v_upper}) + + string(TOLOWER ${_v} _v_lower) + string(REGEX MATCH ${arg_NAME_REGEX} _match_lower ${_v_lower}) + + if(_match_upper OR _match_lower) + set(_match_name TRUE) + endif() + else() + string(REGEX MATCH ${arg_NAME_REGEX} _match_name ${_v}) + endif() + + # Apply regex to variable value, accounting for case sensitivity + # Optimization: Only apply VALUE_REGEX to matched names + # Practicality: Only apply VALUE_REGEX to non-empty variables. + # This avoids the following CMake error: + # "string sub-command REGEX, mode MATCH regex ".*" matched an empty string" + set(_match_value FALSE) + if(_match_name AND ${_v}) + set(_val "${${_v}}") + if(arg_IGNORE_CASE) + string(TOUPPER "${_val}" _val_upper) + string(REGEX MATCH ${arg_VALUE_REGEX} _match_upper "${_val_upper}") + + string(TOLOWER "${_val}" _val_lower) + string(REGEX MATCH ${arg_VALUE_REGEX} _match_lower "${_val_lower}") + + if(_match_upper OR _match_lower) + set(_match_value TRUE) + endif() + else() + string(REGEX MATCH ${arg_VALUE_REGEX} _match_value "${_val}") + endif() + endif() + + # Format variable name and value and print + if (_match_name AND _match_value) + set(_v_print_name ${_v}) + # If it's a cache variable, wrap in "CACHE{}" + if(_has_defined_cache AND DEFINED CACHE{${_v}}) + # Append TYPE to cache variable name, if non-empty + get_property(_type CACHE ${_v} PROPERTY TYPE) + if(NOT "" STREQUAL "${_type}") + set(_v_print_name "CACHE{${_v}}:${_type}") + else() + set(_v_print_name "CACHE{${_v}}") + endif() + endif() + + message(STATUS "[blt_print_variables] ${_v_print_name} := ${${_v}}") + endif() + endforeach() + + message(STATUS "[blt_print_variables] ----------------------------------------------------------") + + unset(_case_sensitive) + unset(_vars) + unset(_has_defined_cache) + unset(_match_name) + unset(_match_value) +endmacro(blt_print_variables) + ##------------------------------------------------------------------------------ ## blt_export_tpl_targets(EXPORT NAMESPACE ) ## @@ -1402,6 +1519,7 @@ macro(blt_export_tpl_targets) endforeach() endmacro() + ##------------------------------------------------------------------------------ ## blt_convert_to_system_includes(TARGET ) ## @@ -1420,8 +1538,18 @@ macro(blt_convert_to_system_includes) message(FATAL_ERROR "TARGET is a required parameter for the blt_convert_to_system_includes macro.") endif() - get_target_property(_include_dirs ${arg_TARGET} INTERFACE_INCLUDE_DIRECTORIES) - set_property(TARGET ${arg_TARGET} APPEND PROPERTY INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "${_include_dirs}") + # PGI does not support -isystem + if(NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "PGI") + get_target_property(_include_dirs ${arg_TARGET} INTERFACE_INCLUDE_DIRECTORIES) + # Don't copy if the target had no include directories + if(_include_dirs) + # Clear previous value in INTERFACE_INCLUDE_DIRECTORIES so it is not doubled + # by target_include_directories + set_property(TARGET ${arg_TARGET} PROPERTY INTERFACE_INCLUDE_DIRECTORIES) + target_include_directories(${arg_TARGET} SYSTEM INTERFACE ${_include_dirs}) + endif() + endif() + unset(_include_dirs) endmacro() @@ -1429,6 +1557,7 @@ endmacro() ##------------------------------------------------------------------------------ ## blt_check_code_compiles(CODE_COMPILES ## VERBOSE_OUTPUT +## DEPENDS_ON ## SOURCE_STRING ) ## ## This macro checks if a snippet of C++ code compiles. @@ -1442,13 +1571,15 @@ endmacro() ## CODE_COMPILES A boolean variable the contains the compilation result. ## ## VERBOSE_OUTPUT Optional parameter to output debug information (Default: off) +## +## DEPENDS_ON Optional parameter for a list of additional dependencies ##------------------------------------------------------------------------------ macro(blt_check_code_compiles) set(options) set(singleValueArgs CODE_COMPILES VERBOSE_OUTPUT ) # NOTE: SOURCE_STRING must be a multiValueArg otherwise CMake removes all semi-colons - set(multiValueArgs SOURCE_STRING) + set(multiValueArgs DEPENDS_ON SOURCE_STRING) # Parse the arguments to the macro cmake_parse_arguments(arg @@ -1475,11 +1606,20 @@ macro(blt_check_code_compiles) string(RANDOM LENGTH 5 _rand) set(_fname ${CMAKE_CURRENT_BINARY_DIR}/_bltCheckCompiles${_rand}.cpp) file(WRITE ${_fname} "${arg_SOURCE_STRING}") - try_compile(${arg_CODE_COMPILES} + if(NOT DEFINED arg_DEPENDS_ON) + try_compile(${arg_CODE_COMPILES} + ${CMAKE_CURRENT_BINARY_DIR}/CMakeTmp + SOURCES ${_fname} + CXX_STANDARD ${CMAKE_CXX_STANDARD} + OUTPUT_VARIABLE _res) + else() + try_compile(${arg_CODE_COMPILES} ${CMAKE_CURRENT_BINARY_DIR}/CMakeTmp SOURCES ${_fname} CXX_STANDARD ${CMAKE_CXX_STANDARD} + LINK_LIBRARIES ${arg_DEPENDS_ON} OUTPUT_VARIABLE _res) + endif() file(REMOVE ${_fname}) if(${arg_VERBOSE_OUTPUT}) diff --git a/cmake/BLTOptions.cmake b/cmake/BLTOptions.cmake index ec4594537..08bf25db1 100644 --- a/cmake/BLTOptions.cmake +++ b/cmake/BLTOptions.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/BLTPrivateMacros.cmake b/cmake/BLTPrivateMacros.cmake index 34f19a625..8e787f365 100644 --- a/cmake/BLTPrivateMacros.cmake +++ b/cmake/BLTPrivateMacros.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -628,11 +628,11 @@ endmacro(blt_make_file_ext_regex) ## ## Filters source list by file extension into C/C++, Fortran, Python, and ## CMake source lists based on BLT_C_FILE_EXTS, BLT_Fortran_FILE_EXTS, -## and BLT_CMAKE_FILE_EXTS (global BLT variables). This filtering is -## case-insensitive. Files named "CMakeLists.txt" are also filtered here. -## Files with no extension or generator expressions that are not object -## libraries (of the form "$") will -## throw fatal errors. +## BLT_Python_FILE_EXTS and BLT_CMAKE_FILE_EXTS (global BLT variables). +## This filtering is case-insensitive. Files named "CMakeLists.txt" are +## also filtered here. Files with no extension or generator expressions +## that are not object libraries (of the form +## "$") will throw fatal errors. ## ------------------------------------------------------------------------------ macro(blt_split_source_list_by_language) @@ -690,11 +690,11 @@ macro(blt_split_source_list_by_language) if (DEFINED arg_Fortran_LIST) list(APPEND ${arg_Fortran_LIST} "${_file}") endif() - elseif("${_lower_file}" MATCHES "${BLT_Python_FILE_EXTS}") + elseif("${_lower_file}" MATCHES "${BLT_Python_FILE_REGEX}") if (DEFINED arg_Python_LIST) list(APPEND ${arg_Python_LIST} "${_file}") endif() - elseif("${_lower_file}" MATCHES "${BLT_CMAKE_EXTS}" OR "${_name}" STREQUAL "CMakeLists.txt") + elseif("${_lower_file}" MATCHES "${BLT_CMAKE_REGEX}" OR "${_name}" STREQUAL "CMakeLists.txt") if (DEFINED arg_CMAKE_LIST) list(APPEND ${arg_CMAKE_LIST} "${_file}") endif() @@ -707,41 +707,6 @@ macro(blt_split_source_list_by_language) endmacro(blt_split_source_list_by_language) -##------------------------------------------------------------------------------ -## blt_update_project_sources( TARGET_SOURCES ) -##------------------------------------------------------------------------------ -macro(blt_update_project_sources) - - set(options) - set(singleValueArgs) - set(multiValueArgs TARGET_SOURCES) - - # Parse the arguments - cmake_parse_arguments(arg "${options}" "${singleValueArgs}" - "${multiValueArgs}" ${ARGN} ) - - # Check arguments - if ( NOT DEFINED arg_TARGET_SOURCES ) - message( FATAL_ERROR "Must provide target sources" ) - endif() - - ## append the target source to the all project sources - foreach( src ${arg_TARGET_SOURCES} ) - if(IS_ABSOLUTE ${src}) - list(APPEND "${PROJECT_NAME}_ALL_SOURCES" "${src}") - else() - list(APPEND "${PROJECT_NAME}_ALL_SOURCES" - "${CMAKE_CURRENT_SOURCE_DIR}/${src}") - endif() - endforeach() - - set( "${PROJECT_NAME}_ALL_SOURCES" "${${PROJECT_NAME}_ALL_SOURCES}" - CACHE STRING "" FORCE ) - mark_as_advanced("${PROJECT_NAME}_ALL_SOURCES") - -endmacro(blt_update_project_sources) - - ##------------------------------------------------------------------------------ ## blt_filter_list( TO REGEX OPERATION ) ## diff --git a/cmake/SetupCodeChecks.cmake b/cmake/SetupCodeChecks.cmake index b35159451..bfcf04db3 100644 --- a/cmake/SetupCodeChecks.cmake +++ b/cmake/SetupCodeChecks.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/SetupCodeMetrics.cmake b/cmake/SetupCodeMetrics.cmake index 6933d482f..57044ead3 100644 --- a/cmake/SetupCodeMetrics.cmake +++ b/cmake/SetupCodeMetrics.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/SetupCompilerOptions.cmake b/cmake/SetupCompilerOptions.cmake index d78263694..c2af0ef4f 100644 --- a/cmake/SetupCompilerOptions.cmake +++ b/cmake/SetupCompilerOptions.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/SetupCompilerStandards.cmake b/cmake/SetupCompilerStandards.cmake index d8f70f3ac..de33b98ce 100644 --- a/cmake/SetupCompilerStandards.cmake +++ b/cmake/SetupCompilerStandards.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/SetupDocs.cmake b/cmake/SetupDocs.cmake index d0bb46c0e..f3ef290e3 100644 --- a/cmake/SetupDocs.cmake +++ b/cmake/SetupDocs.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/WrapAstyle.cmake.in b/cmake/WrapAstyle.cmake.in index 673151c19..eb60cb370 100644 --- a/cmake/WrapAstyle.cmake.in +++ b/cmake/WrapAstyle.cmake.in @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/clang-query-wrapper.py b/cmake/clang-query-wrapper.py index 630407e28..551929b72 100644 --- a/cmake/clang-query-wrapper.py +++ b/cmake/clang-query-wrapper.py @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/thirdparty/SetupCUDA.cmake b/cmake/thirdparty/SetupCUDA.cmake index 7dc73d224..d8d1ea214 100644 --- a/cmake/thirdparty/SetupCUDA.cmake +++ b/cmake/thirdparty/SetupCUDA.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -121,8 +121,9 @@ message(STATUS "CUDA Include Path: ${CUDA_INCLUDE_DIRS}") message(STATUS "CUDA Libraries: ${CUDA_LIBRARIES}") message(STATUS "CUDA Compile Flags: ${CMAKE_CUDA_FLAGS}") message(STATUS "CUDA Link Flags: ${CMAKE_CUDA_LINK_FLAGS}") -message(STATUS "CUDA Separable Compilation: ${CUDA_SEPARABLE_COMPILATION}") -message(STATUS "CUDA Link with NVCC: ${CUDA_LINK_WITH_NVCC}") +message(STATUS "BLT CUDA Separable Compilation: ${CUDA_SEPARABLE_COMPILATION}") +message(STATUS "CUDA Separable Compilation: ${CMAKE_CUDA_SEPARABLE_COMPILATION}") +message(STATUS "CUDA Link with NVCC: ${CUDA_LINK_WITH_NVCC}") message(STATUS "CUDA Implicit Link Libraries: ${CMAKE_CUDA_IMPLICIT_LINK_LIBRARIES}") message(STATUS "CUDA Implicit Link Directories: ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}") diff --git a/cmake/thirdparty/SetupHIP.cmake b/cmake/thirdparty/SetupHIP.cmake index 152342047..9f57ee0be 100644 --- a/cmake/thirdparty/SetupHIP.cmake +++ b/cmake/thirdparty/SetupHIP.cmake @@ -1,16 +1,13 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) -# Author: Noel Chalmers @ Advanced Micro Devices, Inc. -# Date: March 11, 2019 - ################################ # HIP ################################ -if (NOT ROCM_PATH) +if(NOT ROCM_PATH) find_path(ROCM_PATH hip ENV{ROCM_DIR} @@ -43,7 +40,7 @@ if(DEFINED AMDGPU_TARGETS) get_target_property(_hip_link_libs hip::device INTERFACE_LINK_LIBRARIES) foreach(_target ${AMDGPU_TARGETS}) - if (NOT "${CMAKE_HIP_ARCHITECTURES}" MATCHES "${_target}") + if(NOT "${CMAKE_HIP_ARCHITECTURES}" MATCHES "${_target}") set(_flag "--offload-arch=${_target}") set(_generator_compile_flag "$<$:SHELL:${_flag}>") set(_generator_link_flag "$<$:${_flag}>") @@ -65,14 +62,22 @@ endif() # hip targets must be global for aliases when created as imported targets set(_blt_hip_is_global On) -if (${BLT_EXPORT_THIRDPARTY}) +if(${BLT_EXPORT_THIRDPARTY}) set(_blt_hip_is_global Off) -endif () +endif() -blt_import_library(NAME blt_hip - COMPILE_FLAGS "--rocm-path=${ROCM_PATH}" - EXPORTABLE ${BLT_EXPORT_THIRDPARTY} - GLOBAL ${_blt_hip_is_global}) +# Guard against `--rocm-path` being added to crayftn less than version 15.0.0 due to +# invalid command line option error +if(CMAKE_Fortran_COMPILER_ID STREQUAL "Cray" AND CMAKE_Fortran_COMPILER_VERSION VERSION_LESS 15.0.0) + set(_blt_hip_compile_flags "$<$:SHELL:--rocm-path=${ROCM_PATH}>") +else() + set(_blt_hip_compile_flags "--rocm-path=${ROCM_PATH}") +endif() + +blt_import_library(NAME blt_hip + COMPILE_FLAGS ${_blt_hip_compile_flags} + EXPORTABLE ${BLT_EXPORT_THIRDPARTY} + GLOBAL ${_blt_hip_is_global}) # Hard-copy inheritable properties instead of depending on hip::device so that we can export all required # information in our target blt_hip @@ -81,10 +86,10 @@ blt_inherit_target_info(TO blt_hip FROM hip::device OBJECT FALSE) add_library(blt::hip ALIAS blt_hip) blt_import_library(NAME blt_hip_runtime - INCLUDES ${HIP_INCLUDE_DIRS} + INCLUDES ${HIP_INCLUDE_DIRS} TREAT_INCLUDES_AS_SYSTEM ON EXPORTABLE ${BLT_EXPORT_THIRDPARTY} - GLOBAL ${_blt_hip_is_global}) + GLOBAL ${_blt_hip_is_global}) blt_inherit_target_info(TO blt_hip_runtime FROM hip::host OBJECT FALSE) diff --git a/cmake/thirdparty/SetupMPI.cmake b/cmake/thirdparty/SetupMPI.cmake index b808a9fda..5da4c9319 100644 --- a/cmake/thirdparty/SetupMPI.cmake +++ b/cmake/thirdparty/SetupMPI.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/thirdparty/SetupOpenMP.cmake b/cmake/thirdparty/SetupOpenMP.cmake index a5235c789..e48ffcb7b 100644 --- a/cmake/thirdparty/SetupOpenMP.cmake +++ b/cmake/thirdparty/SetupOpenMP.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/cmake/thirdparty/SetupThirdParty.cmake b/cmake/thirdparty/SetupThirdParty.cmake index c8e6e27ed..002252ea9 100644 --- a/cmake/thirdparty/SetupThirdParty.cmake +++ b/cmake/thirdparty/SetupThirdParty.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/CMakeLists.txt b/docs/CMakeLists.txt index a2b62332a..e8765dd45 100644 --- a/docs/CMakeLists.txt +++ b/docs/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/api/code_check.rst b/docs/api/code_check.rst index 8e746b0f3..8b99e0e03 100644 --- a/docs/api/code_check.rst +++ b/docs/api/code_check.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/api/documentation.rst b/docs/api/documentation.rst index 0a607aee9..dd54b9c9b 100644 --- a/docs/api/documentation.rst +++ b/docs/api/documentation.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/api/git.rst b/docs/api/git.rst index 40443a19c..8f4f0e317 100644 --- a/docs/api/git.rst +++ b/docs/api/git.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/api/index.rst b/docs/api/index.rst index 3faa84f5b..399d1399a 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/api/target.rst b/docs/api/target.rst index a0b15eca3..d0a88bec1 100644 --- a/docs/api/target.rst +++ b/docs/api/target.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) @@ -13,9 +13,11 @@ blt_add_benchmark .. code-block:: cmake - blt_add_benchmark( NAME [name] - COMMAND [command] - NUM_MPI_TASKS [n]) + blt_add_benchmark( NAME [name] + COMMAND [command] + NUM_MPI_TASKS [n] + NUM_OMP_THREADS [n] + CONFIGURATIONS [config1 [config2...]]) Adds a benchmark to the project. @@ -28,6 +30,14 @@ COMMAND NUM_MPI_TASKS Indicates this is an MPI test and how many MPI tasks to use. +NUM_OMP_THREADS + Indicates this test requires the defined environment variable ``OMP_NUM_THREADS`` + set to the given variable. + +CONFIGURATIONS + Optionally set additional CTest configuration(s) for this test. Benchmark tests + will always be added to the ``Benchmark`` CTest configuration. + This macro adds a benchmark test to the ``Benchmark`` CTest configuration which can be run by the ``run_benchmarks`` build target. These tests are not run when you use the regular ``test`` build target. @@ -43,6 +53,9 @@ library in its ``DEPENDS_ON`` list. Any calls to this macro should be guarded with ``ENABLE_BENCHMARKS`` unless this option is always on in your build project. +If ``NUM_OMP_THREADS`` is given, this macro will set the environment variable ``OMP_NUM_THREADS`` +before running this test. This is done by appending to the CMake tests property. + .. note:: BLT provides a built-in Google Benchmark that is enabled by default if you set ``ENABLE_BENCHMARKS=ON`` and can be turned off with the option ``ENABLE_GBENCHMARK``. @@ -57,7 +70,7 @@ is always on in your build project. DEPENDS gbenchmark) blt_add_benchmark( NAME component_benchmark - COMMAND component_benchmark "--benchmark_min_time=0.0 --v=3 --benchmark_format=json") + COMMAND component_benchmark "--benchmark_min_time=0.0001s --v=3 --benchmark_format=json") endif() diff --git a/docs/api/target_properties.rst b/docs/api/target_properties.rst index 2c4bf652b..60139bd7f 100644 --- a/docs/api/target_properties.rst +++ b/docs/api/target_properties.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) @@ -190,6 +190,44 @@ Output is of the form for each property: blt_print_target_properties(TARGET foo CHILDREN TRUE PROPERTY_NAME_REGEX "CXX") blt_print_target_properties(TARGET foo PROPERTY_NAME_REGEX "CXX" PROPERTY_VALUE_REGEX "ON") +.. _blt_print_variables: + +blt_print_variables +~~~~~~~~~~~~~~~~~~~ + +.. code-block:: cmake + + blt_print_variables(NAME_REGEX + VALUE_REGEX + [IGNORE_CASE]) + +Prints variables and their values in the current scope, with optional +regex filtering on the variable names and values. + +NAME_REGEX + Regular expression to apply to variable names (all by default) + +VALUE_REGEX + Regular expression to apply to variable values (all by default) + +IGNORE_CASE + Optionally ignore case of variable names and values when filtering + + +Output is of the following form for each variable: + | [blt_print_variables] : + +Cache variables are marked as CACHE and will list their type, e.g. `CACHE{}:TYPE` + +.. code-block:: cmake + :caption: **Example** + :linenos: + + blt_print_variables() + blt_print_variables( NAME_REGEX "blt" IGNORE_CASE) + blt_print_variables( NAME_REGEX "_FOUND" VALUE_REGEX "^on$|^true$|^1$" IGNORE_CASE) + blt_print_variables( NAME_REGEX "LIB|LIBS|LIBRARY|LIBRARIES") + .. _blt_set_target_folder: blt_set_target_folder diff --git a/docs/api/utility.rst b/docs/api/utility.rst index 94fe70ca4..440bd0f9b 100644 --- a/docs/api/utility.rst +++ b/docs/api/utility.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/conf.py b/docs/conf.py index 96ab40c1f..380665cd9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/developer/index.rst b/docs/developer/index.rst index b668c3ef7..363d52734 100644 --- a/docs/developer/index.rst +++ b/docs/developer/index.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/developer/release_process.rst b/docs/developer/release_process.rst index a221c42c0..256398e6f 100644 --- a/docs/developer/release_process.rst +++ b/docs/developer/release_process.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/index.rst b/docs/index.rst index 2bd769631..4573eae3c 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/adding_tests.rst b/docs/tutorial/adding_tests.rst index 3b0f28b1c..21c93f2ae 100644 --- a/docs/tutorial/adding_tests.rst +++ b/docs/tutorial/adding_tests.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) @@ -236,8 +236,8 @@ you are modifying or adding code and need to understand how unit test details are working, for example. .. note:: - You can pass arguments to ctest via the ``TEST_ARGS`` parameter, e.g. - ``make test TEST_ARGS="..."`` + You can pass arguments to ctest via the ``ARGS`` parameter, e.g. + ``make test ARGS="..."`` Useful arguments include: -R diff --git a/docs/tutorial/advanced_topics.rst b/docs/tutorial/advanced_topics.rst index d623320b4..24dea19f9 100644 --- a/docs/tutorial/advanced_topics.rst +++ b/docs/tutorial/advanced_topics.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/bare_bones/CMakeLists.txt b/docs/tutorial/bare_bones/CMakeLists.txt index 1ce7baef6..43b762317 100644 --- a/docs/tutorial/bare_bones/CMakeLists.txt +++ b/docs/tutorial/bare_bones/CMakeLists.txt @@ -33,9 +33,9 @@ else() endif() endif() -# Default to C++11 if not set so GTest/GMock can build +# Default to C++14 if not set so GTest/GMock can build if (NOT BLT_CXX_STD) - set(BLT_CXX_STD "c++11" CACHE STRING "") + set(BLT_CXX_STD "c++14" CACHE STRING "") endif() include(${BLT_SOURCE_DIR}/SetupBLT.cmake) diff --git a/docs/tutorial/calc_pi/CMakeLists.txt b/docs/tutorial/calc_pi/CMakeLists.txt index ff353d603..29b1a2823 100644 --- a/docs/tutorial/calc_pi/CMakeLists.txt +++ b/docs/tutorial/calc_pi/CMakeLists.txt @@ -14,9 +14,9 @@ if(NOT BLT_SOURCE_DIR) set(BLT_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../..") endif() -# Default to C++11 if not set so GTest/GMock can build +# Default to C++14 if not set so GTest/GMock can build if (NOT BLT_CXX_STD) - set(BLT_CXX_STD "c++11" CACHE STRING "") + set(BLT_CXX_STD "c++14" CACHE STRING "") endif() include(${BLT_SOURCE_DIR}/SetupBLT.cmake) @@ -48,72 +48,75 @@ blt_add_executable( NAME example_2 DEPENDS_ON calc_pi) # _blt_tutorial_calcpi_example2_end -#------------------------------------------------------------------------------ -# Test 1: Creating an executable using gtest, using the executable via ctest. -#------------------------------------------------------------------------------ -# _blt_tutorial_calcpi_test1_executable_start -blt_add_executable( NAME test_1 - SOURCES test_1.cpp - DEPENDS_ON calc_pi gtest) -# _blt_tutorial_calcpi_test1_executable_end - -# _blt_tutorial_calcpi_test1_test_start -blt_add_test( NAME test_1 - COMMAND test_1) -# _blt_tutorial_calcpi_test1_test_end - -#------------------------------------------------------------------------------ -# Test 2: Add mpi version of calc_pi, and expand test 1 to also test -# the mpi version. -#------------------------------------------------------------------------------ -if(MPI_FOUND) -# _blt_tutorial_calcpi_test2_executable_start - blt_add_library( NAME calc_pi_mpi - HEADERS calc_pi_mpi.hpp calc_pi_mpi_exports.h - SOURCES calc_pi_mpi.cpp - DEPENDS_ON mpi) - - if(WIN32 AND BUILD_SHARED_LIBS) - target_compile_definitions(calc_pi_mpi PUBLIC WIN32_SHARED_LIBS) +if(ENABLE_GTEST) + #------------------------------------------------------------------------------ + # Test 1: Creating an executable using gtest, using the executable via ctest. + #------------------------------------------------------------------------------ + # _blt_tutorial_calcpi_test1_executable_start + blt_add_executable( NAME test_1 + SOURCES test_1.cpp + DEPENDS_ON calc_pi gtest) + # _blt_tutorial_calcpi_test1_executable_end + + # _blt_tutorial_calcpi_test1_test_start + blt_add_test( NAME test_1 + COMMAND test_1) + # _blt_tutorial_calcpi_test1_test_end + + + #------------------------------------------------------------------------------ + # Test 2: Add mpi version of calc_pi, and expand test 1 to also test + # the mpi version. + #------------------------------------------------------------------------------ + if(MPI_FOUND) + # _blt_tutorial_calcpi_test2_executable_start + blt_add_library( NAME calc_pi_mpi + HEADERS calc_pi_mpi.hpp calc_pi_mpi_exports.h + SOURCES calc_pi_mpi.cpp + DEPENDS_ON mpi) + + if(WIN32 AND BUILD_SHARED_LIBS) + target_compile_definitions(calc_pi_mpi PUBLIC WIN32_SHARED_LIBS) + endif() + + blt_add_executable( NAME test_2 + SOURCES test_2.cpp + DEPENDS_ON calc_pi calc_pi_mpi gtest) + # _blt_tutorial_calcpi_test2_executable_end + + # _blt_tutorial_calcpi_test2_test_start + blt_add_test( NAME test_2 + COMMAND test_2 + NUM_MPI_TASKS 2) # number of mpi tasks to use + # _blt_tutorial_calcpi_test2_test_end endif() - blt_add_executable( NAME test_2 - SOURCES test_2.cpp - DEPENDS_ON calc_pi calc_pi_mpi gtest) -# _blt_tutorial_calcpi_test2_executable_end - -# _blt_tutorial_calcpi_test2_test_start - blt_add_test( NAME test_2 - COMMAND test_2 - NUM_MPI_TASKS 2) # number of mpi tasks to use -# _blt_tutorial_calcpi_test2_test_end -endif() - -#------------------------------------------------------------------------------ -# Test 3: Add cuda version of calc_pi, and expand test 1 to also test -# the cuda version. -#------------------------------------------------------------------------------ -if(CUDA_FOUND) -# _blt_tutorial_calcpi_cuda_start - - blt_add_library( NAME calc_pi_cuda - HEADERS calc_pi_cuda.hpp calc_pi_cuda_exports.h - SOURCES calc_pi_cuda.cpp - DEPENDS_ON cuda) - - if(WIN32 AND BUILD_SHARED_LIBS) - target_compile_definitions(calc_pi_cuda PUBLIC WIN32_SHARED_LIBS) + #------------------------------------------------------------------------------ + # Test 3: Add cuda version of calc_pi, and expand test 1 to also test + # the cuda version. + #------------------------------------------------------------------------------ + if(CUDA_FOUND) + # _blt_tutorial_calcpi_cuda_start + + blt_add_library( NAME calc_pi_cuda + HEADERS calc_pi_cuda.hpp calc_pi_cuda_exports.h + SOURCES calc_pi_cuda.cpp + DEPENDS_ON cuda) + + if(WIN32 AND BUILD_SHARED_LIBS) + target_compile_definitions(calc_pi_cuda PUBLIC WIN32_SHARED_LIBS) + endif() + + blt_add_executable( NAME test_3 + SOURCES test_3.cpp + DEPENDS_ON calc_pi calc_pi_cuda gtest cuda_runtime) + + blt_add_test( NAME test_3 + COMMAND test_3) + # _blt_tutorial_calcpi_cuda_end endif() - blt_add_executable( NAME test_3 - SOURCES test_3.cpp - DEPENDS_ON calc_pi calc_pi_cuda gtest cuda_runtime) - - blt_add_test( NAME test_3 - COMMAND test_3) -# _blt_tutorial_calcpi_cuda_end -endif() - +endif() # endif ENABLE_GTEST #------------------------------------------------------------------------------ # Add Documentation Examples diff --git a/docs/tutorial/common_hpc_dependencies.rst b/docs/tutorial/common_hpc_dependencies.rst index a49fac15e..ff6e30dd6 100644 --- a/docs/tutorial/common_hpc_dependencies.rst +++ b/docs/tutorial/common_hpc_dependencies.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) @@ -38,9 +38,9 @@ Our next example, ``test_2``, builds and tests the ``calc_pi_mpi`` library, which uses MPI to parallelize the calculation over the integration intervals. To enable MPI, we set ``ENABLE_MPI``, ``MPI_C_COMPILER``, and ``MPI_CXX_COMPILER`` -in our host config file. Here is a snippet with these settings for LLNL's Pascal Cluster: +in our host config file. Here is a snippet with these settings for LLNL's Lassen Cluster: -.. literalinclude:: ../../host-configs/llnl/toss_3_x86_64_ib/gcc@4.9.3_nvcc.cmake +.. literalinclude:: ../../host-configs/llnl/toss_3_x86_64_ib/gcc@8.3.1.cmake :start-after: _blt_tutorial_mpi_config_start :end-before: _blt_tutorial_mpi_config_end :language: cmake @@ -101,9 +101,9 @@ or ``CUDA_HOST_COMPILER`` in previous versions. If you do not call ``enable_language(CUDA)``, BLT will set the appropriate host compiler variable for you and enable the CUDA language. -Here is a snippet with these settings for LLNL's Pascal Cluster: +Here is a snippet with these settings for LLNL's Lassen Cluster: -.. literalinclude:: ../../host-configs/llnl/toss_3_x86_64_ib/gcc@4.9.3_nvcc.cmake +.. literalinclude:: ../../host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++17.cmake :start-after: _blt_tutorial_cuda_config_start :end-before: _blt_tutorial_cuda_config_end :language: cmake diff --git a/docs/tutorial/creating_documentation.rst b/docs/tutorial/creating_documentation.rst index 5490dab12..5f433c764 100644 --- a/docs/tutorial/creating_documentation.rst +++ b/docs/tutorial/creating_documentation.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/creating_targets.rst b/docs/tutorial/creating_targets.rst index 661b66676..0e7badd0a 100644 --- a/docs/tutorial/creating_targets.rst +++ b/docs/tutorial/creating_targets.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/exporting_targets.rst b/docs/tutorial/exporting_targets.rst index 2d84caad9..bd01cf2cb 100644 --- a/docs/tutorial/exporting_targets.rst +++ b/docs/tutorial/exporting_targets.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/getting_started.rst b/docs/tutorial/getting_started.rst index 291d04957..94ca59f9a 100644 --- a/docs/tutorial/getting_started.rst +++ b/docs/tutorial/getting_started.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/host_configs.rst b/docs/tutorial/host_configs.rst index 2a92eae10..a7f412b5d 100644 --- a/docs/tutorial/host_configs.rst +++ b/docs/tutorial/host_configs.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/importing_targets.rst b/docs/tutorial/importing_targets.rst index 609c7b652..0cbeca1ac 100644 --- a/docs/tutorial/importing_targets.rst +++ b/docs/tutorial/importing_targets.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/index.rst b/docs/tutorial/index.rst index c3c549fab..6c1c0400a 100644 --- a/docs/tutorial/index.rst +++ b/docs/tutorial/index.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/object_libraries.rst b/docs/tutorial/object_libraries.rst index 3da59bc1c..94d191e17 100644 --- a/docs/tutorial/object_libraries.rst +++ b/docs/tutorial/object_libraries.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/portable_compiler_flags.rst b/docs/tutorial/portable_compiler_flags.rst index be3fc641a..9d6b62aa7 100644 --- a/docs/tutorial/portable_compiler_flags.rst +++ b/docs/tutorial/portable_compiler_flags.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/recommendations.rst b/docs/tutorial/recommendations.rst index 2e0cf6e0e..49d863c86 100644 --- a/docs/tutorial/recommendations.rst +++ b/docs/tutorial/recommendations.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/docs/tutorial/third_party_libraries.rst b/docs/tutorial/third_party_libraries.rst index 0e92b0baa..7c0907a7b 100644 --- a/docs/tutorial/third_party_libraries.rst +++ b/docs/tutorial/third_party_libraries.rst @@ -1,4 +1,4 @@ -.. # Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +.. # Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and .. # other BLT Project Developers. See the top-level LICENSE file for details .. # .. # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/host-configs/darwin/elcapitan-x86_64/naples-clang@7.3.0.cmake b/host-configs/darwin/elcapitan-x86_64/naples-clang@7.3.0.cmake index 8049cf7e0..5a642f545 100644 --- a/host-configs/darwin/elcapitan-x86_64/naples-clang@7.3.0.cmake +++ b/host-configs/darwin/elcapitan-x86_64/naples-clang@7.3.0.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_link_with_nvcc.cmake b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++14_export_tpls.cmake similarity index 62% rename from host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_link_with_nvcc.cmake rename to host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++14_export_tpls.cmake index be9a065d6..28c17b91b 100644 --- a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_link_with_nvcc.cmake +++ b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++14_export_tpls.cmake @@ -1,19 +1,17 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) #------------------------------------------------------------------------------ -# Example host-config file for the blue_os cluster at LLNL +# Example host-config file for the blue_os cluster at LLNL, specifically Lassen #------------------------------------------------------------------------------ # # This file provides CMake with paths / details for: -# C/C++, OpenMP, MPI, and Cuda +# C/C++: Clang with GCC 8.3.1 toolchain +# Cuda +# MPI # -# It demonstrates a more complex build, where the code is linked with nvcc. -#------------------------------------------------------------------------------ -# Warning: This host-config does not currently work with CMake@3.13 or above -# due to a linking error. #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ @@ -21,12 +19,10 @@ #------------------------------------------------------------------------------ # Use Clang compilers for C/C++ -set(CLANG_VERSION "clang-upstream-2019.08.15" CACHE STRING "") -set(CLANG_HOME "/usr/tce/packages/clang/${CLANG_VERSION}") - +set(CLANG_HOME "/usr/tce/packages/clang/clang-ibm-10.0.1-gcc-8.3.1") set(CMAKE_C_COMPILER "${CLANG_HOME}/bin/clang" CACHE PATH "") set(CMAKE_CXX_COMPILER "${CLANG_HOME}/bin/clang++" CACHE PATH "") -set(BLT_CXX_STD "c++11" CACHE STRING "") +set(BLT_CXX_STD "c++14" CACHE STRING "") # Disable Fortran set(ENABLE_FORTRAN OFF CACHE BOOL "") @@ -36,7 +32,7 @@ set(ENABLE_FORTRAN OFF CACHE BOOL "") #------------------------------------------------------------------------------ set(ENABLE_MPI ON CACHE BOOL "") -set(MPI_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-${CLANG_VERSION}") +set(MPI_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-clang-10.0.1-gcc-8.3.1") set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") @@ -44,31 +40,28 @@ set(MPIEXEC "${MPI_HOME}/bin/mpirun" CACHE PATH "") set(MPIEXEC_NUMPROC_FLAG "-np" CACHE PATH "") set(BLT_MPI_COMMAND_APPEND "mpibind" CACHE PATH "") -#------------------------------------------------------------------------------ -# OpenMP support -#------------------------------------------------------------------------------ -set(ENABLE_OPENMP ON CACHE BOOL "") - -# Override default link flags because linking with nvcc -set(OMP_HOME ${CLANG_HOME}/release) -set(BLT_OPENMP_LINK_FLAGS "-Xlinker -rpath -Xlinker ${OMP_HOME}/lib -L${OMP_HOME}/lib -lomp -lomptarget-nvptx" CACHE STRING "") - #------------------------------------------------------------------------------ # CUDA support #------------------------------------------------------------------------------ set(ENABLE_CUDA ON CACHE BOOL "") -set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.1.1" CACHE PATH "") +set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.2.0" CACHE PATH "") set(CMAKE_CUDA_COMPILER "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc" CACHE PATH "") -set(CMAKE_CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER} CACHE PATH "") +set(CMAKE_CUDA_HOST_COMPILER "${CMAKE_CXX_COMPILER}" CACHE PATH "") set(CMAKE_CUDA_ARCHITECTURES "70" CACHE STRING "") -set(_cuda_arch "sm_${CMAKE_CUDA_ARCHITECTURES}") -set(CMAKE_CUDA_FLAGS "-restrict -arch ${_cuda_arch} --expt-extended-lambda -G" CACHE STRING "" ) +set(CMAKE_CUDA_FLAGS "-restrict --expt-extended-lambda -G" CACHE STRING "") set(CUDA_SEPARABLE_COMPILATION ON CACHE BOOL "" ) -set(CUDA_LINK_WITH_NVCC ON CACHE BOOL "") # nvcc does not like gtest's 'pthreads' flag set(gtest_disable_pthreads ON CACHE BOOL "") +# Very specific fix for working around CMake adding implicit link directories returned by the BlueOS +# compilers to link CUDA executables +set(BLT_CMAKE_IMPLICIT_LINK_DIRECTORIES_EXCLUDE "/usr/tce/packages/gcc/gcc-4.9.3/lib64/gcc/powerpc64le-unknown-linux-gnu/4.9.3;/usr/tce/packages/gcc/gcc-4.9.3/lib64" CACHE STRING "") + +#------------------------------------------------------------------------------ +# Enable TPL export +#------------------------------------------------------------------------------ +set(BLT_EXPORT_THIRDPARTY ON CACHE BOOL "") diff --git a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_xlf.cmake b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++14_xlf.cmake similarity index 71% rename from host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_xlf.cmake rename to host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++14_xlf.cmake index a4513012b..f0606e28e 100644 --- a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_xlf.cmake +++ b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++14_xlf.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -20,12 +20,10 @@ #------------------------------------------------------------------------------ # Use Clang compilers for C/C++ -set(CLANG_VERSION "clang-upstream-2019.08.15" CACHE STRING "") -set(CLANG_HOME "/usr/tce/packages/clang/${CLANG_VERSION}") - +set(CLANG_HOME "/usr/tce/packages/clang/clang-ibm-10.0.1-gcc-8.3.1") set(CMAKE_C_COMPILER "${CLANG_HOME}/bin/clang" CACHE PATH "") set(CMAKE_CXX_COMPILER "${CLANG_HOME}/bin/clang++" CACHE PATH "") -set(BLT_CXX_STD "c++11" CACHE STRING "") +set(BLT_CXX_STD "c++14" CACHE STRING "") # Use XL compiler for Fortran set(ENABLE_FORTRAN ON CACHE BOOL "") @@ -36,18 +34,17 @@ set(CMAKE_Fortran_COMPILER "${XL_HOME}/bin/xlf2003" CACHE PATH "") #------------------------------------------------------------------------------ # MPI Support #------------------------------------------------------------------------------ - set(ENABLE_MPI ON CACHE BOOL "") -set(MPI_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-${CLANG_VERSION}") -set(MPI_Fortran_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-${XL_VERSION}") +set(MPI_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-clang-10.0.1-gcc-8.3.1") +set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") +set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") +set(MPI_Fortran_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-clang-10.0.1-gcc-8.3.1") set(MPI_Fortran_COMPILER "${MPI_Fortran_HOME}/bin/mpif90" CACHE PATH "") -set(MPIEXEC "${MPI_HOME}/bin/mpirun" CACHE PATH "") -set(MPIEXEC_NUMPROC_FLAG "-np" CACHE PATH "") +set(MPIEXEC "${MPI_HOME}/bin/mpirun" CACHE PATH "") +set(MPIEXEC_NUMPROC_FLAG "-np" CACHE PATH "") set(BLT_MPI_COMMAND_APPEND "mpibind" CACHE PATH "") #------------------------------------------------------------------------------ @@ -65,16 +62,19 @@ set(BLT_CMAKE_IMPLICIT_LINK_LIBRARIES_EXCLUDE "xlomp_ser" CACHE STRING "") #_blt_tutorial_useful_cuda_flags_start set(ENABLE_CUDA ON CACHE BOOL "") -set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.1.1" CACHE PATH "") +set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.2.0" CACHE PATH "") set(CMAKE_CUDA_COMPILER "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc" CACHE PATH "") -set(CMAKE_CUDA_HOST_COMPILER "${MPI_CXX_COMPILER}" CACHE PATH "") +set(CMAKE_CUDA_HOST_COMPILER "${CMAKE_CXX_COMPILER}" CACHE PATH "") set(CMAKE_CUDA_ARCHITECTURES "70" CACHE STRING "") -set(_cuda_arch "sm_${CMAKE_CUDA_ARCHITECTURES}") -set(CMAKE_CUDA_FLAGS "-restrict -arch ${_cuda_arch} --expt-extended-lambda -G" CACHE STRING "") +set(CMAKE_CUDA_FLAGS "-restrict --expt-extended-lambda -G" CACHE STRING "") set(CUDA_SEPARABLE_COMPILATION ON CACHE BOOL "" ) # nvcc does not like gtest's 'pthreads' flag set(gtest_disable_pthreads ON CACHE BOOL "") #_blt_tutorial_useful_cuda_flags_end + +# Very specific fix for working around CMake adding implicit link directories returned by the BlueOS +# compilers to link CUDA executables +set(BLT_CMAKE_IMPLICIT_LINK_DIRECTORIES_EXCLUDE "/usr/tce/packages/gcc/gcc-4.9.3/lib64/gcc/powerpc64le-unknown-linux-gnu/4.9.3;/usr/tce/packages/gcc/gcc-4.9.3/lib64" CACHE STRING "") diff --git a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++17.cmake b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++17.cmake similarity index 54% rename from host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++17.cmake rename to host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++17.cmake index b29b15af8..989a7e6c6 100644 --- a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++17.cmake +++ b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++17.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -14,54 +14,50 @@ # #------------------------------------------------------------------------------ -#--------------------------------------- +#------------------------------------------------------------------------------ # Compilers -#--------------------------------------- - -set(_CLANG_VERSION "clang-upstream-2019.08.15") -set(_CLANG_DIR "/usr/tce/packages/clang/${_CLANG_VERSION}") -set(_GCC_DIR "/usr/tce/packages/gcc/gcc-8.3.1") - -set(CMAKE_C_COMPILER "${_CLANG_DIR}/bin/clang" CACHE PATH "") -set(CMAKE_CXX_COMPILER "${_CLANG_DIR}/bin/clang++" CACHE PATH "") +#------------------------------------------------------------------------------ +set(CLANG_HOME "/usr/tce/packages/clang/clang-ibm-10.0.1-gcc-8.3.1") +set(CMAKE_C_COMPILER "${CLANG_HOME}/bin/clang" CACHE PATH "") +set(CMAKE_CXX_COMPILER "${CLANG_HOME}/bin/clang++" CACHE PATH "") set(BLT_CXX_STD "c++17" CACHE STRING "") -set(CMAKE_C_FLAGS "--gcc-toolchain=${_GCC_DIR}" CACHE PATH "") -set(CMAKE_CXX_FLAGS "--gcc-toolchain=${_GCC_DIR}" CACHE PATH "") - -set(BLT_EXE_LINKER_FLAGS " -Wl,-rpath,${_GCC_DIR}/lib" CACHE PATH "Adds a missing libstdc++ rpath") +# Disable Fortran +set(ENABLE_FORTRAN OFF CACHE BOOL "") -#--------------------------------------- -# MPI -#--------------------------------------- +#------------------------------------------------------------------------------ +# MPI Support +#------------------------------------------------------------------------------ set(ENABLE_MPI ON CACHE BOOL "") -set(_MPI_BASE_DIR "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-${_CLANG_VERSION}") +set(MPI_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-clang-10.0.1-gcc-8.3.1") +set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") +set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_C_COMPILER "${_MPI_BASE_DIR}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${_MPI_BASE_DIR}/bin/mpicxx" CACHE PATH "") +set(MPIEXEC "${MPI_HOME}/bin/mpirun" CACHE PATH "") +set(MPIEXEC_NUMPROC_FLAG "-np" CACHE PATH "") +set(BLT_MPI_COMMAND_APPEND "mpibind" CACHE PATH "") #------------------------------------------------------------------------------ -# Cuda +# CUDA support #------------------------------------------------------------------------------ - +# _blt_tutorial_cuda_config_start set(ENABLE_CUDA ON CACHE BOOL "") -set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.1.1" CACHE PATH "") - +set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.2.0" CACHE PATH "") set(CMAKE_CUDA_COMPILER "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc" CACHE PATH "") set(CMAKE_CUDA_HOST_COMPILER "${CMAKE_CXX_COMPILER}" CACHE PATH "") set(CMAKE_CUDA_ARCHITECTURES "70" CACHE STRING "") -set(_cuda_arch "sm_${CMAKE_CUDA_ARCHITECTURES}") -set(CMAKE_CUDA_FLAGS "-Xcompiler=--gcc-toolchain=${_GCC_DIR} -restrict -arch ${_cuda_arch} --expt-extended-lambda -G" CACHE STRING "") +set(CMAKE_CUDA_FLAGS "-restrict --expt-extended-lambda -G" CACHE STRING "") set(CUDA_SEPARABLE_COMPILATION ON CACHE BOOL "" ) +# _blt_tutorial_cuda_config_end + # nvcc does not like gtest's 'pthreads' flag set(gtest_disable_pthreads ON CACHE BOOL "") -set(ENABLE_GTEST_DEATH_TESTS OFF CACHE BOOL "") # Very specific fix for working around CMake adding implicit link directories returned by the BlueOS # compilers to link CUDA executables diff --git a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++17_no_separable.cmake b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++17_no_separable.cmake similarity index 53% rename from host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++17_no_separable.cmake rename to host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++17_no_separable.cmake index ccc031b5e..2de266a81 100644 --- a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++17_no_separable.cmake +++ b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@10.0.1_nvcc_c++17_no_separable.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -14,52 +14,47 @@ # #------------------------------------------------------------------------------ -#--------------------------------------- +#------------------------------------------------------------------------------ # Compilers -#--------------------------------------- - -set(_CLANG_VERSION "clang-upstream-2019.08.15") -set(_CLANG_DIR "/usr/tce/packages/clang/${_CLANG_VERSION}") -set(_GCC_DIR "/usr/tce/packages/gcc/gcc-8.3.1") - -set(CMAKE_C_COMPILER "${_CLANG_DIR}/bin/clang" CACHE PATH "") -set(CMAKE_CXX_COMPILER "${_CLANG_DIR}/bin/clang++" CACHE PATH "") +#------------------------------------------------------------------------------ +set(CLANG_HOME "/usr/tce/packages/clang/clang-ibm-10.0.1-gcc-8.3.1") +set(CMAKE_C_COMPILER "${CLANG_HOME}/bin/clang" CACHE PATH "") +set(CMAKE_CXX_COMPILER "${CLANG_HOME}/bin/clang++" CACHE PATH "") set(BLT_CXX_STD "c++17" CACHE STRING "") -set(CMAKE_C_FLAGS "--gcc-toolchain=${_GCC_DIR}" CACHE PATH "") -set(CMAKE_CXX_FLAGS "--gcc-toolchain=${_GCC_DIR}" CACHE PATH "") - -set(BLT_EXE_LINKER_FLAGS " -Wl,-rpath,${_GCC_DIR}/lib" CACHE PATH "Adds a missing libstdc++ rpath") +# Disable Fortran +set(ENABLE_FORTRAN OFF CACHE BOOL "") -#--------------------------------------- -# MPI -#--------------------------------------- +#------------------------------------------------------------------------------ +# MPI Support +#------------------------------------------------------------------------------ set(ENABLE_MPI ON CACHE BOOL "") -set(_MPI_BASE_DIR "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-${_CLANG_VERSION}") +set(MPI_HOME "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-clang-10.0.1-gcc-8.3.1") +set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") +set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_C_COMPILER "${_MPI_BASE_DIR}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${_MPI_BASE_DIR}/bin/mpicxx" CACHE PATH "") +set(MPIEXEC "${MPI_HOME}/bin/mpirun" CACHE PATH "") +set(MPIEXEC_NUMPROC_FLAG "-np" CACHE PATH "") +set(BLT_MPI_COMMAND_APPEND "mpibind" CACHE PATH "") #------------------------------------------------------------------------------ -# Cuda +# CUDA support #------------------------------------------------------------------------------ - set(ENABLE_CUDA ON CACHE BOOL "") -set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.1.1" CACHE PATH "") - +set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.2.0" CACHE PATH "") set(CMAKE_CUDA_COMPILER "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc" CACHE PATH "") set(CMAKE_CUDA_HOST_COMPILER "${CMAKE_CXX_COMPILER}" CACHE PATH "") set(CMAKE_CUDA_ARCHITECTURES "70" CACHE STRING "") -set(_cuda_arch "sm_${CMAKE_CUDA_ARCHITECTURES}") -set(CMAKE_CUDA_FLAGS "-Xcompiler=--gcc-toolchain=${_GCC_DIR} -restrict -arch ${_cuda_arch} --expt-extended-lambda -G" CACHE STRING "") +set(CMAKE_CUDA_FLAGS "-restrict --expt-extended-lambda -G" CACHE STRING "") + +set(CUDA_SEPARABLE_COMPILATION OFF CACHE BOOL "" ) # nvcc does not like gtest's 'pthreads' flag set(gtest_disable_pthreads ON CACHE BOOL "") -set(ENABLE_GTEST_DEATH_TESTS OFF CACHE BOOL "") # Very specific fix for working around CMake adding implicit link directories returned by the BlueOS # compilers to link CUDA executables diff --git a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++14-export-tpls.cmake b/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++14-export-tpls.cmake deleted file mode 100644 index 8563e153c..000000000 --- a/host-configs/llnl/blueos_3_ppc64le_ib_p9/clang@upstream_nvcc_c++14-export-tpls.cmake +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example host-config file for the blue_os cluster at LLNL, specifically Lassen -#------------------------------------------------------------------------------ -# -# This file provides CMake with paths / details for: -# C/C++: Clang with GCC 8.3.1 toolchain -# Cuda -# MPI -# -#------------------------------------------------------------------------------ - -#--------------------------------------- -# Compilers -#--------------------------------------- - -set(_CLANG_VERSION "clang-upstream-2019.08.15") -set(_CLANG_DIR "/usr/tce/packages/clang/${_CLANG_VERSION}") -set(_GCC_DIR "/usr/tce/packages/gcc/gcc-8.3.1") - -set(CMAKE_C_COMPILER "${_CLANG_DIR}/bin/clang" CACHE PATH "") -set(CMAKE_CXX_COMPILER "${_CLANG_DIR}/bin/clang++" CACHE PATH "") - -set(BLT_CXX_STD "c++14" CACHE STRING "") - -set(CMAKE_C_FLAGS "--gcc-toolchain=${_GCC_DIR}" CACHE PATH "") -set(CMAKE_CXX_FLAGS "--gcc-toolchain=${_GCC_DIR}" CACHE PATH "") - -set(BLT_EXE_LINKER_FLAGS " -Wl,-rpath,${_GCC_DIR}/lib" CACHE PATH "Adds a missing libstdc++ rpath") - -#--------------------------------------- -# MPI -#--------------------------------------- -set(ENABLE_MPI ON CACHE BOOL "") - -set(_MPI_BASE_DIR "/usr/tce/packages/spectrum-mpi/spectrum-mpi-rolling-release-${_CLANG_VERSION}") - -set(MPI_C_COMPILER "${_MPI_BASE_DIR}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${_MPI_BASE_DIR}/bin/mpicxx" CACHE PATH "") - -#------------------------------------------------------------------------------ -# Cuda -#------------------------------------------------------------------------------ - -set(ENABLE_CUDA ON CACHE BOOL "") - -set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.1.1" CACHE PATH "") - -set(CMAKE_CUDA_COMPILER "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc" CACHE PATH "") -set(CMAKE_CUDA_HOST_COMPILER "${CMAKE_CXX_COMPILER}" CACHE PATH "") - -set(CMAKE_CUDA_ARCHITECTURES "70" CACHE STRING "") -set(_cuda_arch "sm_${CMAKE_CUDA_ARCHITECTURES}") -set(CMAKE_CUDA_FLAGS "-Xcompiler=--gcc-toolchain=${_GCC_DIR} -restrict -arch ${_cuda_arch} -std=${BLT_CXX_STD} --expt-extended-lambda -G" CACHE STRING "") - -set(CUDA_SEPARABLE_COMPILATION ON CACHE BOOL "" ) - -# nvcc does not like gtest's 'pthreads' flag -set(gtest_disable_pthreads ON CACHE BOOL "") -set(ENABLE_GTEST_DEATH_TESTS OFF CACHE BOOL "") - -# Very specific fix for working around CMake adding implicit link directories returned by the BlueOS -# compilers to link CUDA executables -set(BLT_CMAKE_IMPLICIT_LINK_DIRECTORIES_EXCLUDE "/usr/tce/packages/gcc/gcc-4.9.3/lib64/gcc/powerpc64le-unknown-linux-gnu/4.9.3;/usr/tce/packages/gcc/gcc-4.9.3/lib64" CACHE STRING "") - -#------------------------------------------------------------------------------ -# Enable TPL export -#------------------------------------------------------------------------------ -set(BLT_EXPORT_THIRDPARTY ON CACHE BOOL "") \ No newline at end of file diff --git a/host-configs/llnl/blueos_3_ppc64le_ib_p9/pgi@20.4_nvcc.cmake b/host-configs/llnl/blueos_3_ppc64le_ib_p9/pgi@20.4_nvcc.cmake deleted file mode 100644 index 5750e57fc..000000000 --- a/host-configs/llnl/blueos_3_ppc64le_ib_p9/pgi@20.4_nvcc.cmake +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example host-config file for using PGI and CUDA -#------------------------------------------------------------------------------ -set (CMAKE_CXX_COMPILER "/usr/tce/packages/pgi/pgi-20.4/bin/pgc++" CACHE PATH "") -set (CMAKE_C_COMPILER "/usr/tce/packages/pgi/pgi-20.4/bin/pgcc" CACHE PATH "") - -set(ENABLE_FORTRAN OFF CACHE BOOL "") -set(ENABLE_MPI OFF CACHE BOOL "") -set(ENABLE_OPENMP OFF CACHE BOOL "") - -set(ENABLE_CUDA ON CACHE BOOL "") - -set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-11.1.1" CACHE PATH "") -set(CMAKE_CUDA_COMPILER "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc" CACHE PATH "") -set(CMAKE_CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER} CACHE PATH "") - -set(CUDA_SEPARABLE_COMPILATION ON CACHE BOOL "" ) - -set (_cuda_arch "sm_70") -set (CMAKE_CUDA_FLAGS "-restrict -arch ${_cuda_arch} -std=c++11 --expt-extended-lambda -G" CACHE STRING "" ) diff --git a/host-configs/llnl/toss_3_x86_64_ib/clang@6.0.0-static-analysis.cmake b/host-configs/llnl/toss_3_x86_64_ib/clang@6.0.0-static-analysis.cmake deleted file mode 100644 index d0c2b48eb..000000000 --- a/host-configs/llnl/toss_3_x86_64_ib/clang@6.0.0-static-analysis.cmake +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example host-config file for the quartz cluster at LLNL -#------------------------------------------------------------------------------ -# -# This file provides CMake with paths / details for: -# C,C++, & Fortran compilers + MPI -#------------------------------------------------------------------------------ -# clang-4.0.0 / gfortran@4.9.3 compilers -# Uses clang's 'libc++' instead of 'libstdc++' - -set(CLANG_HOME "/usr/tce/packages/clang/clang-6.0.0") -set(GNU_HOME "/usr/tce/packages/gcc/gcc-4.9.3") - -# c compiler -set(CMAKE_C_COMPILER "${CLANG_HOME}/bin/clang" CACHE PATH "") - -# cpp compiler -set(CMAKE_CXX_COMPILER "${CLANG_HOME}/bin/clang++" CACHE PATH "") - -# fortran support -set(ENABLE_FORTRAN ON CACHE BOOL "") - -# fortran compiler -set(CMAKE_Fortran_COMPILER "${GNU_HOME}/bin/gfortran" CACHE PATH "") - -#------------------------------------------------------------------------------ -# Extra flags -#------------------------------------------------------------------------------ - -# Use clang's libc++ instead of libstdc++ -set(BLT_CXX_FLAGS "-stdlib=libc++" CACHE STRING "") -set(gtest_defines "-DGTEST_HAS_CXXABI_H_=0" CACHE STRING "") - -#------------------------------------------------------------------------------ -# Static Analysis Support -#------------------------------------------------------------------------------ -set(ClangQuery_DIR ${CLANG_HOME}/bin) -set(ENABLE_CLANGQUERY ON CACHE BOOL "") - -set(ClangTidy_DIR ${CLANG_HOME}/bin) -set(ENABLE_CLANGTIDY ON CACHE BOOL "") - -#------------------------------------------------------------------------------ -# MPI Support -#------------------------------------------------------------------------------ -set(ENABLE_MPI ON CACHE BOOL "") - -set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3-clang-6.0.0" CACHE PATH "") -set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_Fortran_COMPILER "${MPI_HOME}/bin/mpifort" CACHE PATH "") - -set(MPIEXEC "/usr/bin/srun" CACHE PATH "") -set(MPIEXEC_NUMPROC_FLAG "-n" CACHE PATH "") diff --git a/host-configs/llnl/toss_3_x86_64_ib/gcc@4.9.3_nvcc.cmake b/host-configs/llnl/toss_3_x86_64_ib/gcc@4.9.3_nvcc.cmake deleted file mode 100644 index c085fc10a..000000000 --- a/host-configs/llnl/toss_3_x86_64_ib/gcc@4.9.3_nvcc.cmake +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example host-config file for the Pascal cluster at LLNL -#------------------------------------------------------------------------------ -# This file provides CMake with paths / details for: -# C,C++, & Fortran compilers + MPI & CUDA -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------ -# gcc@4.9.3 compilers -#------------------------------------------------------------------------------ -# _blt_tutorial_compiler_config_start -set(GCC_HOME "/usr/tce") -set(CMAKE_C_COMPILER "${GCC_HOME}/bin/gcc" CACHE PATH "") -set(CMAKE_CXX_COMPILER "${GCC_HOME}/bin/g++" CACHE PATH "") - -# Fortran support -set(ENABLE_FORTRAN ON CACHE BOOL "") -set(CMAKE_Fortran_COMPILER "${GCC_HOME}/bin/gfortran" CACHE PATH "") -# _blt_tutorial_compiler_config_end - -#------------------------------------------------------------------------------ -# MPI Support -#------------------------------------------------------------------------------ -# _blt_tutorial_mpi_config_start -set(ENABLE_MPI ON CACHE BOOL "") - -set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3-gcc-4.9.3/") -set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") - -set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") - -set(MPI_Fortran_COMPILER "${MPI_HOME}/bin/mpif90" CACHE PATH "") -# _blt_tutorial_mpi_config_end - -#------------------------------------------------------------------------------ -# CUDA support -#------------------------------------------------------------------------------ -# _blt_tutorial_cuda_config_start -set(ENABLE_CUDA ON CACHE BOOL "") - -set(CUDA_TOOLKIT_ROOT_DIR "/usr/tce/packages/cuda/cuda-10.1.168" CACHE PATH "") -set(CMAKE_CUDA_COMPILER "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc" CACHE PATH "") -set(CMAKE_CUDA_HOST_COMPILER "${CMAKE_CXX_COMPILER}" CACHE PATH "") - -set(CMAKE_CUDA_ARCHITECTURES "70" CACHE STRING "") -set(_cuda_arch "sm_${CMAKE_CUDA_ARCHITECTURES}") -set(CMAKE_CUDA_FLAGS "-restrict -arch ${_cuda_arch} -std=c++11 --expt-extended-lambda -G" - CACHE STRING "") - -set(CUDA_SEPARABLE_COMPILATION ON CACHE BOOL "") - -# _blt_tutorial_cuda_config_end - diff --git a/host-configs/llnl/toss_3_x86_64_ib/intel-oneapi@2021.3-c++17.cmake b/host-configs/llnl/toss_3_x86_64_ib/intel-oneapi@2021.3-c++17.cmake deleted file mode 100644 index 7a386a2b3..000000000 --- a/host-configs/llnl/toss_3_x86_64_ib/intel-oneapi@2021.3-c++17.cmake +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example host-config file for the quartz cluster at LLNL -#------------------------------------------------------------------------------ -# -# This file provides CMake with paths / details for: -# C,C++, & Fortran compilers + MPI -# -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------ -# intel-oneapi.2021.3 compilers -#------------------------------------------------------------------------------ - -set(INTELLLVM_VERSION "intel-oneapi.2021.3") -set(INTELLLVM_HOME "/usr/tce/packages/intel/${INTELLLVM_VERSION}") - -# c compiler -set(CMAKE_C_COMPILER "${INTELLLVM_HOME}/bin/icx" CACHE PATH "") - -# cpp compiler -set(CMAKE_CXX_COMPILER "${INTELLLVM_HOME}/bin/icpx" CACHE PATH "") - -# fortran support -set(ENABLE_FORTRAN ON CACHE BOOL "") - -# fortran compiler -set(CMAKE_Fortran_COMPILER "${INTELLLVM_HOME}/bin/ifx" CACHE PATH "") - -#------------------------------------------------------------------------------ -# Extra flags -#------------------------------------------------------------------------------ - -set(BLT_CXX_STD "c++17") - -# Use non-system default stdlib -set(GCC_VERSION "gcc-9.3.1") -# Note: gcc-8.3.1 and above need the "/rh" directory. Below that version do not. -set(GCC_HOME "/usr/tce/packages/gcc/${GCC_VERSION}/rh") - -set(BLT_C_FLAGS "--gcc-toolchain=${GCC_HOME}" CACHE STRING "") -set(BLT_CXX_FLAGS "--gcc-toolchain=${GCC_HOME}" CACHE STRING "") -set(BLT_FORTRAN_FLAGS "-gcc-name=${GCC_HOME}/bin/gcc" CACHE STRING "") - -#------------------------------------------------------------------------------ -# MPI Support -#------------------------------------------------------------------------------ -set(ENABLE_MPI ON CACHE BOOL "") - -set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3.6-${INTELLLVM_VERSION}" CACHE PATH "") - -set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_Fortran_COMPILER "${MPI_HOME}/bin/mpif90" CACHE PATH "") - -set(MPIEXEC "/usr/bin/srun" CACHE PATH "") -set(MPIEXEC_NUMPROC_FLAG "-n" CACHE PATH "") diff --git a/host-configs/llnl/toss_3_x86_64_ib/pgi@20.1.cmake b/host-configs/llnl/toss_3_x86_64_ib/pgi@20.1.cmake deleted file mode 100644 index 690df7b57..000000000 --- a/host-configs/llnl/toss_3_x86_64_ib/pgi@20.1.cmake +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example pgi@20.1 host-config for LLNL toss3 machines -#------------------------------------------------------------------------------ - -set(COMPILER_HOME "/usr/tce/packages/pgi/pgi-20.1") - -# c compiler -set(CMAKE_C_COMPILER "${COMPILER_HOME}/bin/pgcc" CACHE PATH "") - -# cpp compiler -set(CMAKE_CXX_COMPILER "${COMPILER_HOME}/bin/pgc++" CACHE PATH "") - -# fortran support -set(ENABLE_FORTRAN ON CACHE BOOL "") - -# fortran support -set(CMAKE_Fortran_COMPILER "${COMPILER_HOME}/bin/pgfortran" CACHE PATH "") - -#------------------------------------------------------------------------------ -# Extra options and flags -#------------------------------------------------------------------------------ - -set(ENABLE_OPENMP ON CACHE BOOL "") - - -#------------------------------------------------------------------------------ -# MPI Support -#------------------------------------------------------------------------------ - -set(ENABLE_MPI ON CACHE BOOL "") - -set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3-pgi-20.1") - -set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_Fortran_COMPILER "${MPI_HOME}/bin/mpif90" CACHE PATH "") -set(MPIEXEC "/usr/bin/srun" CACHE PATH "") -set(MPIEXEC_NUMPROC_FLAG "-n" CACHE PATH "") diff --git a/host-configs/llnl/toss_3_x86_64_ib/clang@4.0.0-libcxx.cmake b/host-configs/llnl/toss_4_x86_64_ib/clang@14.0.6.cmake similarity index 74% rename from host-configs/llnl/toss_3_x86_64_ib/clang@4.0.0-libcxx.cmake rename to host-configs/llnl/toss_4_x86_64_ib/clang@14.0.6.cmake index 51bac1a1a..f4c0fead9 100644 --- a/host-configs/llnl/toss_3_x86_64_ib/clang@4.0.0-libcxx.cmake +++ b/host-configs/llnl/toss_4_x86_64_ib/clang@14.0.6.cmake @@ -1,20 +1,19 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) #------------------------------------------------------------------------------ -# Example host-config file for the quartz cluster at LLNL +# Example host-config file for a cluster on a toss4 platform (e.g. quartz) at LLNL #------------------------------------------------------------------------------ # # This file provides CMake with paths / details for: # C,C++, & Fortran compilers + MPI #------------------------------------------------------------------------------ -# clang-4.0.0 / gfortran@4.9.3 compilers -# Uses clang's 'libc++' instead of 'libstdc++' +# clang-14.0.6 compilers -set(CLANG_HOME "/usr/tce/packages/clang/clang-4.0.0") -set(GNU_HOME "/usr/tce/packages/gcc/gcc-4.9.3") +set(CLANG_VERSION "clang-14.0.6") +set(CLANG_HOME "/usr/tce/packages/clang/${CLANG_VERSION}") # c compiler set(CMAKE_C_COMPILER "${CLANG_HOME}/bin/clang" CACHE PATH "") @@ -29,23 +28,23 @@ set(ENABLE_FORTRAN ON CACHE BOOL "") set(CMAKE_Fortran_COMPILER "${GNU_HOME}/bin/gfortran" CACHE PATH "") #------------------------------------------------------------------------------ -# Extra flags +# Static Analysis Support #------------------------------------------------------------------------------ +set(ClangQuery_DIR ${CLANG_HOME}/bin) +set(ENABLE_CLANGQUERY ON CACHE BOOL "") -# Use clang's libc++ instead of libstdc++ -set(BLT_CXX_FLAGS "-stdlib=libc++" CACHE STRING "") -set(gtest_defines "-DGTEST_HAS_CXXABI_H_=0" CACHE STRING "") +set(ClangTidy_DIR ${CLANG_HOME}/bin) +set(ENABLE_CLANGTIDY ON CACHE BOOL "") #------------------------------------------------------------------------------ # MPI Support #------------------------------------------------------------------------------ set(ENABLE_MPI ON CACHE BOOL "") -set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3-clang-4.0.0" CACHE PATH "") +set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3.6-${CLANG_VERSION}" CACHE PATH "") set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") set(MPI_Fortran_COMPILER "${MPI_HOME}/bin/mpifort" CACHE PATH "") set(MPIEXEC "/usr/bin/srun" CACHE PATH "") set(MPIEXEC_NUMPROC_FLAG "-n" CACHE PATH "") - diff --git a/host-configs/llnl/toss_3_x86_64_ib/gcc@8.3.1-export-tpls.cmake b/host-configs/llnl/toss_4_x86_64_ib/gcc@10.3.1-export-tpls.cmake similarity index 88% rename from host-configs/llnl/toss_3_x86_64_ib/gcc@8.3.1-export-tpls.cmake rename to host-configs/llnl/toss_4_x86_64_ib/gcc@10.3.1-export-tpls.cmake index a552b738f..ac29746c3 100644 --- a/host-configs/llnl/toss_3_x86_64_ib/gcc@8.3.1-export-tpls.cmake +++ b/host-configs/llnl/toss_4_x86_64_ib/gcc@10.3.1-export-tpls.cmake @@ -1,10 +1,10 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) #------------------------------------------------------------------------------ -# Example host-config file for the quartz cluster at LLNL +# Example host-config file for a cluster on a toss4 platform (e.g. quartz) at LLNL #------------------------------------------------------------------------------ # # This file provides CMake with paths / details for: @@ -13,10 +13,10 @@ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ -# gcc@8.3.1 compilers +# gcc@10.3.1 compilers #------------------------------------------------------------------------------ -set(GCC_VERSION "gcc-8.3.1") +set(GCC_VERSION "gcc-10.3.1") set(GCC_HOME "/usr/tce/packages/gcc/${GCC_VERSION}") # c compiler @@ -36,7 +36,7 @@ set(CMAKE_Fortran_COMPILER "${GCC_HOME}/bin/gfortran" CACHE PATH "") #------------------------------------------------------------------------------ set(ENABLE_MPI ON CACHE BOOL "") -set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3-${GCC_VERSION}" CACHE PATH "") +set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3.6-${GCC_VERSION}" CACHE PATH "") set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") diff --git a/host-configs/llnl/toss_3_x86_64_ib/gcc@8.3.1.cmake b/host-configs/llnl/toss_4_x86_64_ib/gcc@10.3.1.cmake similarity index 86% rename from host-configs/llnl/toss_3_x86_64_ib/gcc@8.3.1.cmake rename to host-configs/llnl/toss_4_x86_64_ib/gcc@10.3.1.cmake index 06c8fbaca..3bbc5b68e 100644 --- a/host-configs/llnl/toss_3_x86_64_ib/gcc@8.3.1.cmake +++ b/host-configs/llnl/toss_4_x86_64_ib/gcc@10.3.1.cmake @@ -1,10 +1,10 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) #------------------------------------------------------------------------------ -# Example host-config file for the quartz cluster at LLNL +# Example host-config file for a cluster on a toss4 platform (e.g. quartz) at LLNL #------------------------------------------------------------------------------ # # This file provides CMake with paths / details for: @@ -13,10 +13,10 @@ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ -# gcc@8.3.1 compilers +# gcc@10.3.1 compilers #------------------------------------------------------------------------------ -set(GCC_VERSION "gcc-8.3.1") +set(GCC_VERSION "gcc-10.3.1") set(GCC_HOME "/usr/tce/packages/gcc/${GCC_VERSION}") # c compiler @@ -36,7 +36,7 @@ set(CMAKE_Fortran_COMPILER "${GCC_HOME}/bin/gfortran" CACHE PATH "") #------------------------------------------------------------------------------ set(ENABLE_MPI ON CACHE BOOL "") -set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3-${GCC_VERSION}" CACHE PATH "") +set(MPI_HOME "/usr/tce/packages/mvapich2/mvapich2-2.3.6-${GCC_VERSION}" CACHE PATH "") set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") diff --git a/host-configs/llnl/toss_3_x86_64_ib/intel-oneapi@2021.3.cmake b/host-configs/llnl/toss_4_x86_64_ib/intel@2022.1.0-c++17.cmake similarity index 79% rename from host-configs/llnl/toss_3_x86_64_ib/intel-oneapi@2021.3.cmake rename to host-configs/llnl/toss_4_x86_64_ib/intel@2022.1.0-c++17.cmake index 293c0be0c..c73860231 100644 --- a/host-configs/llnl/toss_3_x86_64_ib/intel-oneapi@2021.3.cmake +++ b/host-configs/llnl/toss_4_x86_64_ib/intel@2022.1.0-c++17.cmake @@ -1,10 +1,10 @@ -# Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) #------------------------------------------------------------------------------ -# Example host-config file for the quartz cluster at LLNL +# Example host-config file for a cluster on a toss4 platform (e.g. quartz) at LLNL #------------------------------------------------------------------------------ # # This file provides CMake with paths / details for: @@ -13,10 +13,10 @@ #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ -# intel-oneapi.2021.3 compilers +# intel-2022.1.0 compilers #------------------------------------------------------------------------------ -set(INTELLLVM_VERSION "intel-oneapi.2021.3") +set(INTELLLVM_VERSION "intel-2022.1.0-magic") set(INTELLLVM_HOME "/usr/tce/packages/intel/${INTELLLVM_VERSION}") # c compiler @@ -31,6 +31,12 @@ set(ENABLE_FORTRAN ON CACHE BOOL "") # fortran compiler set(CMAKE_Fortran_COMPILER "${INTELLLVM_HOME}/bin/ifx" CACHE PATH "") +#------------------------------------------------------------------------------ +# Extra flags +#------------------------------------------------------------------------------ + +set(BLT_CXX_STD "c++17") + #------------------------------------------------------------------------------ # MPI Support #------------------------------------------------------------------------------ diff --git a/host-configs/llnl/toss_4_x86_64_ib/rocm@4.5.2_hip.cmake b/host-configs/llnl/toss_4_x86_64_ib/rocm@4.5.2_hip.cmake deleted file mode 100644 index 8d17a68ee..000000000 --- a/host-configs/llnl/toss_4_x86_64_ib/rocm@4.5.2_hip.cmake +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example host-config file for the corona cluster at LLNL -#------------------------------------------------------------------------------ -# This file provides CMake with paths / details for: -# C,C++, & Fortran compilers + MPI & HIP -# using ROCM compilers -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------ -# ROCM@4.5.2 compilers -#------------------------------------------------------------------------------ -set(ROCM_HOME "/usr/tce/packages/rocmcc-tce/rocmcc-4.5.2") -set(CMAKE_C_COMPILER "${ROCM_HOME}/bin/amdclang" CACHE PATH "") -set(CMAKE_CXX_COMPILER "${ROCM_HOME}/bin/hipcc" CACHE PATH "") - -# Fortran support -set(ENABLE_FORTRAN ON CACHE BOOL "") -set(CMAKE_Fortran_COMPILER "${ROCM_HOME}/bin/amdflang" CACHE PATH "") - -#------------------------------------------------------------------------------ -# MPI Support -#------------------------------------------------------------------------------ -set(ENABLE_MPI ON CACHE BOOL "") - -set(MPI_HOME "/usr/tce/packages/mvapich2-tce/mvapich2-2.3.6-rocmcc-4.5.2/") -set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_Fortran_COMPILER "${MPI_HOME}/bin/mpif90" CACHE PATH "") - -#------------------------------------------------------------------------------ -# HIP support -#------------------------------------------------------------------------------ -set(ENABLE_HIP ON CACHE BOOL "") -set(ROCM_PATH "/opt/rocm-4.5.2/" CACHE PATH "") -set(CMAKE_HIP_ARCHITECTURES "gfx906" CACHE STRING "") - -# Recommended link line when not using tce-wrapped compilers -# set(CMAKE_EXE_LINKER_FLAGS "-Wl,--disable-new-dtags -L/opt/rocm-4.5.2/hip/lib -L/opt/rocm-4.5.2/lib -L/opt/rocm-4.5.2/lib64 -Wl,-rpath,/opt/rocm-4.5.2/hip/lib:/opt/rocm-4.5.2/lib:/opt/rocm-4.5.2/lib64 -lamdhip64 -lhsakmt -lhsa-runtime64 -lamd_comgr" CACHE STRING "") diff --git a/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip.cmake b/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip.cmake index c640b6cbb..44ef05ac1 100644 --- a/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip.cmake +++ b/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip_c++17.cmake b/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip_c++17.cmake index 224fd5d1d..fd081cf6d 100644 --- a/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip_c++17.cmake +++ b/host-configs/llnl/toss_4_x86_64_ib_cray/cce@13.0.1_clang_hip_c++17.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/host-configs/llnl/toss_4_x86_64_ib_cray/rocm@4.5.2_hip.cmake b/host-configs/llnl/toss_4_x86_64_ib_cray/rocm@4.5.2_hip.cmake deleted file mode 100644 index 11a5b0978..000000000 --- a/host-configs/llnl/toss_4_x86_64_ib_cray/rocm@4.5.2_hip.cmake +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and -# other BLT Project Developers. See the top-level LICENSE file for details -# -# SPDX-License-Identifier: (BSD-3-Clause) - -#------------------------------------------------------------------------------ -# Example host-config file for the rznevada cluster at LLNL -#------------------------------------------------------------------------------ -# This file provides CMake with paths / details for: -# C,C++, & Fortran compilers + MPI & HIP -# using ROCM compilers -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------ -# ROCM@4.5.2 compilers -#------------------------------------------------------------------------------ -set(ROCM_HOME "/usr/tce/packages/rocmcc-tce/rocmcc-4.5.2-cce-13.0.1") -set(CMAKE_C_COMPILER "${ROCM_HOME}/bin/amdclang" CACHE PATH "") -set(CMAKE_CXX_COMPILER "${ROCM_HOME}/bin/hipcc" CACHE PATH "") - -# Fortran support -set(ENABLE_FORTRAN ON CACHE BOOL "") -set(CMAKE_Fortran_COMPILER "${ROCM_HOME}/bin/crayftn" CACHE PATH "") - -#------------------------------------------------------------------------------ -# MPI Support -#------------------------------------------------------------------------------ -set(ENABLE_MPI ON CACHE BOOL "") - -set(MPI_HOME "/usr/tce/packages/cray-mpich-tce/cray-mpich-8.1.13-rocmcc-4.5.2-cce-13.0.1") -set(MPI_C_COMPILER "${MPI_HOME}/bin/mpicc" CACHE PATH "") -set(MPI_CXX_COMPILER "${MPI_HOME}/bin/mpicxx" CACHE PATH "") -set(MPI_Fortran_COMPILER "${MPI_HOME}/bin/mpif90" CACHE PATH "") - -#------------------------------------------------------------------------------ -# HIP support -#------------------------------------------------------------------------------ -set(ENABLE_HIP ON CACHE BOOL "") -set(ROCM_PATH "/opt/rocm-4.5.2/" CACHE PATH "") -set(CMAKE_HIP_ARCHITECTURES "gfx908" CACHE STRING "") - -# Recommended link line when not using tce-wrapped compilers -# set(CMAKE_EXE_LINKER_FLAGS "-Wl,--disable-new-dtags -L/opt/rocm-4.5.2/hip/lib -L/opt/rocm-4.5.2/lib -L/opt/rocm-4.5.2/lib64 -Wl,-rpath,/opt/rocm-4.5.2/hip/lib:/opt/rocm-4.5.2/lib:/opt/rocm-4.5.2/lib64 -lamdhip64 -lhsakmt -lhsa-runtime64 -lamd_comgr" CACHE STRING "") diff --git a/host-configs/llnl/windows/sqa-uno-msvc@15.cmake b/host-configs/llnl/windows/sqa-uno-msvc@15.cmake index 050502875..55afac77b 100644 --- a/host-configs/llnl/windows/sqa-uno-msvc@15.cmake +++ b/host-configs/llnl/windows/sqa-uno-msvc@15.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/host-configs/olcf/summit/gcc@6.4.0_nvcc.cmake b/host-configs/olcf/summit/gcc@6.4.0_nvcc.cmake index 4892950c6..dfa3e60e5 100644 --- a/host-configs/olcf/summit/gcc@6.4.0_nvcc.cmake +++ b/host-configs/olcf/summit/gcc@6.4.0_nvcc.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -50,7 +50,6 @@ set(MPIEXEC_EXECUTABLE "/sw/summit/xalt/1.2.1/bin/jsrun" CACHE PATH "") #------------------------------------------------------------------------------ # CUDA support #------------------------------------------------------------------------------ -# _blt_tutorial_cuda_config_start set(ENABLE_CUDA ON CACHE BOOL "") set(CUDA_TOOLKIT_ROOT_DIR "/sw/summit/cuda/10.1.243/" CACHE PATH "") @@ -63,6 +62,3 @@ set(CMAKE_CUDA_FLAGS "-restrict -arch ${_cuda_arch} -std=c++11 --expt-extended-l CACHE STRING "") set(CUDA_SEPARABLE_COMPILATION ON CACHE BOOL "") - -# _blt_tutorial_cuda_config_end - diff --git a/host-configs/other/hip.cmake b/host-configs/other/hip.cmake index 5e09b2eac..10c79643a 100644 --- a/host-configs/other/hip.cmake +++ b/host-configs/other/hip.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/host-configs/other/radiuss-aws-ec2.cmake b/host-configs/other/radiuss-aws-ec2.cmake index c6de49370..ed4f0be52 100644 --- a/host-configs/other/radiuss-aws-ec2.cmake +++ b/host-configs/other/radiuss-aws-ec2.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/scripts/make_local_branch_from_fork_pr.sh b/scripts/make_local_branch_from_fork_pr.sh index 75a72f044..68fad6248 100755 --- a/scripts/make_local_branch_from_fork_pr.sh +++ b/scripts/make_local_branch_from_fork_pr.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash ############################################################################### -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/CMakeLists.txt b/tests/internal/CMakeLists.txt index c746f368e..2c51dd21f 100644 --- a/tests/internal/CMakeLists.txt +++ b/tests/internal/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -20,7 +20,7 @@ if(NOT BLT_SOURCE_DIR) endif() if (NOT BLT_CXX_STD) - set(BLT_CXX_STD "c++11" CACHE STRING "") + set(BLT_CXX_STD "c++14" CACHE STRING "") endif() include(${BLT_SOURCE_DIR}/SetupBLT.cmake) @@ -257,9 +257,10 @@ if (ENABLE_CUDA AND ENABLE_MPI AND NUM_MPI_TASKS 4) endif() +# Exercise blt_print_target_properties macro message(STATUS "") message(STATUS "Exercising blt_print_target_properties macro default options.") -foreach(_target gtest example t_example_smoke not-a-target blt_header_only mpi cuda cuda_runtime blt::hip blt::hip_runtime) +foreach(_target gtest gbenchmark example t_example_smoke not-a-target blt_header_only mpi cuda cuda_runtime blt::hip blt::hip_runtime) blt_print_target_properties(TARGET ${_target}) endforeach() @@ -281,6 +282,18 @@ blt_register_library(NAME foo DEPENDS_ON bar) blt_register_library(NAME bar DEPENDS_ON foo) blt_print_target_properties(TARGET bar CHILDREN true) +# Exercise blt_print_variables macro +message(STATUS "") +message(STATUS [[Exercising blt_print_variables macro on using 'NAME_REGEX "blt" IGNORE_CASE':]]) +blt_print_variables( NAME_REGEX "blt" IGNORE_CASE) +message(STATUS "") +message(STATUS [[Exercising blt_print_variables macro on using 'NAME_REGEX "_FOUND" VALUE_REGEX "^on$|^true$|^1$" IGNORE_CASE']]) +blt_print_variables( NAME_REGEX "_FOUND" VALUE_REGEX "^on$|^true$|^1$" IGNORE_CASE) +message(STATUS "") +message(STATUS [[Exercising blt_print_variables macro on using 'NAME_REGEX "LIB|LIBS|LIBRARY|LIBRARIES"']]) +blt_print_variables( NAME_REGEX "LIB|LIBS|LIBRARY|LIBRARIES") + +# Test object libraries add_subdirectory(src/object_library_test) if(ENABLE_CLANGQUERY OR ENABLE_CLANGTIDY) diff --git a/tests/internal/src/Example.cpp b/tests/internal/src/Example.cpp index d631e4c46..2fa8fcd28 100644 --- a/tests/internal/src/Example.cpp +++ b/tests/internal/src/Example.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/Example.hpp b/tests/internal/src/Example.hpp index d6b305f8f..34c70c205 100644 --- a/tests/internal/src/Example.hpp +++ b/tests/internal/src/Example.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/Example_Exports.h b/tests/internal/src/Example_Exports.h index a0d900dfc..cb61c4ddf 100644 --- a/tests/internal/src/Example_Exports.h +++ b/tests/internal/src/Example_Exports.h @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/HeaderOnly.hpp b/tests/internal/src/HeaderOnly.hpp index 951ee3443..92e3ea818 100644 --- a/tests/internal/src/HeaderOnly.hpp +++ b/tests/internal/src/HeaderOnly.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/CMakeLists.txt b/tests/internal/src/combine_static_library_test/CMakeLists.txt index f0e013a7d..93a141853 100644 --- a/tests/internal/src/combine_static_library_test/CMakeLists.txt +++ b/tests/internal/src/combine_static_library_test/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/Foo1.cpp b/tests/internal/src/combine_static_library_test/Foo1.cpp index 4f7ad14c1..ecf5a3bfe 100644 --- a/tests/internal/src/combine_static_library_test/Foo1.cpp +++ b/tests/internal/src/combine_static_library_test/Foo1.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/Foo1.hpp b/tests/internal/src/combine_static_library_test/Foo1.hpp index 8af1be68a..f198ab216 100644 --- a/tests/internal/src/combine_static_library_test/Foo1.hpp +++ b/tests/internal/src/combine_static_library_test/Foo1.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/Foo2.cpp b/tests/internal/src/combine_static_library_test/Foo2.cpp index 7f72ce6ad..5dc6eb191 100644 --- a/tests/internal/src/combine_static_library_test/Foo2.cpp +++ b/tests/internal/src/combine_static_library_test/Foo2.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/Foo2.hpp b/tests/internal/src/combine_static_library_test/Foo2.hpp index a8fa9908e..7ade982da 100644 --- a/tests/internal/src/combine_static_library_test/Foo2.hpp +++ b/tests/internal/src/combine_static_library_test/Foo2.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/Foo3.cpp b/tests/internal/src/combine_static_library_test/Foo3.cpp index bfba96d0b..ca35abd4a 100644 --- a/tests/internal/src/combine_static_library_test/Foo3.cpp +++ b/tests/internal/src/combine_static_library_test/Foo3.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/Foo3.hpp b/tests/internal/src/combine_static_library_test/Foo3.hpp index 33538b7d2..d152c4d91 100644 --- a/tests/internal/src/combine_static_library_test/Foo3.hpp +++ b/tests/internal/src/combine_static_library_test/Foo3.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_shared_smoke.cpp b/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_shared_smoke.cpp index 279b121a7..1f7c9b29c 100644 --- a/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_shared_smoke.cpp +++ b/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_shared_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_static_smoke.cpp b/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_static_smoke.cpp index 279b121a7..1f7c9b29c 100644 --- a/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_static_smoke.cpp +++ b/tests/internal/src/combine_static_library_test/blt_combine_static_libraries_static_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/combine_static_library_test/main.cpp b/tests/internal/src/combine_static_library_test/main.cpp index 8db985916..4e9e26c98 100644 --- a/tests/internal/src/combine_static_library_test/main.cpp +++ b/tests/internal/src/combine_static_library_test/main.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/hip_defines_test/CMakeLists.txt b/tests/internal/src/hip_defines_test/CMakeLists.txt index b25a91cd9..d7af6a835 100644 --- a/tests/internal/src/hip_defines_test/CMakeLists.txt +++ b/tests/internal/src/hip_defines_test/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/hip_defines_test/bar.cpp b/tests/internal/src/hip_defines_test/bar.cpp index f7ef18286..d04fabc09 100644 --- a/tests/internal/src/hip_defines_test/bar.cpp +++ b/tests/internal/src/hip_defines_test/bar.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/hip_defines_test/foo.cpp b/tests/internal/src/hip_defines_test/foo.cpp index 9d78d7f5b..a58290e3e 100644 --- a/tests/internal/src/hip_defines_test/foo.cpp +++ b/tests/internal/src/hip_defines_test/foo.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/CMakeLists.txt b/tests/internal/src/object_library_test/CMakeLists.txt index b5081e21e..6cecb1161 100644 --- a/tests/internal/src/object_library_test/CMakeLists.txt +++ b/tests/internal/src/object_library_test/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/base_object.cpp b/tests/internal/src/object_library_test/base_object.cpp index bce908145..7a1584db2 100644 --- a/tests/internal/src/object_library_test/base_object.cpp +++ b/tests/internal/src/object_library_test/base_object.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/base_object.hpp b/tests/internal/src/object_library_test/base_object.hpp index 86be1b836..6a2ab8fc4 100644 --- a/tests/internal/src/object_library_test/base_object.hpp +++ b/tests/internal/src/object_library_test/base_object.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/inherited_base/CMakeLists.txt b/tests/internal/src/object_library_test/inherited_base/CMakeLists.txt index 198436563..9cf967d0d 100644 --- a/tests/internal/src/object_library_test/inherited_base/CMakeLists.txt +++ b/tests/internal/src/object_library_test/inherited_base/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/inherited_base/inherited_base.cpp b/tests/internal/src/object_library_test/inherited_base/inherited_base.cpp index 01c19433d..da99a74ad 100644 --- a/tests/internal/src/object_library_test/inherited_base/inherited_base.cpp +++ b/tests/internal/src/object_library_test/inherited_base/inherited_base.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/inherited_base/inherited_base.hpp b/tests/internal/src/object_library_test/inherited_base/inherited_base.hpp index bd47af43a..ddd8a3b99 100644 --- a/tests/internal/src/object_library_test/inherited_base/inherited_base.hpp +++ b/tests/internal/src/object_library_test/inherited_base/inherited_base.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/main.cpp b/tests/internal/src/object_library_test/main.cpp index f116465a5..cf5839127 100644 --- a/tests/internal/src/object_library_test/main.cpp +++ b/tests/internal/src/object_library_test/main.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/object.cpp b/tests/internal/src/object_library_test/object.cpp index 6ffb0ead5..23a66a44a 100644 --- a/tests/internal/src/object_library_test/object.cpp +++ b/tests/internal/src/object_library_test/object.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/object_library_test/object.hpp b/tests/internal/src/object_library_test/object.hpp index f78c672d4..c46eee3a0 100644 --- a/tests/internal/src/object_library_test/object.hpp +++ b/tests/internal/src/object_library_test/object.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/static_analysis/CMakeLists.txt b/tests/internal/src/static_analysis/CMakeLists.txt index e287e1485..78e8aa79f 100644 --- a/tests/internal/src/static_analysis/CMakeLists.txt +++ b/tests/internal/src/static_analysis/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/static_analysis/subtle_error_source.cpp b/tests/internal/src/static_analysis/subtle_error_source.cpp index 35adeb336..2475621ac 100644 --- a/tests/internal/src/static_analysis/subtle_error_source.cpp +++ b/tests/internal/src/static_analysis/subtle_error_source.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/static_analysis/well_analyzed_source.cpp b/tests/internal/src/static_analysis/well_analyzed_source.cpp index 5fc9a4cb3..c1de2c216 100644 --- a/tests/internal/src/static_analysis/well_analyzed_source.cpp +++ b/tests/internal/src/static_analysis/well_analyzed_source.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/t_example_compile_definitions.cpp b/tests/internal/src/t_example_compile_definitions.cpp index bad6794cd..9b037253e 100644 --- a/tests/internal/src/t_example_compile_definitions.cpp +++ b/tests/internal/src/t_example_compile_definitions.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/t_example_smoke.cpp b/tests/internal/src/t_example_smoke.cpp index c5800b916..99edfd389 100644 --- a/tests/internal/src/t_example_smoke.cpp +++ b/tests/internal/src/t_example_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/t_git_macros_smoke.cpp.in b/tests/internal/src/t_git_macros_smoke.cpp.in index 270878056..a7d65af11 100644 --- a/tests/internal/src/t_git_macros_smoke.cpp.in +++ b/tests/internal/src/t_git_macros_smoke.cpp.in @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/t_header_only_smoke.cpp b/tests/internal/src/t_header_only_smoke.cpp index 797b0f69b..997e41cd0 100644 --- a/tests/internal/src/t_header_only_smoke.cpp +++ b/tests/internal/src/t_header_only_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cmake_format_conformant.cmake b/tests/internal/src/test_cmake_format_conformant.cmake index 62178c321..8a08da9a4 100644 --- a/tests/internal/src/test_cmake_format_conformant.cmake +++ b/tests/internal/src/test_cmake_format_conformant.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and other # BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cmake_format_nonconformant.cmake b/tests/internal/src/test_cmake_format_nonconformant.cmake index bbb218476..22b5fbbac 100644 --- a/tests/internal/src/test_cmake_format_nonconformant.cmake +++ b/tests/internal/src/test_cmake_format_nonconformant.cmake @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and other # BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cuda_device_call_from_kernel/CMakeLists.txt b/tests/internal/src/test_cuda_device_call_from_kernel/CMakeLists.txt index 059fbaf43..38678c8a2 100644 --- a/tests/internal/src/test_cuda_device_call_from_kernel/CMakeLists.txt +++ b/tests/internal/src/test_cuda_device_call_from_kernel/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cuda_device_call_from_kernel/Child.cpp b/tests/internal/src/test_cuda_device_call_from_kernel/Child.cpp index 93a27d302..648bfd062 100644 --- a/tests/internal/src/test_cuda_device_call_from_kernel/Child.cpp +++ b/tests/internal/src/test_cuda_device_call_from_kernel/Child.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cuda_device_call_from_kernel/Child.hpp b/tests/internal/src/test_cuda_device_call_from_kernel/Child.hpp index 16e33c2cf..bd91abfb8 100644 --- a/tests/internal/src/test_cuda_device_call_from_kernel/Child.hpp +++ b/tests/internal/src/test_cuda_device_call_from_kernel/Child.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cuda_device_call_from_kernel/CudaTests.cpp b/tests/internal/src/test_cuda_device_call_from_kernel/CudaTests.cpp index 11d43ac64..ebc17d1ad 100644 --- a/tests/internal/src/test_cuda_device_call_from_kernel/CudaTests.cpp +++ b/tests/internal/src/test_cuda_device_call_from_kernel/CudaTests.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cuda_device_call_from_kernel/Parent.cpp b/tests/internal/src/test_cuda_device_call_from_kernel/Parent.cpp index 32826f13c..5245f9f59 100644 --- a/tests/internal/src/test_cuda_device_call_from_kernel/Parent.cpp +++ b/tests/internal/src/test_cuda_device_call_from_kernel/Parent.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cuda_device_call_from_kernel/Parent.hpp b/tests/internal/src/test_cuda_device_call_from_kernel/Parent.hpp index 74bff7aa9..dc388a695 100644 --- a/tests/internal/src/test_cuda_device_call_from_kernel/Parent.hpp +++ b/tests/internal/src/test_cuda_device_call_from_kernel/Parent.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/src/test_cuda_mpi.cpp b/tests/internal/src/test_cuda_mpi.cpp index a89b5b730..e87d9298a 100644 --- a/tests/internal/src/test_cuda_mpi.cpp +++ b/tests/internal/src/test_cuda_mpi.cpp @@ -1,5 +1,5 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/internal/unit/CMakeLists.txt b/tests/internal/unit/CMakeLists.txt index 5d7887361..da6e84725 100644 --- a/tests/internal/unit/CMakeLists.txt +++ b/tests/internal/unit/CMakeLists.txt @@ -20,7 +20,7 @@ if(NOT BLT_SOURCE_DIR) endif() if (NOT BLT_CXX_STD) - set(BLT_CXX_STD "c++11" CACHE STRING "") + set(BLT_CXX_STD "c++14" CACHE STRING "") endif() include(${BLT_SOURCE_DIR}/SetupBLT.cmake) @@ -173,3 +173,29 @@ if(_hello_world_compiled) else() message(FATAL_ERROR "... failed to compile.") endif() + +if(ENABLE_HIP) + message(STATUS "Checking blt_hip_runtime imported target in blt_check_code_compiles") + blt_check_code_compiles(CODE_COMPILES _hello_world_with_libs_compiled + VERBOSE_OUTPUT ON + DEPENDS_ON blt_hip_runtime + SOURCE_STRING + [=[ + #include + #include "hip/hip_runtime.h" + + int main(int, char**) + { + + std::cout << "Hello World!" << std::endl; + + return 0; + } + ]=]) + + if(_hello_world_with_libs_compiled) + message(STATUS "... passed") + else() + message(FATAL_ERROR "... failed to compile.") + endif() +endif() diff --git a/tests/smoke/CMakeLists.txt b/tests/smoke/CMakeLists.txt index 266461591..1aa060ba3 100644 --- a/tests/smoke/CMakeLists.txt +++ b/tests/smoke/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -40,7 +40,7 @@ endif() ################ # gbenchmark test ################ -if(ENABLE_GBENCHMARKS) +if(ENABLE_GBENCHMARK) blt_add_executable(NAME blt_gbenchmark_smoke SOURCES blt_gbenchmark_smoke.cpp OUTPUT_DIR ${TEST_OUTPUT_DIRECTORY} @@ -49,11 +49,11 @@ if(ENABLE_GBENCHMARKS) if(ENABLE_BENCHMARKS) blt_add_benchmark(NAME blt_gbenchmark_smoke - COMMAND blt_gbenchmark_smoke "--benchmark_min_time=0.0001") + COMMAND blt_gbenchmark_smoke "--benchmark_min_time=0.0001s") else() # A user could turn on gbenchmarks but turn off benchmarks blt_add_test(NAME blt_gbenchmark_smoke - COMMAND blt_gbenchmark_smoke "--benchmark_min_time=0.0001") + COMMAND blt_gbenchmark_smoke "--benchmark_min_time=0.0001s") endif() endif() diff --git a/tests/smoke/blt_cuda_gtest_smoke.cpp b/tests/smoke/blt_cuda_gtest_smoke.cpp index f37c36503..5d0e134c2 100644 --- a/tests/smoke/blt_cuda_gtest_smoke.cpp +++ b/tests/smoke/blt_cuda_gtest_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_cuda_mpi_smoke.cpp b/tests/smoke/blt_cuda_mpi_smoke.cpp index c3aecd2d3..02a0ed00b 100644 --- a/tests/smoke/blt_cuda_mpi_smoke.cpp +++ b/tests/smoke/blt_cuda_mpi_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_cuda_openmp_smoke.cpp b/tests/smoke/blt_cuda_openmp_smoke.cpp index 0c6062e66..9f9825ab8 100644 --- a/tests/smoke/blt_cuda_openmp_smoke.cpp +++ b/tests/smoke/blt_cuda_openmp_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_cuda_runtime_smoke.cpp b/tests/smoke/blt_cuda_runtime_smoke.cpp index dd66748d3..20ce063c0 100644 --- a/tests/smoke/blt_cuda_runtime_smoke.cpp +++ b/tests/smoke/blt_cuda_runtime_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_cuda_smoke.cpp b/tests/smoke/blt_cuda_smoke.cpp index 0adba8606..7838f8cec 100644 --- a/tests/smoke/blt_cuda_smoke.cpp +++ b/tests/smoke/blt_cuda_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_cuda_version_smoke.cpp b/tests/smoke/blt_cuda_version_smoke.cpp index 49caa8f56..3f2562816 100644 --- a/tests/smoke/blt_cuda_version_smoke.cpp +++ b/tests/smoke/blt_cuda_version_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) @@ -10,6 +10,7 @@ //----------------------------------------------------------------------------- #include +#include #include "cuda_runtime_api.h" diff --git a/tests/smoke/blt_fruit_mpi_smoke.f90 b/tests/smoke/blt_fruit_mpi_smoke.f90 index fc4603094..1e314c4a7 100644 --- a/tests/smoke/blt_fruit_mpi_smoke.f90 +++ b/tests/smoke/blt_fruit_mpi_smoke.f90 @@ -1,4 +1,4 @@ -! Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +! Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and ! other BLT Project Developers. See the top-level LICENSE file for details ! ! SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_fruit_smoke.f90 b/tests/smoke/blt_fruit_smoke.f90 index 63f0693d2..8b3ad590d 100644 --- a/tests/smoke/blt_fruit_smoke.f90 +++ b/tests/smoke/blt_fruit_smoke.f90 @@ -1,4 +1,4 @@ -! Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +! Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and ! other BLT Project Developers. See the top-level LICENSE file for details ! ! SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_gbenchmark_smoke.cpp b/tests/smoke/blt_gbenchmark_smoke.cpp index a2831c01c..920af328d 100644 --- a/tests/smoke/blt_gbenchmark_smoke.cpp +++ b/tests/smoke/blt_gbenchmark_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) @@ -10,14 +10,14 @@ #define BASIC_BENCHMARK_TEST(x) \ BENCHMARK(x)->Arg( 1<<3 )->Arg( 1<<9 )->Arg( 1 << 13 ) -void benchmark_smoke_empty(benchmark::State& state) +void benchmark_smoke_string_create(benchmark::State& state) { for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); + std::string empty_string; } } -BENCHMARK(benchmark_smoke_empty); +BENCHMARK(benchmark_smoke_string_create); void benchmark_smoke_spin_loop(benchmark::State& state) diff --git a/tests/smoke/blt_gmock_smoke.cpp b/tests/smoke/blt_gmock_smoke.cpp index 99453a0cb..110e9a1b1 100644 --- a/tests/smoke/blt_gmock_smoke.cpp +++ b/tests/smoke/blt_gmock_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_gtest_smoke.cpp b/tests/smoke/blt_gtest_smoke.cpp index 7b8d53667..a68c890e7 100644 --- a/tests/smoke/blt_gtest_smoke.cpp +++ b/tests/smoke/blt_gtest_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_hip_gtest_smoke.cpp b/tests/smoke/blt_hip_gtest_smoke.cpp index 76172e76c..81cbfdc65 100644 --- a/tests/smoke/blt_hip_gtest_smoke.cpp +++ b/tests/smoke/blt_hip_gtest_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_hip_runtime_c_smoke.c b/tests/smoke/blt_hip_runtime_c_smoke.c index 42cfacd97..16519e341 100644 --- a/tests/smoke/blt_hip_runtime_c_smoke.c +++ b/tests/smoke/blt_hip_runtime_c_smoke.c @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_hip_runtime_smoke.cpp b/tests/smoke/blt_hip_runtime_smoke.cpp index a7ca79fc6..200df812d 100644 --- a/tests/smoke/blt_hip_runtime_smoke.cpp +++ b/tests/smoke/blt_hip_runtime_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_hip_smoke.cpp b/tests/smoke/blt_hip_smoke.cpp index b94eb152b..2200cad69 100644 --- a/tests/smoke/blt_hip_smoke.cpp +++ b/tests/smoke/blt_hip_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_mpi_smoke.cpp b/tests/smoke/blt_mpi_smoke.cpp index 230a79351..ff1930bc8 100644 --- a/tests/smoke/blt_mpi_smoke.cpp +++ b/tests/smoke/blt_mpi_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/blt_openmp_smoke.cpp b/tests/smoke/blt_openmp_smoke.cpp index e2d7ebfae..100e0ff46 100644 --- a/tests/smoke/blt_openmp_smoke.cpp +++ b/tests/smoke/blt_openmp_smoke.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/fortran_driver.cpp b/tests/smoke/fortran_driver.cpp index 48b842784..e1b613f57 100644 --- a/tests/smoke/fortran_driver.cpp +++ b/tests/smoke/fortran_driver.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/tests/smoke/fortran_mpi_driver.cpp b/tests/smoke/fortran_mpi_driver.cpp index a9b60fcf6..fcb1b25c9 100644 --- a/tests/smoke/fortran_mpi_driver.cpp +++ b/tests/smoke/fortran_mpi_driver.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +// Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and // other BLT Project Developers. See the top-level LICENSE file for details // // SPDX-License-Identifier: (BSD-3-Clause) diff --git a/thirdparty_builtin/CMakeLists.txt b/thirdparty_builtin/CMakeLists.txt index 54aa5b3df..6acb24841 100644 --- a/thirdparty_builtin/CMakeLists.txt +++ b/thirdparty_builtin/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and +# Copyright (c) 2017-2023, Lawrence Livermore National Security, LLC and # other BLT Project Developers. See the top-level LICENSE file for details # # SPDX-License-Identifier: (BSD-3-Clause) @@ -7,9 +7,9 @@ set(_blt_tpl_targets) # tracks names of enabled tpl targets if(ENABLE_GBENCHMARK OR ENABLE_GTEST OR ENABLE_GMOCK) if("${CMAKE_CXX_STANDARD}" STREQUAL "" OR - "${CMAKE_CXX_STANDARD}" LESS 11) - message(WARNING "GoogleTest, GoogleMock, and GoogleBenchmark require C++11 or later. " - "Set BLT_CXX_STD to 'c++11' or higher before loading BLT.") + "${CMAKE_CXX_STANDARD}" LESS 14) + message(WARNING "GoogleTest, GoogleMock, and GoogleBenchmark require C++14 or later. " + "Set BLT_CXX_STD to 'c++14' or higher before loading BLT.") endif() endif() @@ -84,8 +84,8 @@ if(ENABLE_TESTS) set (INSTALL_GTEST OFF CACHE BOOL "") # Enable builtin google test - add_subdirectory(googletest-master-2020-01-07 - ${BLT_BUILD_DIR}/thirdparty_builtin/googletest-master-2020-01-07) + add_subdirectory(googletest + ${BLT_BUILD_DIR}/thirdparty_builtin/googletest) if(UNIX AND NOT APPLE) find_package( Threads ) @@ -145,8 +145,8 @@ if(ENABLE_BENCHMARKS) endif() set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "") - add_subdirectory(benchmark-1.5.0 - ${BLT_BUILD_DIR}/thirdparty_builtin/benchmark-1.5.0) + add_subdirectory(benchmark-1.8.0 + ${BLT_BUILD_DIR}/thirdparty_builtin/benchmark-1.8.0) if (UNIX AND NOT APPLE) find_library(RT_LIBRARIES rt) diff --git a/thirdparty_builtin/benchmark-1.5.0/.gitignore b/thirdparty_builtin/benchmark-1.5.0/.gitignore deleted file mode 100644 index 806d04c6b..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/.gitignore +++ /dev/null @@ -1,61 +0,0 @@ -*.a -*.so -*.so.?* -*.dll -*.exe -*.dylib -*.cmake -!/cmake/*.cmake -!/test/AssemblyTests.cmake -*~ -*.pyc -__pycache__ - -# lcov -*.lcov -/lcov - -# cmake files. -/Testing -CMakeCache.txt -CMakeFiles/ -cmake_install.cmake - -# makefiles. -Makefile - -# in-source build. -bin/ -lib/ -/test/*_test - -# exuberant ctags. -tags - -# YouCompleteMe configuration. -.ycm_extra_conf.pyc - -# ninja generated files. -.ninja_deps -.ninja_log -build.ninja -install_manifest.txt -rules.ninja - -# bazel output symlinks. -bazel-* - -# out-of-source build top-level folders. -build/ -_build/ -build*/ - -# in-source dependencies -/googletest/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -CMakeSettings.json - -# Visual Studio Code cache/options directory -.vscode/ diff --git a/thirdparty_builtin/benchmark-1.5.0/.travis-libcxx-setup.sh b/thirdparty_builtin/benchmark-1.5.0/.travis-libcxx-setup.sh deleted file mode 100644 index a591743c6..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/.travis-libcxx-setup.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash - -# Install a newer CMake version -curl -sSL https://cmake.org/files/v3.6/cmake-3.6.1-Linux-x86_64.sh -o install-cmake.sh -chmod +x install-cmake.sh -sudo ./install-cmake.sh --prefix=/usr/local --skip-license - -# Checkout LLVM sources -git clone --depth=1 https://github.com/llvm-mirror/llvm.git llvm-source -git clone --depth=1 https://github.com/llvm-mirror/libcxx.git llvm-source/projects/libcxx -git clone --depth=1 https://github.com/llvm-mirror/libcxxabi.git llvm-source/projects/libcxxabi - -# Setup libc++ options -if [ -z "$BUILD_32_BITS" ]; then - export BUILD_32_BITS=OFF && echo disabling 32 bit build -fi - -# Build and install libc++ (Use unstable ABI for better sanitizer coverage) -mkdir llvm-build && cd llvm-build -cmake -DCMAKE_C_COMPILER=${C_COMPILER} -DCMAKE_CXX_COMPILER=${COMPILER} \ - -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=/usr \ - -DLIBCXX_ABI_UNSTABLE=ON \ - -DLLVM_USE_SANITIZER=${LIBCXX_SANITIZER} \ - -DLLVM_BUILD_32_BITS=${BUILD_32_BITS} \ - ../llvm-source -make cxx -j2 -sudo make install-cxxabi install-cxx -cd ../ diff --git a/thirdparty_builtin/benchmark-1.5.0/BUILD.bazel b/thirdparty_builtin/benchmark-1.5.0/BUILD.bazel deleted file mode 100644 index 6ee69f290..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/BUILD.bazel +++ /dev/null @@ -1,42 +0,0 @@ -licenses(["notice"]) - -config_setting( - name = "windows", - values = { - "cpu": "x64_windows", - }, - visibility = [":__subpackages__"], -) - -cc_library( - name = "benchmark", - srcs = glob( - [ - "src/*.cc", - "src/*.h", - ], - exclude = ["src/benchmark_main.cc"], - ), - hdrs = ["include/benchmark/benchmark.h"], - linkopts = select({ - ":windows": ["-DEFAULTLIB:shlwapi.lib"], - "//conditions:default": ["-pthread"], - }), - strip_include_prefix = "include", - visibility = ["//visibility:public"], -) - -cc_library( - name = "benchmark_main", - srcs = ["src/benchmark_main.cc"], - hdrs = ["include/benchmark/benchmark.h"], - strip_include_prefix = "include", - visibility = ["//visibility:public"], - deps = [":benchmark"], -) - -cc_library( - name = "benchmark_internal_headers", - hdrs = glob(["src/*.h"]), - visibility = ["//test:__pkg__"], -) diff --git a/thirdparty_builtin/benchmark-1.5.0/WORKSPACE b/thirdparty_builtin/benchmark-1.5.0/WORKSPACE deleted file mode 100644 index 9a75f968d..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/WORKSPACE +++ /dev/null @@ -1,9 +0,0 @@ -workspace(name = "com_github_google_benchmark") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "com_google_googletest", - urls = ["https://github.com/google/googletest/archive/3f0cf6b62ad1eb50d8736538363d3580dd640c3e.zip"], - strip_prefix = "googletest-3f0cf6b62ad1eb50d8736538363d3580dd640c3e", -) diff --git a/thirdparty_builtin/benchmark-1.5.0/_config.yml b/thirdparty_builtin/benchmark-1.5.0/_config.yml deleted file mode 100644 index 18854876c..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/_config.yml +++ /dev/null @@ -1 +0,0 @@ -theme: jekyll-theme-midnight \ No newline at end of file diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/Config.cmake.in b/thirdparty_builtin/benchmark-1.5.0/cmake/Config.cmake.in deleted file mode 100644 index 6e9256eea..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/cmake/Config.cmake.in +++ /dev/null @@ -1 +0,0 @@ -include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") diff --git a/thirdparty_builtin/benchmark-1.5.0/conan/CMakeLists.txt b/thirdparty_builtin/benchmark-1.5.0/conan/CMakeLists.txt deleted file mode 100644 index 15b92ca91..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/conan/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 2.8.11) -project(cmake_wrapper) - -include(conanbuildinfo.cmake) -conan_basic_setup() - -include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt) diff --git a/thirdparty_builtin/benchmark-1.5.0/conan/test_package/CMakeLists.txt b/thirdparty_builtin/benchmark-1.5.0/conan/test_package/CMakeLists.txt deleted file mode 100644 index 089a6c729..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/conan/test_package/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -cmake_minimum_required(VERSION 2.8.11) -project(test_package) - -set(CMAKE_VERBOSE_MAKEFILE TRUE) - -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() - -add_executable(${PROJECT_NAME} test_package.cpp) -target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS}) diff --git a/thirdparty_builtin/benchmark-1.5.0/conan/test_package/conanfile.py b/thirdparty_builtin/benchmark-1.5.0/conan/test_package/conanfile.py deleted file mode 100644 index d63f4088c..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/conan/test_package/conanfile.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from conans import ConanFile, CMake -import os - - -class TestPackageConan(ConanFile): - settings = "os", "compiler", "build_type", "arch" - generators = "cmake" - - def build(self): - cmake = CMake(self) - cmake.configure() - cmake.build() - - def test(self): - bin_path = os.path.join("bin", "test_package") - self.run(bin_path, run_environment=True) diff --git a/thirdparty_builtin/benchmark-1.5.0/conan/test_package/test_package.cpp b/thirdparty_builtin/benchmark-1.5.0/conan/test_package/test_package.cpp deleted file mode 100644 index 4fa7ec0bf..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/conan/test_package/test_package.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "benchmark/benchmark.h" - -void BM_StringCreation(benchmark::State& state) { - while (state.KeepRunning()) - std::string empty_string; -} - -BENCHMARK(BM_StringCreation); - -void BM_StringCopy(benchmark::State& state) { - std::string x = "hello"; - while (state.KeepRunning()) - std::string copy(x); -} - -BENCHMARK(BM_StringCopy); - -BENCHMARK_MAIN(); diff --git a/thirdparty_builtin/benchmark-1.5.0/conanfile.py b/thirdparty_builtin/benchmark-1.5.0/conanfile.py deleted file mode 100644 index e31fc5268..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/conanfile.py +++ /dev/null @@ -1,79 +0,0 @@ -from conans import ConanFile, CMake, tools -from conans.errors import ConanInvalidConfiguration -import shutil -import os - - -class GoogleBenchmarkConan(ConanFile): - name = "benchmark" - description = "A microbenchmark support library." - topics = ("conan", "benchmark", "google", "microbenchmark") - url = "https://github.com/google/benchmark" - homepage = "https://github.com/google/benchmark" - author = "Google Inc." - license = "Apache-2.0" - exports_sources = ["*"] - generators = "cmake" - - settings = "arch", "build_type", "compiler", "os" - options = { - "shared": [True, False], - "fPIC": [True, False], - "enable_lto": [True, False], - "enable_exceptions": [True, False] - } - default_options = {"shared": False, "fPIC": True, "enable_lto": False, "enable_exceptions": True} - - _build_subfolder = "." - - def source(self): - # Wrap the original CMake file to call conan_basic_setup - shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt") - shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt") - - def config_options(self): - if self.settings.os == "Windows": - if self.settings.compiler == "Visual Studio" and float(self.settings.compiler.version.value) <= 12: - raise ConanInvalidConfiguration("{} {} does not support Visual Studio <= 12".format(self.name, self.version)) - del self.options.fPIC - - def configure(self): - if self.settings.os == "Windows" and self.options.shared: - raise ConanInvalidConfiguration("Windows shared builds are not supported right now, see issue #639") - - def _configure_cmake(self): - cmake = CMake(self) - - cmake.definitions["BENCHMARK_ENABLE_TESTING"] = "OFF" - cmake.definitions["BENCHMARK_ENABLE_GTEST_TESTS"] = "OFF" - cmake.definitions["BENCHMARK_ENABLE_LTO"] = "ON" if self.options.enable_lto else "OFF" - cmake.definitions["BENCHMARK_ENABLE_EXCEPTIONS"] = "ON" if self.options.enable_exceptions else "OFF" - - # See https://github.com/google/benchmark/pull/638 for Windows 32 build explanation - if self.settings.os != "Windows": - cmake.definitions["BENCHMARK_BUILD_32_BITS"] = "ON" if "64" not in str(self.settings.arch) else "OFF" - cmake.definitions["BENCHMARK_USE_LIBCXX"] = "ON" if (str(self.settings.compiler.libcxx) == "libc++") else "OFF" - else: - cmake.definitions["BENCHMARK_USE_LIBCXX"] = "OFF" - - cmake.configure(build_folder=self._build_subfolder) - return cmake - - def build(self): - cmake = self._configure_cmake() - cmake.build() - - def package(self): - cmake = self._configure_cmake() - cmake.install() - - self.copy(pattern="LICENSE", dst="licenses") - - def package_info(self): - self.cpp_info.libs = tools.collect_libs(self) - if self.settings.os == "Linux": - self.cpp_info.libs.extend(["pthread", "rt"]) - elif self.settings.os == "Windows": - self.cpp_info.libs.append("shlwapi") - elif self.settings.os == "SunOS": - self.cpp_info.libs.append("kstat") diff --git a/thirdparty_builtin/benchmark-1.5.0/dependencies.md b/thirdparty_builtin/benchmark-1.5.0/dependencies.md deleted file mode 100644 index 6289b4e35..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/dependencies.md +++ /dev/null @@ -1,18 +0,0 @@ -# Build tool dependency policy - -To ensure the broadest compatibility when building the benchmark library, but -still allow forward progress, we require any build tooling to be available for: - -* Debian stable AND -* The last two Ubuntu LTS releases AND - -Currently, this means using build tool versions that are available for Ubuntu -16.04 (Xenial), Ubuntu 18.04 (Bionic), and Debian stretch. - -_Note, [travis](.travis.yml) runs under Ubuntu 14.04 (Trusty) for linux builds._ - -## cmake -The current supported version is cmake 3.5.1 as of 2018-06-06. - -_Note, this version is also available for Ubuntu 14.04, the previous Ubuntu LTS -release, as `cmake3`._ diff --git a/thirdparty_builtin/benchmark-1.5.0/docs/_config.yml b/thirdparty_builtin/benchmark-1.5.0/docs/_config.yml deleted file mode 100644 index 18854876c..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/docs/_config.yml +++ /dev/null @@ -1 +0,0 @@ -theme: jekyll-theme-midnight \ No newline at end of file diff --git a/thirdparty_builtin/benchmark-1.5.0/mingw.py b/thirdparty_builtin/benchmark-1.5.0/mingw.py deleted file mode 100644 index 706ad559d..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/mingw.py +++ /dev/null @@ -1,320 +0,0 @@ -#! /usr/bin/env python -# encoding: utf-8 - -import argparse -import errno -import logging -import os -import platform -import re -import sys -import subprocess -import tempfile - -try: - import winreg -except ImportError: - import _winreg as winreg -try: - import urllib.request as request -except ImportError: - import urllib as request -try: - import urllib.parse as parse -except ImportError: - import urlparse as parse - -class EmptyLogger(object): - ''' - Provides an implementation that performs no logging - ''' - def debug(self, *k, **kw): - pass - def info(self, *k, **kw): - pass - def warn(self, *k, **kw): - pass - def error(self, *k, **kw): - pass - def critical(self, *k, **kw): - pass - def setLevel(self, *k, **kw): - pass - -urls = ( - 'http://downloads.sourceforge.net/project/mingw-w64/Toolchains%20' - 'targetting%20Win32/Personal%20Builds/mingw-builds/installer/' - 'repository.txt', - 'http://downloads.sourceforge.net/project/mingwbuilds/host-windows/' - 'repository.txt' -) -''' -A list of mingw-build repositories -''' - -def repository(urls = urls, log = EmptyLogger()): - ''' - Downloads and parse mingw-build repository files and parses them - ''' - log.info('getting mingw-builds repository') - versions = {} - re_sourceforge = re.compile(r'http://sourceforge.net/projects/([^/]+)/files') - re_sub = r'http://downloads.sourceforge.net/project/\1' - for url in urls: - log.debug(' - requesting: %s', url) - socket = request.urlopen(url) - repo = socket.read() - if not isinstance(repo, str): - repo = repo.decode(); - socket.close() - for entry in repo.split('\n')[:-1]: - value = entry.split('|') - version = tuple([int(n) for n in value[0].strip().split('.')]) - version = versions.setdefault(version, {}) - arch = value[1].strip() - if arch == 'x32': - arch = 'i686' - elif arch == 'x64': - arch = 'x86_64' - arch = version.setdefault(arch, {}) - threading = arch.setdefault(value[2].strip(), {}) - exceptions = threading.setdefault(value[3].strip(), {}) - revision = exceptions.setdefault(int(value[4].strip()[3:]), - re_sourceforge.sub(re_sub, value[5].strip())) - return versions - -def find_in_path(file, path=None): - ''' - Attempts to find an executable in the path - ''' - if platform.system() == 'Windows': - file += '.exe' - if path is None: - path = os.environ.get('PATH', '') - if type(path) is type(''): - path = path.split(os.pathsep) - return list(filter(os.path.exists, - map(lambda dir, file=file: os.path.join(dir, file), path))) - -def find_7zip(log = EmptyLogger()): - ''' - Attempts to find 7zip for unpacking the mingw-build archives - ''' - log.info('finding 7zip') - path = find_in_path('7z') - if not path: - key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\7-Zip') - path, _ = winreg.QueryValueEx(key, 'Path') - path = [os.path.join(path, '7z.exe')] - log.debug('found \'%s\'', path[0]) - return path[0] - -find_7zip() - -def unpack(archive, location, log = EmptyLogger()): - ''' - Unpacks a mingw-builds archive - ''' - sevenzip = find_7zip(log) - log.info('unpacking %s', os.path.basename(archive)) - cmd = [sevenzip, 'x', archive, '-o' + location, '-y'] - log.debug(' - %r', cmd) - with open(os.devnull, 'w') as devnull: - subprocess.check_call(cmd, stdout = devnull) - -def download(url, location, log = EmptyLogger()): - ''' - Downloads and unpacks a mingw-builds archive - ''' - log.info('downloading MinGW') - log.debug(' - url: %s', url) - log.debug(' - location: %s', location) - - re_content = re.compile(r'attachment;[ \t]*filename=(")?([^"]*)(")?[\r\n]*') - - stream = request.urlopen(url) - try: - content = stream.getheader('Content-Disposition') or '' - except AttributeError: - content = stream.headers.getheader('Content-Disposition') or '' - matches = re_content.match(content) - if matches: - filename = matches.group(2) - else: - parsed = parse.urlparse(stream.geturl()) - filename = os.path.basename(parsed.path) - - try: - os.makedirs(location) - except OSError as e: - if e.errno == errno.EEXIST and os.path.isdir(location): - pass - else: - raise - - archive = os.path.join(location, filename) - with open(archive, 'wb') as out: - while True: - buf = stream.read(1024) - if not buf: - break - out.write(buf) - unpack(archive, location, log = log) - os.remove(archive) - - possible = os.path.join(location, 'mingw64') - if not os.path.exists(possible): - possible = os.path.join(location, 'mingw32') - if not os.path.exists(possible): - raise ValueError('Failed to find unpacked MinGW: ' + possible) - return possible - -def root(location = None, arch = None, version = None, threading = None, - exceptions = None, revision = None, log = EmptyLogger()): - ''' - Returns the root folder of a specific version of the mingw-builds variant - of gcc. Will download the compiler if needed - ''' - - # Get the repository if we don't have all the information - if not (arch and version and threading and exceptions and revision): - versions = repository(log = log) - - # Determine some defaults - version = version or max(versions.keys()) - if not arch: - arch = platform.machine().lower() - if arch == 'x86': - arch = 'i686' - elif arch == 'amd64': - arch = 'x86_64' - if not threading: - keys = versions[version][arch].keys() - if 'posix' in keys: - threading = 'posix' - elif 'win32' in keys: - threading = 'win32' - else: - threading = keys[0] - if not exceptions: - keys = versions[version][arch][threading].keys() - if 'seh' in keys: - exceptions = 'seh' - elif 'sjlj' in keys: - exceptions = 'sjlj' - else: - exceptions = keys[0] - if revision == None: - revision = max(versions[version][arch][threading][exceptions].keys()) - if not location: - location = os.path.join(tempfile.gettempdir(), 'mingw-builds') - - # Get the download url - url = versions[version][arch][threading][exceptions][revision] - - # Tell the user whatzzup - log.info('finding MinGW %s', '.'.join(str(v) for v in version)) - log.debug(' - arch: %s', arch) - log.debug(' - threading: %s', threading) - log.debug(' - exceptions: %s', exceptions) - log.debug(' - revision: %s', revision) - log.debug(' - url: %s', url) - - # Store each specific revision differently - slug = '{version}-{arch}-{threading}-{exceptions}-rev{revision}' - slug = slug.format( - version = '.'.join(str(v) for v in version), - arch = arch, - threading = threading, - exceptions = exceptions, - revision = revision - ) - if arch == 'x86_64': - root_dir = os.path.join(location, slug, 'mingw64') - elif arch == 'i686': - root_dir = os.path.join(location, slug, 'mingw32') - else: - raise ValueError('Unknown MinGW arch: ' + arch) - - # Download if needed - if not os.path.exists(root_dir): - downloaded = download(url, os.path.join(location, slug), log = log) - if downloaded != root_dir: - raise ValueError('The location of mingw did not match\n%s\n%s' - % (downloaded, root_dir)) - - return root_dir - -def str2ver(string): - ''' - Converts a version string into a tuple - ''' - try: - version = tuple(int(v) for v in string.split('.')) - if len(version) is not 3: - raise ValueError() - except ValueError: - raise argparse.ArgumentTypeError( - 'please provide a three digit version string') - return version - -def main(): - ''' - Invoked when the script is run directly by the python interpreter - ''' - parser = argparse.ArgumentParser( - description = 'Downloads a specific version of MinGW', - formatter_class = argparse.ArgumentDefaultsHelpFormatter - ) - parser.add_argument('--location', - help = 'the location to download the compiler to', - default = os.path.join(tempfile.gettempdir(), 'mingw-builds')) - parser.add_argument('--arch', required = True, choices = ['i686', 'x86_64'], - help = 'the target MinGW architecture string') - parser.add_argument('--version', type = str2ver, - help = 'the version of GCC to download') - parser.add_argument('--threading', choices = ['posix', 'win32'], - help = 'the threading type of the compiler') - parser.add_argument('--exceptions', choices = ['sjlj', 'seh', 'dwarf'], - help = 'the method to throw exceptions') - parser.add_argument('--revision', type=int, - help = 'the revision of the MinGW release') - group = parser.add_mutually_exclusive_group() - group.add_argument('-v', '--verbose', action='store_true', - help='increase the script output verbosity') - group.add_argument('-q', '--quiet', action='store_true', - help='only print errors and warning') - args = parser.parse_args() - - # Create the logger - logger = logging.getLogger('mingw') - handler = logging.StreamHandler() - formatter = logging.Formatter('%(message)s') - handler.setFormatter(formatter) - logger.addHandler(handler) - logger.setLevel(logging.INFO) - if args.quiet: - logger.setLevel(logging.WARN) - if args.verbose: - logger.setLevel(logging.DEBUG) - - # Get MinGW - root_dir = root(location = args.location, arch = args.arch, - version = args.version, threading = args.threading, - exceptions = args.exceptions, revision = args.revision, - log = logger) - - sys.stdout.write('%s\n' % os.path.join(root_dir, 'bin')) - -if __name__ == '__main__': - try: - main() - except IOError as e: - sys.stderr.write('IO error: %s\n' % e) - sys.exit(1) - except OSError as e: - sys.stderr.write('OS error: %s\n' % e) - sys.exit(1) - except KeyboardInterrupt as e: - sys.stderr.write('Killed\n') - sys.exit(1) diff --git a/thirdparty_builtin/benchmark-1.5.0/releasing.md b/thirdparty_builtin/benchmark-1.5.0/releasing.md deleted file mode 100644 index f0cd7010e..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/releasing.md +++ /dev/null @@ -1,16 +0,0 @@ -# How to release - -* Make sure you're on master and synced to HEAD -* Ensure the project builds and tests run (sanity check only, obviously) - * `parallel -j0 exec ::: test/*_test` can help ensure everything at least - passes -* Prepare release notes - * `git log $(git describe --abbrev=0 --tags)..HEAD` gives you the list of - commits between the last annotated tag and HEAD - * Pick the most interesting. -* Create a release through github's interface - * Note this will create a lightweight tag. - * Update this to an annotated tag: - * `git pull --tags` - * `git tag -a -f ` - * `git push --force origin` diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark.cc b/thirdparty_builtin/benchmark-1.5.0/src/benchmark.cc deleted file mode 100644 index 29bfa3512..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark.cc +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "benchmark_api_internal.h" -#include "benchmark_runner.h" -#include "internal_macros.h" - -#ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "colorprint.h" -#include "commandlineflags.h" -#include "complexity.h" -#include "counter.h" -#include "internal_macros.h" -#include "log.h" -#include "mutex.h" -#include "re.h" -#include "statistics.h" -#include "string_util.h" -#include "thread_manager.h" -#include "thread_timer.h" - -DEFINE_bool(benchmark_list_tests, false, - "Print a list of benchmarks. This option overrides all other " - "options."); - -DEFINE_string(benchmark_filter, ".", - "A regular expression that specifies the set of benchmarks " - "to execute. If this flag is empty, or if this flag is the " - "string \"all\", all benchmarks linked into the binary are " - "run."); - -DEFINE_double(benchmark_min_time, 0.5, - "Minimum number of seconds we should run benchmark before " - "results are considered significant. For cpu-time based " - "tests, this is the lower bound on the total cpu time " - "used by all threads that make up the test. For real-time " - "based tests, this is the lower bound on the elapsed time " - "of the benchmark execution, regardless of number of " - "threads."); - -DEFINE_int32(benchmark_repetitions, 1, - "The number of runs of each benchmark. If greater than 1, the " - "mean and standard deviation of the runs will be reported."); - -DEFINE_bool( - benchmark_report_aggregates_only, false, - "Report the result of each benchmark repetitions. When 'true' is specified " - "only the mean, standard deviation, and other statistics are reported for " - "repeated benchmarks. Affects all reporters."); - -DEFINE_bool( - benchmark_display_aggregates_only, false, - "Display the result of each benchmark repetitions. When 'true' is " - "specified only the mean, standard deviation, and other statistics are " - "displayed for repeated benchmarks. Unlike " - "benchmark_report_aggregates_only, only affects the display reporter, but " - "*NOT* file reporter, which will still contain all the output."); - -DEFINE_string(benchmark_format, "console", - "The format to use for console output. Valid values are " - "'console', 'json', or 'csv'."); - -DEFINE_string(benchmark_out_format, "json", - "The format to use for file output. Valid values are " - "'console', 'json', or 'csv'."); - -DEFINE_string(benchmark_out, "", "The file to write additional output to"); - -DEFINE_string(benchmark_color, "auto", - "Whether to use colors in the output. Valid values: " - "'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use " - "colors if the output is being sent to a terminal and the TERM " - "environment variable is set to a terminal type that supports " - "colors."); - -DEFINE_bool(benchmark_counters_tabular, false, - "Whether to use tabular format when printing user counters to " - "the console. Valid values: 'true'/'yes'/1, 'false'/'no'/0." - "Defaults to false."); - -DEFINE_int32(v, 0, "The level of verbose logging to output"); - -namespace benchmark { - -namespace internal { - -// FIXME: wouldn't LTO mess this up? -void UseCharPointer(char const volatile*) {} - -} // namespace internal - -State::State(IterationCount max_iters, const std::vector& ranges, - int thread_i, int n_threads, internal::ThreadTimer* timer, - internal::ThreadManager* manager) - : total_iterations_(0), - batch_leftover_(0), - max_iterations(max_iters), - started_(false), - finished_(false), - error_occurred_(false), - range_(ranges), - complexity_n_(0), - counters(), - thread_index(thread_i), - threads(n_threads), - timer_(timer), - manager_(manager) { - CHECK(max_iterations != 0) << "At least one iteration must be run"; - CHECK_LT(thread_index, threads) << "thread_index must be less than threads"; - - // Note: The use of offsetof below is technically undefined until C++17 - // because State is not a standard layout type. However, all compilers - // currently provide well-defined behavior as an extension (which is - // demonstrated since constexpr evaluation must diagnose all undefined - // behavior). However, GCC and Clang also warn about this use of offsetof, - // which must be suppressed. -#if defined(__INTEL_COMPILER) -#pragma warning push -#pragma warning(disable:1875) -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Winvalid-offsetof" -#endif - // Offset tests to ensure commonly accessed data is on the first cache line. - const int cache_line_size = 64; - static_assert(offsetof(State, error_occurred_) <= - (cache_line_size - sizeof(error_occurred_)), - ""); -#if defined(__INTEL_COMPILER) -#pragma warning pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif -} - -void State::PauseTiming() { - // Add in time accumulated so far - CHECK(started_ && !finished_ && !error_occurred_); - timer_->StopTimer(); -} - -void State::ResumeTiming() { - CHECK(started_ && !finished_ && !error_occurred_); - timer_->StartTimer(); -} - -void State::SkipWithError(const char* msg) { - CHECK(msg); - error_occurred_ = true; - { - MutexLock l(manager_->GetBenchmarkMutex()); - if (manager_->results.has_error_ == false) { - manager_->results.error_message_ = msg; - manager_->results.has_error_ = true; - } - } - total_iterations_ = 0; - if (timer_->running()) timer_->StopTimer(); -} - -void State::SetIterationTime(double seconds) { - timer_->SetIterationTime(seconds); -} - -void State::SetLabel(const char* label) { - MutexLock l(manager_->GetBenchmarkMutex()); - manager_->results.report_label_ = label; -} - -void State::StartKeepRunning() { - CHECK(!started_ && !finished_); - started_ = true; - total_iterations_ = error_occurred_ ? 0 : max_iterations; - manager_->StartStopBarrier(); - if (!error_occurred_) ResumeTiming(); -} - -void State::FinishKeepRunning() { - CHECK(started_ && (!finished_ || error_occurred_)); - if (!error_occurred_) { - PauseTiming(); - } - // Total iterations has now wrapped around past 0. Fix this. - total_iterations_ = 0; - finished_ = true; - manager_->StartStopBarrier(); -} - -namespace internal { -namespace { - -void RunBenchmarks(const std::vector& benchmarks, - BenchmarkReporter* display_reporter, - BenchmarkReporter* file_reporter) { - // Note the file_reporter can be null. - CHECK(display_reporter != nullptr); - - // Determine the width of the name field using a minimum width of 10. - bool might_have_aggregates = FLAGS_benchmark_repetitions > 1; - size_t name_field_width = 10; - size_t stat_field_width = 0; - for (const BenchmarkInstance& benchmark : benchmarks) { - name_field_width = - std::max(name_field_width, benchmark.name.str().size()); - might_have_aggregates |= benchmark.repetitions > 1; - - for (const auto& Stat : *benchmark.statistics) - stat_field_width = std::max(stat_field_width, Stat.name_.size()); - } - if (might_have_aggregates) name_field_width += 1 + stat_field_width; - - // Print header here - BenchmarkReporter::Context context; - context.name_field_width = name_field_width; - - // Keep track of running times of all instances of current benchmark - std::vector complexity_reports; - - // We flush streams after invoking reporter methods that write to them. This - // ensures users get timely updates even when streams are not line-buffered. - auto flushStreams = [](BenchmarkReporter* reporter) { - if (!reporter) return; - std::flush(reporter->GetOutputStream()); - std::flush(reporter->GetErrorStream()); - }; - - if (display_reporter->ReportContext(context) && - (!file_reporter || file_reporter->ReportContext(context))) { - flushStreams(display_reporter); - flushStreams(file_reporter); - - for (const auto& benchmark : benchmarks) { - RunResults run_results = RunBenchmark(benchmark, &complexity_reports); - - auto report = [&run_results](BenchmarkReporter* reporter, - bool report_aggregates_only) { - assert(reporter); - // If there are no aggregates, do output non-aggregates. - report_aggregates_only &= !run_results.aggregates_only.empty(); - if (!report_aggregates_only) - reporter->ReportRuns(run_results.non_aggregates); - if (!run_results.aggregates_only.empty()) - reporter->ReportRuns(run_results.aggregates_only); - }; - - report(display_reporter, run_results.display_report_aggregates_only); - if (file_reporter) - report(file_reporter, run_results.file_report_aggregates_only); - - flushStreams(display_reporter); - flushStreams(file_reporter); - } - } - display_reporter->Finalize(); - if (file_reporter) file_reporter->Finalize(); - flushStreams(display_reporter); - flushStreams(file_reporter); -} - -std::unique_ptr CreateReporter( - std::string const& name, ConsoleReporter::OutputOptions output_opts) { - typedef std::unique_ptr PtrType; - if (name == "console") { - return PtrType(new ConsoleReporter(output_opts)); - } else if (name == "json") { - return PtrType(new JSONReporter); - } else if (name == "csv") { - return PtrType(new CSVReporter); - } else { - std::cerr << "Unexpected format: '" << name << "'\n"; - std::exit(1); - } -} - -} // end namespace - -bool IsZero(double n) { - return std::abs(n) < std::numeric_limits::epsilon(); -} - -ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) { - int output_opts = ConsoleReporter::OO_Defaults; - auto is_benchmark_color = [force_no_color] () -> bool { - if (force_no_color) { - return false; - } - if (FLAGS_benchmark_color == "auto") { - return IsColorTerminal(); - } - return IsTruthyFlagValue(FLAGS_benchmark_color); - }; - if (is_benchmark_color()) { - output_opts |= ConsoleReporter::OO_Color; - } else { - output_opts &= ~ConsoleReporter::OO_Color; - } - if (FLAGS_benchmark_counters_tabular) { - output_opts |= ConsoleReporter::OO_Tabular; - } else { - output_opts &= ~ConsoleReporter::OO_Tabular; - } - return static_cast(output_opts); -} - -} // end namespace internal - -size_t RunSpecifiedBenchmarks() { - return RunSpecifiedBenchmarks(nullptr, nullptr); -} - -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) { - return RunSpecifiedBenchmarks(display_reporter, nullptr); -} - -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, - BenchmarkReporter* file_reporter) { - std::string spec = FLAGS_benchmark_filter; - if (spec.empty() || spec == "all") - spec = "."; // Regexp that matches all benchmarks - - // Setup the reporters - std::ofstream output_file; - std::unique_ptr default_display_reporter; - std::unique_ptr default_file_reporter; - if (!display_reporter) { - default_display_reporter = internal::CreateReporter( - FLAGS_benchmark_format, internal::GetOutputOptions()); - display_reporter = default_display_reporter.get(); - } - auto& Out = display_reporter->GetOutputStream(); - auto& Err = display_reporter->GetErrorStream(); - - std::string const& fname = FLAGS_benchmark_out; - if (fname.empty() && file_reporter) { - Err << "A custom file reporter was provided but " - "--benchmark_out= was not specified." - << std::endl; - std::exit(1); - } - if (!fname.empty()) { - output_file.open(fname); - if (!output_file.is_open()) { - Err << "invalid file name: '" << fname << std::endl; - std::exit(1); - } - if (!file_reporter) { - default_file_reporter = internal::CreateReporter( - FLAGS_benchmark_out_format, ConsoleReporter::OO_None); - file_reporter = default_file_reporter.get(); - } - file_reporter->SetOutputStream(&output_file); - file_reporter->SetErrorStream(&output_file); - } - - std::vector benchmarks; - if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0; - - if (benchmarks.empty()) { - Err << "Failed to match any benchmarks against regex: " << spec << "\n"; - return 0; - } - - if (FLAGS_benchmark_list_tests) { - for (auto const& benchmark : benchmarks) - Out << benchmark.name.str() << "\n"; - } else { - internal::RunBenchmarks(benchmarks, display_reporter, file_reporter); - } - - return benchmarks.size(); -} - -void RegisterMemoryManager(MemoryManager* manager) { - internal::memory_manager = manager; -} - -namespace internal { - -void PrintUsageAndExit() { - fprintf(stdout, - "benchmark" - " [--benchmark_list_tests={true|false}]\n" - " [--benchmark_filter=]\n" - " [--benchmark_min_time=]\n" - " [--benchmark_repetitions=]\n" - " [--benchmark_report_aggregates_only={true|false}]\n" - " [--benchmark_display_aggregates_only={true|false}]\n" - " [--benchmark_format=]\n" - " [--benchmark_out=]\n" - " [--benchmark_out_format=]\n" - " [--benchmark_color={auto|true|false}]\n" - " [--benchmark_counters_tabular={true|false}]\n" - " [--v=]\n"); - exit(0); -} - -void ParseCommandLineFlags(int* argc, char** argv) { - using namespace benchmark; - BenchmarkReporter::Context::executable_name = - (argc && *argc > 0) ? argv[0] : "unknown"; - for (int i = 1; i < *argc; ++i) { - if (ParseBoolFlag(argv[i], "benchmark_list_tests", - &FLAGS_benchmark_list_tests) || - ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) || - ParseDoubleFlag(argv[i], "benchmark_min_time", - &FLAGS_benchmark_min_time) || - ParseInt32Flag(argv[i], "benchmark_repetitions", - &FLAGS_benchmark_repetitions) || - ParseBoolFlag(argv[i], "benchmark_report_aggregates_only", - &FLAGS_benchmark_report_aggregates_only) || - ParseBoolFlag(argv[i], "benchmark_display_aggregates_only", - &FLAGS_benchmark_display_aggregates_only) || - ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) || - ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) || - ParseStringFlag(argv[i], "benchmark_out_format", - &FLAGS_benchmark_out_format) || - ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) || - // "color_print" is the deprecated name for "benchmark_color". - // TODO: Remove this. - ParseStringFlag(argv[i], "color_print", &FLAGS_benchmark_color) || - ParseBoolFlag(argv[i], "benchmark_counters_tabular", - &FLAGS_benchmark_counters_tabular) || - ParseInt32Flag(argv[i], "v", &FLAGS_v)) { - for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1]; - - --(*argc); - --i; - } else if (IsFlag(argv[i], "help")) { - PrintUsageAndExit(); - } - } - for (auto const* flag : - {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format}) - if (*flag != "console" && *flag != "json" && *flag != "csv") { - PrintUsageAndExit(); - } - if (FLAGS_benchmark_color.empty()) { - PrintUsageAndExit(); - } -} - -int InitializeStreams() { - static std::ios_base::Init init; - return 0; -} - -} // end namespace internal - -void Initialize(int* argc, char** argv) { - internal::ParseCommandLineFlags(argc, argv); - internal::LogLevel() = FLAGS_v; -} - -bool ReportUnrecognizedArguments(int argc, char** argv) { - for (int i = 1; i < argc; ++i) { - fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], - argv[i]); - } - return argc > 1; -} - -} // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_api_internal.cc b/thirdparty_builtin/benchmark-1.5.0/src/benchmark_api_internal.cc deleted file mode 100644 index d468a257e..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_api_internal.cc +++ /dev/null @@ -1,15 +0,0 @@ -#include "benchmark_api_internal.h" - -namespace benchmark { -namespace internal { - -State BenchmarkInstance::Run(IterationCount iters, int thread_id, - internal::ThreadTimer* timer, - internal::ThreadManager* manager) const { - State st(iters, arg, thread_id, threads, timer, manager); - benchmark->Run(st); - return st; -} - -} // internal -} // benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_api_internal.h b/thirdparty_builtin/benchmark-1.5.0/src/benchmark_api_internal.h deleted file mode 100644 index 264eff95c..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_api_internal.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef BENCHMARK_API_INTERNAL_H -#define BENCHMARK_API_INTERNAL_H - -#include "benchmark/benchmark.h" -#include "commandlineflags.h" - -#include -#include -#include -#include -#include -#include - -namespace benchmark { -namespace internal { - -// Information kept per benchmark we may want to run -struct BenchmarkInstance { - BenchmarkName name; - Benchmark* benchmark; - AggregationReportMode aggregation_report_mode; - std::vector arg; - TimeUnit time_unit; - int range_multiplier; - bool measure_process_cpu_time; - bool use_real_time; - bool use_manual_time; - BigO complexity; - BigOFunc* complexity_lambda; - UserCounters counters; - const std::vector* statistics; - bool last_benchmark_instance; - int repetitions; - double min_time; - IterationCount iterations; - int threads; // Number of concurrent threads to us - - State Run(IterationCount iters, int thread_id, internal::ThreadTimer* timer, - internal::ThreadManager* manager) const; -}; - -bool FindBenchmarksInternal(const std::string& re, - std::vector* benchmarks, - std::ostream* Err); - -bool IsZero(double n); - -ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color = false); - -} // end namespace internal -} // end namespace benchmark - -#endif // BENCHMARK_API_INTERNAL_H diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_runner.cc b/thirdparty_builtin/benchmark-1.5.0/src/benchmark_runner.cc deleted file mode 100644 index 0bae6a545..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_runner.cc +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark_runner.h" -#include "benchmark/benchmark.h" -#include "benchmark_api_internal.h" -#include "internal_macros.h" - -#ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "colorprint.h" -#include "commandlineflags.h" -#include "complexity.h" -#include "counter.h" -#include "internal_macros.h" -#include "log.h" -#include "mutex.h" -#include "re.h" -#include "statistics.h" -#include "string_util.h" -#include "thread_manager.h" -#include "thread_timer.h" - -namespace benchmark { - -namespace internal { - -MemoryManager* memory_manager = nullptr; - -namespace { - -static constexpr IterationCount kMaxIterations = 1000000000; - -BenchmarkReporter::Run CreateRunReport( - const benchmark::internal::BenchmarkInstance& b, - const internal::ThreadManager::Result& results, - IterationCount memory_iterations, - const MemoryManager::Result& memory_result, double seconds, - int64_t repetition_index) { - // Create report about this benchmark run. - BenchmarkReporter::Run report; - - report.run_name = b.name; - report.error_occurred = results.has_error_; - report.error_message = results.error_message_; - report.report_label = results.report_label_; - // This is the total iterations across all threads. - report.iterations = results.iterations; - report.time_unit = b.time_unit; - report.threads = b.threads; - report.repetition_index = repetition_index; - report.repetitions = b.repetitions; - - if (!report.error_occurred) { - if (b.use_manual_time) { - report.real_accumulated_time = results.manual_time_used; - } else { - report.real_accumulated_time = results.real_time_used; - } - report.cpu_accumulated_time = results.cpu_time_used; - report.complexity_n = results.complexity_n; - report.complexity = b.complexity; - report.complexity_lambda = b.complexity_lambda; - report.statistics = b.statistics; - report.counters = results.counters; - - if (memory_iterations > 0) { - report.has_memory_result = true; - report.allocs_per_iter = - memory_iterations ? static_cast(memory_result.num_allocs) / - memory_iterations - : 0; - report.max_bytes_used = memory_result.max_bytes_used; - } - - internal::Finish(&report.counters, results.iterations, seconds, b.threads); - } - return report; -} - -// Execute one thread of benchmark b for the specified number of iterations. -// Adds the stats collected for the thread into *total. -void RunInThread(const BenchmarkInstance* b, IterationCount iters, - int thread_id, ThreadManager* manager) { - internal::ThreadTimer timer( - b->measure_process_cpu_time - ? internal::ThreadTimer::CreateProcessCpuTime() - : internal::ThreadTimer::Create()); - State st = b->Run(iters, thread_id, &timer, manager); - CHECK(st.iterations() >= st.max_iterations) - << "Benchmark returned before State::KeepRunning() returned false!"; - { - MutexLock l(manager->GetBenchmarkMutex()); - internal::ThreadManager::Result& results = manager->results; - results.iterations += st.iterations(); - results.cpu_time_used += timer.cpu_time_used(); - results.real_time_used += timer.real_time_used(); - results.manual_time_used += timer.manual_time_used(); - results.complexity_n += st.complexity_length_n(); - internal::Increment(&results.counters, st.counters); - } - manager->NotifyThreadComplete(); -} - -class BenchmarkRunner { - public: - BenchmarkRunner(const benchmark::internal::BenchmarkInstance& b_, - std::vector* complexity_reports_) - : b(b_), - complexity_reports(*complexity_reports_), - min_time(!IsZero(b.min_time) ? b.min_time : FLAGS_benchmark_min_time), - repeats(b.repetitions != 0 ? b.repetitions - : FLAGS_benchmark_repetitions), - has_explicit_iteration_count(b.iterations != 0), - pool(b.threads - 1), - iters(has_explicit_iteration_count ? b.iterations : 1) { - run_results.display_report_aggregates_only = - (FLAGS_benchmark_report_aggregates_only || - FLAGS_benchmark_display_aggregates_only); - run_results.file_report_aggregates_only = - FLAGS_benchmark_report_aggregates_only; - if (b.aggregation_report_mode != internal::ARM_Unspecified) { - run_results.display_report_aggregates_only = - (b.aggregation_report_mode & - internal::ARM_DisplayReportAggregatesOnly); - run_results.file_report_aggregates_only = - (b.aggregation_report_mode & internal::ARM_FileReportAggregatesOnly); - } - - for (int repetition_num = 0; repetition_num < repeats; repetition_num++) { - DoOneRepetition(repetition_num); - } - - // Calculate additional statistics - run_results.aggregates_only = ComputeStats(run_results.non_aggregates); - - // Maybe calculate complexity report - if ((b.complexity != oNone) && b.last_benchmark_instance) { - auto additional_run_stats = ComputeBigO(complexity_reports); - run_results.aggregates_only.insert(run_results.aggregates_only.end(), - additional_run_stats.begin(), - additional_run_stats.end()); - complexity_reports.clear(); - } - } - - RunResults&& get_results() { return std::move(run_results); } - - private: - RunResults run_results; - - const benchmark::internal::BenchmarkInstance& b; - std::vector& complexity_reports; - - const double min_time; - const int repeats; - const bool has_explicit_iteration_count; - - std::vector pool; - - IterationCount iters; // preserved between repetitions! - // So only the first repetition has to find/calculate it, - // the other repetitions will just use that precomputed iteration count. - - struct IterationResults { - internal::ThreadManager::Result results; - IterationCount iters; - double seconds; - }; - IterationResults DoNIterations() { - VLOG(2) << "Running " << b.name.str() << " for " << iters << "\n"; - - std::unique_ptr manager; - manager.reset(new internal::ThreadManager(b.threads)); - - // Run all but one thread in separate threads - for (std::size_t ti = 0; ti < pool.size(); ++ti) { - pool[ti] = std::thread(&RunInThread, &b, iters, static_cast(ti + 1), - manager.get()); - } - // And run one thread here directly. - // (If we were asked to run just one thread, we don't create new threads.) - // Yes, we need to do this here *after* we start the separate threads. - RunInThread(&b, iters, 0, manager.get()); - - // The main thread has finished. Now let's wait for the other threads. - manager->WaitForAllThreads(); - for (std::thread& thread : pool) thread.join(); - - IterationResults i; - // Acquire the measurements/counters from the manager, UNDER THE LOCK! - { - MutexLock l(manager->GetBenchmarkMutex()); - i.results = manager->results; - } - - // And get rid of the manager. - manager.reset(); - - // Adjust real/manual time stats since they were reported per thread. - i.results.real_time_used /= b.threads; - i.results.manual_time_used /= b.threads; - // If we were measuring whole-process CPU usage, adjust the CPU time too. - if (b.measure_process_cpu_time) i.results.cpu_time_used /= b.threads; - - VLOG(2) << "Ran in " << i.results.cpu_time_used << "/" - << i.results.real_time_used << "\n"; - - // So for how long were we running? - i.iters = iters; - // Base decisions off of real time if requested by this benchmark. - i.seconds = i.results.cpu_time_used; - if (b.use_manual_time) { - i.seconds = i.results.manual_time_used; - } else if (b.use_real_time) { - i.seconds = i.results.real_time_used; - } - - return i; - } - - IterationCount PredictNumItersNeeded(const IterationResults& i) const { - // See how much iterations should be increased by. - // Note: Avoid division by zero with max(seconds, 1ns). - double multiplier = min_time * 1.4 / std::max(i.seconds, 1e-9); - // If our last run was at least 10% of FLAGS_benchmark_min_time then we - // use the multiplier directly. - // Otherwise we use at most 10 times expansion. - // NOTE: When the last run was at least 10% of the min time the max - // expansion should be 14x. - bool is_significant = (i.seconds / min_time) > 0.1; - multiplier = is_significant ? multiplier : std::min(10.0, multiplier); - if (multiplier <= 1.0) multiplier = 2.0; - - // So what seems to be the sufficiently-large iteration count? Round up. - const IterationCount max_next_iters = - 0.5 + std::max(multiplier * i.iters, i.iters + 1.0); - // But we do have *some* sanity limits though.. - const IterationCount next_iters = std::min(max_next_iters, kMaxIterations); - - VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n"; - return next_iters; // round up before conversion to integer. - } - - bool ShouldReportIterationResults(const IterationResults& i) const { - // Determine if this run should be reported; - // Either it has run for a sufficient amount of time - // or because an error was reported. - return i.results.has_error_ || - i.iters >= kMaxIterations || // Too many iterations already. - i.seconds >= min_time || // The elapsed time is large enough. - // CPU time is specified but the elapsed real time greatly exceeds - // the minimum time. - // Note that user provided timers are except from this sanity check. - ((i.results.real_time_used >= 5 * min_time) && !b.use_manual_time); - } - - void DoOneRepetition(int64_t repetition_index) { - const bool is_the_first_repetition = repetition_index == 0; - IterationResults i; - - // We *may* be gradually increasing the length (iteration count) - // of the benchmark until we decide the results are significant. - // And once we do, we report those last results and exit. - // Please do note that the if there are repetitions, the iteration count - // is *only* calculated for the *first* repetition, and other repetitions - // simply use that precomputed iteration count. - for (;;) { - i = DoNIterations(); - - // Do we consider the results to be significant? - // If we are doing repetitions, and the first repetition was already done, - // it has calculated the correct iteration time, so we have run that very - // iteration count just now. No need to calculate anything. Just report. - // Else, the normal rules apply. - const bool results_are_significant = !is_the_first_repetition || - has_explicit_iteration_count || - ShouldReportIterationResults(i); - - if (results_are_significant) break; // Good, let's report them! - - // Nope, bad iteration. Let's re-estimate the hopefully-sufficient - // iteration count, and run the benchmark again... - - iters = PredictNumItersNeeded(i); - assert(iters > i.iters && - "if we did more iterations than we want to do the next time, " - "then we should have accepted the current iteration run."); - } - - // Oh, one last thing, we need to also produce the 'memory measurements'.. - MemoryManager::Result memory_result; - IterationCount memory_iterations = 0; - if (memory_manager != nullptr) { - // Only run a few iterations to reduce the impact of one-time - // allocations in benchmarks that are not properly managed. - memory_iterations = std::min(16, iters); - memory_manager->Start(); - std::unique_ptr manager; - manager.reset(new internal::ThreadManager(1)); - RunInThread(&b, memory_iterations, 0, manager.get()); - manager->WaitForAllThreads(); - manager.reset(); - - memory_manager->Stop(&memory_result); - } - - // Ok, now actualy report. - BenchmarkReporter::Run report = - CreateRunReport(b, i.results, memory_iterations, memory_result, - i.seconds, repetition_index); - - if (!report.error_occurred && b.complexity != oNone) - complexity_reports.push_back(report); - - run_results.non_aggregates.push_back(report); - } -}; - -} // end namespace - -RunResults RunBenchmark( - const benchmark::internal::BenchmarkInstance& b, - std::vector* complexity_reports) { - internal::BenchmarkRunner r(b, complexity_reports); - return r.get_results(); -} - -} // end namespace internal - -} // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_runner.h b/thirdparty_builtin/benchmark-1.5.0/src/benchmark_runner.h deleted file mode 100644 index 96e8282a1..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_runner.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef BENCHMARK_RUNNER_H_ -#define BENCHMARK_RUNNER_H_ - -#include "benchmark_api_internal.h" -#include "internal_macros.h" - -DECLARE_double(benchmark_min_time); - -DECLARE_int32(benchmark_repetitions); - -DECLARE_bool(benchmark_report_aggregates_only); - -DECLARE_bool(benchmark_display_aggregates_only); - -namespace benchmark { - -namespace internal { - -extern MemoryManager* memory_manager; - -struct RunResults { - std::vector non_aggregates; - std::vector aggregates_only; - - bool display_report_aggregates_only = false; - bool file_report_aggregates_only = false; -}; - -RunResults RunBenchmark( - const benchmark::internal::BenchmarkInstance& b, - std::vector* complexity_reports); - -} // namespace internal - -} // end namespace benchmark - -#endif // BENCHMARK_RUNNER_H_ diff --git a/thirdparty_builtin/benchmark-1.5.0/src/check.h b/thirdparty_builtin/benchmark-1.5.0/src/check.h deleted file mode 100644 index f5f8253f8..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/check.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef CHECK_H_ -#define CHECK_H_ - -#include -#include -#include - -#include "internal_macros.h" -#include "log.h" - -namespace benchmark { -namespace internal { - -typedef void(AbortHandlerT)(); - -inline AbortHandlerT*& GetAbortHandler() { - static AbortHandlerT* handler = &std::abort; - return handler; -} - -BENCHMARK_NORETURN inline void CallAbortHandler() { - GetAbortHandler()(); - std::abort(); // fallback to enforce noreturn -} - -// CheckHandler is the class constructed by failing CHECK macros. CheckHandler -// will log information about the failures and abort when it is destructed. -class CheckHandler { - public: - CheckHandler(const char* check, const char* file, const char* func, int line) - : log_(GetErrorLogInstance()) { - log_ << file << ":" << line << ": " << func << ": Check `" << check - << "' failed. "; - } - - LogType& GetLog() { return log_; } - - BENCHMARK_NORETURN ~CheckHandler() BENCHMARK_NOEXCEPT_OP(false) { - log_ << std::endl; - CallAbortHandler(); - } - - CheckHandler& operator=(const CheckHandler&) = delete; - CheckHandler(const CheckHandler&) = delete; - CheckHandler() = delete; - - private: - LogType& log_; -}; - -} // end namespace internal -} // end namespace benchmark - -// The CHECK macro returns a std::ostream object that can have extra information -// written to it. -#ifndef NDEBUG -#define CHECK(b) \ - (b ? ::benchmark::internal::GetNullLogInstance() \ - : ::benchmark::internal::CheckHandler(#b, __FILE__, __func__, __LINE__) \ - .GetLog()) -#else -#define CHECK(b) ::benchmark::internal::GetNullLogInstance() -#endif - -// clang-format off -// preserve whitespacing between operators for alignment -#define CHECK_EQ(a, b) CHECK((a) == (b)) -#define CHECK_NE(a, b) CHECK((a) != (b)) -#define CHECK_GE(a, b) CHECK((a) >= (b)) -#define CHECK_LE(a, b) CHECK((a) <= (b)) -#define CHECK_GT(a, b) CHECK((a) > (b)) -#define CHECK_LT(a, b) CHECK((a) < (b)) - -#define CHECK_FLOAT_EQ(a, b, eps) CHECK(std::fabs((a) - (b)) < (eps)) -#define CHECK_FLOAT_NE(a, b, eps) CHECK(std::fabs((a) - (b)) >= (eps)) -#define CHECK_FLOAT_GE(a, b, eps) CHECK((a) - (b) > -(eps)) -#define CHECK_FLOAT_LE(a, b, eps) CHECK((b) - (a) > -(eps)) -#define CHECK_FLOAT_GT(a, b, eps) CHECK((a) - (b) > (eps)) -#define CHECK_FLOAT_LT(a, b, eps) CHECK((b) - (a) > (eps)) -//clang-format on - -#endif // CHECK_H_ diff --git a/thirdparty_builtin/benchmark-1.5.0/src/commandlineflags.h b/thirdparty_builtin/benchmark-1.5.0/src/commandlineflags.h deleted file mode 100644 index 5eaea82a5..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/commandlineflags.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef BENCHMARK_COMMANDLINEFLAGS_H_ -#define BENCHMARK_COMMANDLINEFLAGS_H_ - -#include -#include - -// Macro for referencing flags. -#define FLAG(name) FLAGS_##name - -// Macros for declaring flags. -#define DECLARE_bool(name) extern bool FLAG(name) -#define DECLARE_int32(name) extern int32_t FLAG(name) -#define DECLARE_int64(name) extern int64_t FLAG(name) -#define DECLARE_double(name) extern double FLAG(name) -#define DECLARE_string(name) extern std::string FLAG(name) - -// Macros for defining flags. -#define DEFINE_bool(name, default_val, doc) bool FLAG(name) = (default_val) -#define DEFINE_int32(name, default_val, doc) int32_t FLAG(name) = (default_val) -#define DEFINE_int64(name, default_val, doc) int64_t FLAG(name) = (default_val) -#define DEFINE_double(name, default_val, doc) double FLAG(name) = (default_val) -#define DEFINE_string(name, default_val, doc) \ - std::string FLAG(name) = (default_val) - -namespace benchmark { -// Parses a bool/Int32/string from the environment variable -// corresponding to the given Google Test flag. -bool BoolFromEnv(const char* flag, bool default_val); -int32_t Int32FromEnv(const char* flag, int32_t default_val); -const char* StringFromEnv(const char* flag, const char* default_val); - -// Parses a string for a bool flag, in the form of either -// "--flag=value" or "--flag". -// -// In the former case, the value is taken as true if it passes IsTruthyValue(). -// -// In the latter case, the value is taken as true. -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseBoolFlag(const char* str, const char* flag, bool* value); - -// Parses a string for an Int32 flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseInt32Flag(const char* str, const char* flag, int32_t* value); - -// Parses a string for a Double flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseDoubleFlag(const char* str, const char* flag, double* value); - -// Parses a string for a string flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseStringFlag(const char* str, const char* flag, std::string* value); - -// Returns true if the string matches the flag. -bool IsFlag(const char* str, const char* flag); - -// Returns true unless value starts with one of: '0', 'f', 'F', 'n' or 'N', or -// some non-alphanumeric character. As a special case, also returns true if -// value is the empty string. -bool IsTruthyFlagValue(const std::string& value); -} // end namespace benchmark - -#endif // BENCHMARK_COMMANDLINEFLAGS_H_ diff --git a/thirdparty_builtin/benchmark-1.5.0/src/sleep.cc b/thirdparty_builtin/benchmark-1.5.0/src/sleep.cc deleted file mode 100644 index 1512ac90f..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/sleep.cc +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "sleep.h" - -#include -#include -#include - -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#endif - -namespace benchmark { -#ifdef BENCHMARK_OS_WINDOWS -// Window's Sleep takes milliseconds argument. -void SleepForMilliseconds(int milliseconds) { Sleep(milliseconds); } -void SleepForSeconds(double seconds) { - SleepForMilliseconds(static_cast(kNumMillisPerSecond * seconds)); -} -#else // BENCHMARK_OS_WINDOWS -void SleepForMicroseconds(int microseconds) { - struct timespec sleep_time; - sleep_time.tv_sec = microseconds / kNumMicrosPerSecond; - sleep_time.tv_nsec = (microseconds % kNumMicrosPerSecond) * kNumNanosPerMicro; - while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) - ; // Ignore signals and wait for the full interval to elapse. -} - -void SleepForMilliseconds(int milliseconds) { - SleepForMicroseconds(milliseconds * kNumMicrosPerMilli); -} - -void SleepForSeconds(double seconds) { - SleepForMicroseconds(static_cast(seconds * kNumMicrosPerSecond)); -} -#endif // BENCHMARK_OS_WINDOWS -} // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/sleep.h b/thirdparty_builtin/benchmark-1.5.0/src/sleep.h deleted file mode 100644 index f98551afe..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/src/sleep.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef BENCHMARK_SLEEP_H_ -#define BENCHMARK_SLEEP_H_ - -namespace benchmark { -const int kNumMillisPerSecond = 1000; -const int kNumMicrosPerMilli = 1000; -const int kNumMicrosPerSecond = kNumMillisPerSecond * 1000; -const int kNumNanosPerMicro = 1000; -const int kNumNanosPerSecond = kNumNanosPerMicro * kNumMicrosPerSecond; - -void SleepForMilliseconds(int milliseconds); -void SleepForSeconds(double seconds); -} // end namespace benchmark - -#endif // BENCHMARK_SLEEP_H_ diff --git a/thirdparty_builtin/benchmark-1.5.0/test/BUILD b/thirdparty_builtin/benchmark-1.5.0/test/BUILD deleted file mode 100644 index 3f174c486..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/test/BUILD +++ /dev/null @@ -1,65 +0,0 @@ -TEST_COPTS = [ - "-pedantic", - "-pedantic-errors", - "-std=c++11", - "-Wall", - "-Wextra", - "-Wshadow", -# "-Wshorten-64-to-32", - "-Wfloat-equal", - "-fstrict-aliasing", -] - -PER_SRC_COPTS = ({ - "cxx03_test.cc": ["-std=c++03"], - # Some of the issues with DoNotOptimize only occur when optimization is enabled - "donotoptimize_test.cc": ["-O3"], -}) - - -TEST_ARGS = ["--benchmark_min_time=0.01"] - -PER_SRC_TEST_ARGS = ({ - "user_counters_tabular_test.cc": ["--benchmark_counters_tabular=true"], -}) - -cc_library( - name = "output_test_helper", - testonly = 1, - srcs = ["output_test_helper.cc"], - hdrs = ["output_test.h"], - copts = TEST_COPTS, - deps = [ - "//:benchmark", - "//:benchmark_internal_headers", - ], -) - -[ - cc_test( - name = test_src[:-len(".cc")], - size = "small", - srcs = [test_src], - args = TEST_ARGS + PER_SRC_TEST_ARGS.get(test_src, []), - copts = TEST_COPTS + PER_SRC_COPTS.get(test_src, []), - deps = [ - ":output_test_helper", - "//:benchmark", - "//:benchmark_internal_headers", - "@com_google_googletest//:gtest", - ] + ( - ["@com_google_googletest//:gtest_main"] if (test_src[-len("gtest.cc"):] == "gtest.cc") else [] - ), - # FIXME: Add support for assembly tests to bazel. - # See Issue #556 - # https://github.com/google/benchmark/issues/556 - ) for test_src in glob(["*test.cc"], exclude = ["*_assembly_test.cc", "link_main_test.cc"]) -] - -cc_test( - name = "link_main_test", - size = "small", - srcs = ["link_main_test.cc"], - copts = TEST_COPTS, - deps = ["//:benchmark_main"], -) diff --git a/thirdparty_builtin/benchmark-1.5.0/test/commandlineflags_gtest.cc b/thirdparty_builtin/benchmark-1.5.0/test/commandlineflags_gtest.cc deleted file mode 100644 index 5460778c4..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/test/commandlineflags_gtest.cc +++ /dev/null @@ -1,78 +0,0 @@ -#include - -#include "../src/commandlineflags.h" -#include "../src/internal_macros.h" -#include "gtest/gtest.h" - -namespace benchmark { -namespace { - -#if defined(BENCHMARK_OS_WINDOWS) -int setenv(const char* name, const char* value, int overwrite) { - if (!overwrite) { - // NOTE: getenv_s is far superior but not available under mingw. - char* env_value = getenv(name); - if (env_value == nullptr) { - return -1; - } - } - return _putenv_s(name, value); -} - -int unsetenv(const char* name) { - return _putenv_s(name, ""); -} - -#endif // BENCHMARK_OS_WINDOWS - -TEST(BoolFromEnv, Default) { - ASSERT_EQ(unsetenv("BENCHMARK_NOT_IN_ENV"), 0); - EXPECT_EQ(BoolFromEnv("not_in_env", true), true); -} - -TEST(BoolFromEnv, False) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "0", 1), 0); - EXPECT_EQ(BoolFromEnv("in_env", true), false); - unsetenv("BENCHMARK_IN_ENV"); -} - -TEST(BoolFromEnv, True) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "1", 1), 0); - EXPECT_EQ(BoolFromEnv("in_env", false), true); - unsetenv("BENCHMARK_IN_ENV"); - - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "foo", 1), 0); - EXPECT_EQ(BoolFromEnv("in_env", false), true); - unsetenv("BENCHMARK_IN_ENV"); -} - -TEST(Int32FromEnv, NotInEnv) { - ASSERT_EQ(unsetenv("BENCHMARK_NOT_IN_ENV"), 0); - EXPECT_EQ(Int32FromEnv("not_in_env", 42), 42); -} - -TEST(Int32FromEnv, InvalidInteger) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "foo", 1), 0); - EXPECT_EQ(Int32FromEnv("in_env", 42), 42); - ASSERT_EQ(unsetenv("BENCHMARK_IN_ENV"), 0); -} - -TEST(Int32FromEnv, ValidInteger) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "42", 1), 0); - EXPECT_EQ(Int32FromEnv("in_env", 64), 42); - unsetenv("BENCHMARK_IN_ENV"); -} - -TEST(StringFromEnv, Default) { - ASSERT_EQ(unsetenv("BENCHMARK_NOT_IN_ENV"), 0); - EXPECT_STREQ(StringFromEnv("not_in_env", "foo"), "foo"); -} - -TEST(StringFromEnv, Valid) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "foo", 1), 0); - EXPECT_STREQ(StringFromEnv("in_env", "bar"), "foo"); - unsetenv("BENCHMARK_IN_ENV"); -} - -} // namespace -} // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/test/fixture_test.cc b/thirdparty_builtin/benchmark-1.5.0/test/fixture_test.cc deleted file mode 100644 index 1462b10f0..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/test/fixture_test.cc +++ /dev/null @@ -1,49 +0,0 @@ - -#include "benchmark/benchmark.h" - -#include -#include - -class MyFixture : public ::benchmark::Fixture { - public: - void SetUp(const ::benchmark::State& state) { - if (state.thread_index == 0) { - assert(data.get() == nullptr); - data.reset(new int(42)); - } - } - - void TearDown(const ::benchmark::State& state) { - if (state.thread_index == 0) { - assert(data.get() != nullptr); - data.reset(); - } - } - - ~MyFixture() { assert(data == nullptr); } - - std::unique_ptr data; -}; - -BENCHMARK_F(MyFixture, Foo)(benchmark::State &st) { - assert(data.get() != nullptr); - assert(*data == 42); - for (auto _ : st) { - } -} - -BENCHMARK_DEFINE_F(MyFixture, Bar)(benchmark::State& st) { - if (st.thread_index == 0) { - assert(data.get() != nullptr); - assert(*data == 42); - } - for (auto _ : st) { - assert(data.get() != nullptr); - assert(*data == 42); - } - st.SetItemsProcessed(st.range(0)); -} -BENCHMARK_REGISTER_F(MyFixture, Bar)->Arg(42); -BENCHMARK_REGISTER_F(MyFixture, Bar)->Arg(42)->ThreadPerCpu(); - -BENCHMARK_MAIN(); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/string_util_gtest.cc b/thirdparty_builtin/benchmark-1.5.0/test/string_util_gtest.cc deleted file mode 100644 index 2c5d073f6..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/test/string_util_gtest.cc +++ /dev/null @@ -1,146 +0,0 @@ -//===---------------------------------------------------------------------===// -// statistics_test - Unit tests for src/statistics.cc -//===---------------------------------------------------------------------===// - -#include "../src/string_util.h" -#include "gtest/gtest.h" - -namespace { -TEST(StringUtilTest, stoul) { - { - size_t pos = 0; - EXPECT_EQ(0ul, benchmark::stoul("0", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(7ul, benchmark::stoul("7", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(135ul, benchmark::stoul("135", &pos)); - EXPECT_EQ(3ul, pos); - } -#if ULONG_MAX == 0xFFFFFFFFul - { - size_t pos = 0; - EXPECT_EQ(0xFFFFFFFFul, benchmark::stoul("4294967295", &pos)); - EXPECT_EQ(10ul, pos); - } -#elif ULONG_MAX == 0xFFFFFFFFFFFFFFFFul - { - size_t pos = 0; - EXPECT_EQ(0xFFFFFFFFFFFFFFFFul, benchmark::stoul("18446744073709551615", &pos)); - EXPECT_EQ(20ul, pos); - } -#endif - { - size_t pos = 0; - EXPECT_EQ(10ul, benchmark::stoul("1010", &pos, 2)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(520ul, benchmark::stoul("1010", &pos, 8)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1010ul, benchmark::stoul("1010", &pos, 10)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(4112ul, benchmark::stoul("1010", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(0xBEEFul, benchmark::stoul("BEEF", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - ASSERT_THROW(benchmark::stoul("this is a test"), std::invalid_argument); - } -} - -TEST(StringUtilTest, stoi) { - { - size_t pos = 0; - EXPECT_EQ(0, benchmark::stoi("0", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(-17, benchmark::stoi("-17", &pos)); - EXPECT_EQ(3ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1357, benchmark::stoi("1357", &pos)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(10, benchmark::stoi("1010", &pos, 2)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(520, benchmark::stoi("1010", &pos, 8)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1010, benchmark::stoi("1010", &pos, 10)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(4112, benchmark::stoi("1010", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(0xBEEF, benchmark::stoi("BEEF", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - ASSERT_THROW(benchmark::stoi("this is a test"), std::invalid_argument); - } -} - -TEST(StringUtilTest, stod) { - { - size_t pos = 0; - EXPECT_EQ(0.0, benchmark::stod("0", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(-84.0, benchmark::stod("-84", &pos)); - EXPECT_EQ(3ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1234.0, benchmark::stod("1234", &pos)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1.5, benchmark::stod("1.5", &pos)); - EXPECT_EQ(3ul, pos); - } - { - size_t pos = 0; - /* Note: exactly representable as double */ - EXPECT_EQ(-1.25e+9, benchmark::stod("-1.25e+9", &pos)); - EXPECT_EQ(8ul, pos); - } - { - ASSERT_THROW(benchmark::stod("this is a test"), std::invalid_argument); - } -} - -} // end namespace diff --git a/thirdparty_builtin/benchmark-1.5.0/test/user_counters_tabular_test.cc b/thirdparty_builtin/benchmark-1.5.0/test/user_counters_tabular_test.cc deleted file mode 100644 index 099464ef9..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/test/user_counters_tabular_test.cc +++ /dev/null @@ -1,283 +0,0 @@ - -#undef NDEBUG - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// @todo: this checks the full output at once; the rule for -// CounterSet1 was failing because it was not matching "^[-]+$". -// @todo: check that the counters are vertically aligned. -ADD_CASES( - TC_ConsoleOut, - { - // keeping these lines long improves readability, so: - // clang-format off - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Bat %s Baz %s Foo %s Frob %s Lob$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Baz %s Foo$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bat %s Baz %s Foo$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$"}, - // clang-format on - }); -ADD_CASES(TC_CSVOut, {{"%csv_header," - "\"Bar\",\"Bat\",\"Baz\",\"Foo\",\"Frob\",\"Lob\""}}); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -void BM_Counters_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {1, bm::Counter::kAvgThreads}}, - {"Bar", {2, bm::Counter::kAvgThreads}}, - {"Baz", {4, bm::Counter::kAvgThreads}}, - {"Bat", {8, bm::Counter::kAvgThreads}}, - {"Frob", {16, bm::Counter::kAvgThreads}}, - {"Lob", {32, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_Counters_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_Counters_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float,$", MR_Next}, - {"\"Frob\": %float,$", MR_Next}, - {"\"Lob\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Tabular/threads:%int\",%csv_report," - "%float,%float,%float,%float,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckTabular(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 1); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 2); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 4); - CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 8); - CHECK_COUNTER_VALUE(e, int, "Frob", EQ, 16); - CHECK_COUNTER_VALUE(e, int, "Lob", EQ, 32); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Tabular/threads:%int", &CheckTabular); - -// ========================================================================= // -// -------------------- Tabular+Rate Counters Output ----------------------- // -// ========================================================================= // - -void BM_CounterRates_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {1, bm::Counter::kAvgThreadsRate}}, - {"Bar", {2, bm::Counter::kAvgThreadsRate}}, - {"Baz", {4, bm::Counter::kAvgThreadsRate}}, - {"Bat", {8, bm::Counter::kAvgThreadsRate}}, - {"Frob", {16, bm::Counter::kAvgThreadsRate}}, - {"Lob", {32, bm::Counter::kAvgThreadsRate}}, - }); -} -BENCHMARK(BM_CounterRates_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterRates_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterRates_Tabular/threads:%int\",$", - MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float,$", MR_Next}, - {"\"Frob\": %float,$", MR_Next}, - {"\"Lob\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterRates_Tabular/threads:%int\",%csv_report," - "%float,%float,%float,%float,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckTabularRate(Results const& e) { - double t = e.DurationCPUTime(); - CHECK_FLOAT_COUNTER_VALUE(e, "Foo", EQ, 1. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Bar", EQ, 2. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Baz", EQ, 4. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Bat", EQ, 8. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Frob", EQ, 16. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Lob", EQ, 32. / t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_CounterRates_Tabular/threads:%int", - &CheckTabularRate); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -// set only some of the counters -void BM_CounterSet0_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {10, bm::Counter::kAvgThreads}}, - {"Bar", {20, bm::Counter::kAvgThreads}}, - {"Baz", {40, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet0_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterSet0_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterSet0_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet0_Tabular/threads:%int\",%csv_report," - "%float,,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet0(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 20); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet0_Tabular", &CheckSet0); - -// again. -void BM_CounterSet1_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {15, bm::Counter::kAvgThreads}}, - {"Bar", {25, bm::Counter::kAvgThreads}}, - {"Baz", {45, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet1_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterSet1_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterSet1_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet1_Tabular/threads:%int\",%csv_report," - "%float,,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet1(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 15); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 25); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 45); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet1_Tabular/threads:%int", &CheckSet1); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -// set only some of the counters, different set now. -void BM_CounterSet2_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {10, bm::Counter::kAvgThreads}}, - {"Bat", {30, bm::Counter::kAvgThreads}}, - {"Baz", {40, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet2_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterSet2_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterSet2_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet2_Tabular/threads:%int\",%csv_report," - ",%float,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet2(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); - CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 30); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet2_Tabular", &CheckSet2); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/report.py b/thirdparty_builtin/benchmark-1.5.0/tools/gbench/report.py deleted file mode 100644 index 5bd3a8d85..000000000 --- a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/report.py +++ /dev/null @@ -1,541 +0,0 @@ -import unittest -"""report.py - Utilities for reporting statistics about benchmark results -""" -import os -import re -import copy - -from scipy.stats import mannwhitneyu - - -class BenchmarkColor(object): - def __init__(self, name, code): - self.name = name - self.code = code - - def __repr__(self): - return '%s%r' % (self.__class__.__name__, - (self.name, self.code)) - - def __format__(self, format): - return self.code - - -# Benchmark Colors Enumeration -BC_NONE = BenchmarkColor('NONE', '') -BC_MAGENTA = BenchmarkColor('MAGENTA', '\033[95m') -BC_CYAN = BenchmarkColor('CYAN', '\033[96m') -BC_OKBLUE = BenchmarkColor('OKBLUE', '\033[94m') -BC_OKGREEN = BenchmarkColor('OKGREEN', '\033[32m') -BC_HEADER = BenchmarkColor('HEADER', '\033[92m') -BC_WARNING = BenchmarkColor('WARNING', '\033[93m') -BC_WHITE = BenchmarkColor('WHITE', '\033[97m') -BC_FAIL = BenchmarkColor('FAIL', '\033[91m') -BC_ENDC = BenchmarkColor('ENDC', '\033[0m') -BC_BOLD = BenchmarkColor('BOLD', '\033[1m') -BC_UNDERLINE = BenchmarkColor('UNDERLINE', '\033[4m') - -UTEST_MIN_REPETITIONS = 2 -UTEST_OPTIMAL_REPETITIONS = 9 # Lowest reasonable number, More is better. -UTEST_COL_NAME = "_pvalue" - - -def color_format(use_color, fmt_str, *args, **kwargs): - """ - Return the result of 'fmt_str.format(*args, **kwargs)' after transforming - 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' - is False then all color codes in 'args' and 'kwargs' are replaced with - the empty string. - """ - assert use_color is True or use_color is False - if not use_color: - args = [arg if not isinstance(arg, BenchmarkColor) else BC_NONE - for arg in args] - kwargs = {key: arg if not isinstance(arg, BenchmarkColor) else BC_NONE - for key, arg in kwargs.items()} - return fmt_str.format(*args, **kwargs) - - -def find_longest_name(benchmark_list): - """ - Return the length of the longest benchmark name in a given list of - benchmark JSON objects - """ - longest_name = 1 - for bc in benchmark_list: - if len(bc['name']) > longest_name: - longest_name = len(bc['name']) - return longest_name - - -def calculate_change(old_val, new_val): - """ - Return a float representing the decimal change between old_val and new_val. - """ - if old_val == 0 and new_val == 0: - return 0.0 - if old_val == 0: - return float(new_val - old_val) / (float(old_val + new_val) / 2) - return float(new_val - old_val) / abs(old_val) - - -def filter_benchmark(json_orig, family, replacement=""): - """ - Apply a filter to the json, and only leave the 'family' of benchmarks. - """ - regex = re.compile(family) - filtered = {} - filtered['benchmarks'] = [] - for be in json_orig['benchmarks']: - if not regex.search(be['name']): - continue - filteredbench = copy.deepcopy(be) # Do NOT modify the old name! - filteredbench['name'] = regex.sub(replacement, filteredbench['name']) - filtered['benchmarks'].append(filteredbench) - return filtered - - -def get_unique_benchmark_names(json): - """ - While *keeping* the order, give all the unique 'names' used for benchmarks. - """ - seen = set() - uniqued = [x['name'] for x in json['benchmarks'] - if x['name'] not in seen and - (seen.add(x['name']) or True)] - return uniqued - - -def intersect(list1, list2): - """ - Given two lists, get a new list consisting of the elements only contained - in *both of the input lists*, while preserving the ordering. - """ - return [x for x in list1 if x in list2] - - -def is_potentially_comparable_benchmark(x): - return ('time_unit' in x and 'real_time' in x and 'cpu_time' in x) - - -def partition_benchmarks(json1, json2): - """ - While preserving the ordering, find benchmarks with the same names in - both of the inputs, and group them. - (i.e. partition/filter into groups with common name) - """ - json1_unique_names = get_unique_benchmark_names(json1) - json2_unique_names = get_unique_benchmark_names(json2) - names = intersect(json1_unique_names, json2_unique_names) - partitions = [] - for name in names: - time_unit = None - # Pick the time unit from the first entry of the lhs benchmark. - # We should be careful not to crash with unexpected input. - for x in json1['benchmarks']: - if (x['name'] == name and is_potentially_comparable_benchmark(x)): - time_unit = x['time_unit'] - break - if time_unit is None: - continue - # Filter by name and time unit. - # All the repetitions are assumed to be comparable. - lhs = [x for x in json1['benchmarks'] if x['name'] == name and - x['time_unit'] == time_unit] - rhs = [x for x in json2['benchmarks'] if x['name'] == name and - x['time_unit'] == time_unit] - partitions.append([lhs, rhs]) - return partitions - - -def extract_field(partition, field_name): - # The count of elements may be different. We want *all* of them. - lhs = [x[field_name] for x in partition[0]] - rhs = [x[field_name] for x in partition[1]] - return [lhs, rhs] - -def calc_utest(timings_cpu, timings_time): - min_rep_cnt = min(len(timings_time[0]), - len(timings_time[1]), - len(timings_cpu[0]), - len(timings_cpu[1])) - - # Does *everything* has at least UTEST_MIN_REPETITIONS repetitions? - if min_rep_cnt < UTEST_MIN_REPETITIONS: - return False, None, None - - time_pvalue = mannwhitneyu( - timings_time[0], timings_time[1], alternative='two-sided').pvalue - cpu_pvalue = mannwhitneyu( - timings_cpu[0], timings_cpu[1], alternative='two-sided').pvalue - - return (min_rep_cnt >= UTEST_OPTIMAL_REPETITIONS), cpu_pvalue, time_pvalue - -def print_utest(partition, utest_alpha, first_col_width, use_color=True): - def get_utest_color(pval): - return BC_FAIL if pval >= utest_alpha else BC_OKGREEN - - timings_time = extract_field(partition, 'real_time') - timings_cpu = extract_field(partition, 'cpu_time') - have_optimal_repetitions, cpu_pvalue, time_pvalue = calc_utest(timings_cpu, timings_time) - - # Check if we failed miserably with minimum required repetitions for utest - if not have_optimal_repetitions and cpu_pvalue is None and time_pvalue is None: - return [] - - dsc = "U Test, Repetitions: {} vs {}".format( - len(timings_cpu[0]), len(timings_cpu[1])) - dsc_color = BC_OKGREEN - - # We still got some results to show but issue a warning about it. - if not have_optimal_repetitions: - dsc_color = BC_WARNING - dsc += ". WARNING: Results unreliable! {}+ repetitions recommended.".format( - UTEST_OPTIMAL_REPETITIONS) - - special_str = "{}{:<{}s}{endc}{}{:16.4f}{endc}{}{:16.4f}{endc}{} {}" - - last_name = partition[0][0]['name'] - return [color_format(use_color, - special_str, - BC_HEADER, - "{}{}".format(last_name, UTEST_COL_NAME), - first_col_width, - get_utest_color(time_pvalue), time_pvalue, - get_utest_color(cpu_pvalue), cpu_pvalue, - dsc_color, dsc, - endc=BC_ENDC)] - - -def generate_difference_report( - json1, - json2, - display_aggregates_only=False, - utest=False, - utest_alpha=0.05, - use_color=True): - """ - Calculate and report the difference between each test of two benchmarks - runs specified as 'json1' and 'json2'. - """ - assert utest is True or utest is False - first_col_width = find_longest_name(json1['benchmarks']) - - def find_test(name): - for b in json2['benchmarks']: - if b['name'] == name: - return b - return None - - first_col_width = max( - first_col_width, - len('Benchmark')) - first_col_width += len(UTEST_COL_NAME) - first_line = "{:<{}s}Time CPU Time Old Time New CPU Old CPU New".format( - 'Benchmark', 12 + first_col_width) - output_strs = [first_line, '-' * len(first_line)] - - partitions = partition_benchmarks(json1, json2) - for partition in partitions: - # Careful, we may have different repetition count. - for i in range(min(len(partition[0]), len(partition[1]))): - bn = partition[0][i] - other_bench = partition[1][i] - - # *If* we were asked to only display aggregates, - # and if it is non-aggregate, then skip it. - if display_aggregates_only and 'run_type' in bn and 'run_type' in other_bench: - assert bn['run_type'] == other_bench['run_type'] - if bn['run_type'] != 'aggregate': - continue - - fmt_str = "{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}" - - def get_color(res): - if res > 0.05: - return BC_FAIL - elif res > -0.07: - return BC_WHITE - else: - return BC_CYAN - - tres = calculate_change(bn['real_time'], other_bench['real_time']) - cpures = calculate_change(bn['cpu_time'], other_bench['cpu_time']) - output_strs += [color_format(use_color, - fmt_str, - BC_HEADER, - bn['name'], - first_col_width, - get_color(tres), - tres, - get_color(cpures), - cpures, - bn['real_time'], - other_bench['real_time'], - bn['cpu_time'], - other_bench['cpu_time'], - endc=BC_ENDC)] - - # After processing the whole partition, if requested, do the U test. - if utest: - output_strs += print_utest(partition, - utest_alpha=utest_alpha, - first_col_width=first_col_width, - use_color=use_color) - - return output_strs - - -############################################################################### -# Unit tests - - -class TestGetUniqueBenchmarkNames(unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput = os.path.join(testInputs, 'test3_run0.json') - with open(testOutput, 'r') as f: - json = json.load(f) - return json - - def test_basic(self): - expect_lines = [ - 'BM_One', - 'BM_Two', - 'short', # These two are not sorted - 'medium', # These two are not sorted - ] - json = self.load_results() - output_lines = get_unique_benchmark_names(json) - print("\n") - print("\n".join(output_lines)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - self.assertEqual(expect_lines[i], output_lines[i]) - - -class TestReportDifference(unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput1 = os.path.join(testInputs, 'test1_run1.json') - testOutput2 = os.path.join(testInputs, 'test1_run2.json') - with open(testOutput1, 'r') as f: - json1 = json.load(f) - with open(testOutput2, 'r') as f: - json2 = json.load(f) - return json1, json2 - - def test_basic(self): - expect_lines = [ - ['BM_SameTimes', '+0.0000', '+0.0000', '10', '10', '10', '10'], - ['BM_2xFaster', '-0.5000', '-0.5000', '50', '25', '50', '25'], - ['BM_2xSlower', '+1.0000', '+1.0000', '50', '100', '50', '100'], - ['BM_1PercentFaster', '-0.0100', '-0.0100', '100', '99', '100', '99'], - ['BM_1PercentSlower', '+0.0100', '+0.0100', '100', '101', '100', '101'], - ['BM_10PercentFaster', '-0.1000', '-0.1000', '100', '90', '100', '90'], - ['BM_10PercentSlower', '+0.1000', '+0.1000', '100', '110', '100', '110'], - ['BM_100xSlower', '+99.0000', '+99.0000', - '100', '10000', '100', '10000'], - ['BM_100xFaster', '-0.9900', '-0.9900', - '10000', '100', '10000', '100'], - ['BM_10PercentCPUToTime', '+0.1000', - '-0.1000', '100', '110', '100', '90'], - ['BM_ThirdFaster', '-0.3333', '-0.3334', '100', '67', '100', '67'], - ['BM_NotBadTimeUnit', '-0.9000', '+0.2000', '0', '0', '0', '1'], - ] - json1, json2 = self.load_results() - output_lines_with_header = generate_difference_report( - json1, json2, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(len(parts), 7) - self.assertEqual(expect_lines[i], parts) - - -class TestReportDifferenceBetweenFamilies(unittest.TestCase): - def load_result(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput = os.path.join(testInputs, 'test2_run.json') - with open(testOutput, 'r') as f: - json = json.load(f) - return json - - def test_basic(self): - expect_lines = [ - ['.', '-0.5000', '-0.5000', '10', '5', '10', '5'], - ['./4', '-0.5000', '-0.5000', '40', '20', '40', '20'], - ['Prefix/.', '-0.5000', '-0.5000', '20', '10', '20', '10'], - ['Prefix/./3', '-0.5000', '-0.5000', '30', '15', '30', '15'], - ] - json = self.load_result() - json1 = filter_benchmark(json, "BM_Z.ro", ".") - json2 = filter_benchmark(json, "BM_O.e", ".") - output_lines_with_header = generate_difference_report( - json1, json2, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(len(parts), 7) - self.assertEqual(expect_lines[i], parts) - - -class TestReportDifferenceWithUTest(unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput1 = os.path.join(testInputs, 'test3_run0.json') - testOutput2 = os.path.join(testInputs, 'test3_run1.json') - with open(testOutput1, 'r') as f: - json1 = json.load(f) - with open(testOutput2, 'r') as f: - json2 = json.load(f) - return json1, json2 - - def test_utest(self): - expect_lines = [] - expect_lines = [ - ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'], - ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'], - ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'], - ['BM_Two_pvalue', - '0.6985', - '0.6985', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '2.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'], - ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'], - ['short_pvalue', - '0.7671', - '0.1489', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '3.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ['medium', '-0.3750', '-0.3375', '8', '5', '80', '53'], - ] - json1, json2 = self.load_results() - output_lines_with_header = generate_difference_report( - json1, json2, utest=True, utest_alpha=0.05, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(expect_lines[i], parts) - - -class TestReportDifferenceWithUTestWhileDisplayingAggregatesOnly( - unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput1 = os.path.join(testInputs, 'test3_run0.json') - testOutput2 = os.path.join(testInputs, 'test3_run1.json') - with open(testOutput1, 'r') as f: - json1 = json.load(f) - with open(testOutput2, 'r') as f: - json2 = json.load(f) - return json1, json2 - - def test_utest(self): - expect_lines = [] - expect_lines = [ - ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'], - ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'], - ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'], - ['BM_Two_pvalue', - '0.6985', - '0.6985', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '2.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'], - ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'], - ['short_pvalue', - '0.7671', - '0.1489', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '3.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ] - json1, json2 = self.load_results() - output_lines_with_header = generate_difference_report( - json1, json2, display_aggregates_only=True, - utest=True, utest_alpha=0.05, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(expect_lines[i], parts) - - -if __name__ == '__main__': - unittest.main() - -# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 -# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; -# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/thirdparty_builtin/benchmark-1.5.0/.clang-format b/thirdparty_builtin/benchmark-1.8.0/.clang-format similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/.clang-format rename to thirdparty_builtin/benchmark-1.8.0/.clang-format diff --git a/thirdparty_builtin/benchmark-1.8.0/.clang-tidy b/thirdparty_builtin/benchmark-1.8.0/.clang-tidy new file mode 100644 index 000000000..56938a598 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.clang-tidy @@ -0,0 +1,7 @@ +--- +Checks: 'clang-analyzer-*,readability-redundant-*,performance-*' +WarningsAsErrors: 'clang-analyzer-*,readability-redundant-*,performance-*' +HeaderFilterRegex: '.*' +AnalyzeTemporaryDtors: false +FormatStyle: none +User: user diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/ISSUE_TEMPLATE/bug_report.md b/thirdparty_builtin/benchmark-1.8.0/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..6c2ced9b2 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**System** +Which OS, compiler, and compiler version are you using: + - OS: + - Compiler and version: + +**To reproduce** +Steps to reproduce the behavior: +1. sync to commit ... +2. cmake/bazel... +3. make ... +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Additional context** +Add any other context about the problem here. diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/ISSUE_TEMPLATE/feature_request.md b/thirdparty_builtin/benchmark-1.8.0/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..9e8ab6a67 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FR]" +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/install_bazel.sh b/thirdparty_builtin/benchmark-1.8.0/.github/install_bazel.sh new file mode 100644 index 000000000..bb910d8b5 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/install_bazel.sh @@ -0,0 +1,13 @@ +if ! bazel version; then + arch=$(uname -m) + if [ "$arch" == "aarch64" ]; then + arch="arm64" + fi + echo "Installing wget and downloading $arch Bazel binary from GitHub releases." + yum install -y wget + wget "https://github.com/bazelbuild/bazel/releases/download/6.0.0/bazel-6.0.0-linux-$arch" -O /usr/local/bin/bazel + chmod +x /usr/local/bin/bazel +else + # bazel is installed for the correct architecture + exit 0 +fi diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/libcxx-setup.sh b/thirdparty_builtin/benchmark-1.8.0/.github/libcxx-setup.sh new file mode 100755 index 000000000..8773b9c40 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/libcxx-setup.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +set -e + +# Checkout LLVM sources +git clone --depth=1 https://github.com/llvm/llvm-project.git llvm-project + +## Setup libc++ options +if [ -z "$BUILD_32_BITS" ]; then + export BUILD_32_BITS=OFF && echo disabling 32 bit build +fi + +## Build and install libc++ (Use unstable ABI for better sanitizer coverage) +mkdir llvm-build && cd llvm-build +cmake -DCMAKE_C_COMPILER=${CC} \ + -DCMAKE_CXX_COMPILER=${CXX} \ + -DCMAKE_BUILD_TYPE=RelWithDebInfo \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DLIBCXX_ABI_UNSTABLE=OFF \ + -DLLVM_USE_SANITIZER=${LIBCXX_SANITIZER} \ + -DLLVM_BUILD_32_BITS=${BUILD_32_BITS} \ + -DLLVM_ENABLE_RUNTIMES='libcxx;libcxxabi;libunwind' \ + -G "Unix Makefiles" \ + ../llvm-project/runtimes/ +make -j cxx cxxabi unwind +cd .. diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/bazel.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/bazel.yml new file mode 100644 index 000000000..9e31c9012 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/bazel.yml @@ -0,0 +1,35 @@ +name: bazel + +on: + push: {} + pull_request: {} + +jobs: + job: + name: bazel.${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-2022] + + steps: + - uses: actions/checkout@v3 + + - name: mount bazel cache + uses: actions/cache@v3 + env: + cache-name: bazel-cache + with: + path: "~/.cache/bazel" + key: ${{ env.cache-name }}-${{ matrix.os }}-${{ github.ref }} + restore-keys: | + ${{ env.cache-name }}-${{ matrix.os }}-main + + - name: build + run: | + bazel build //:benchmark //:benchmark_main //test/... + + - name: test + run: | + bazel test --test_output=all //test/... diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test-min-cmake.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test-min-cmake.yml new file mode 100644 index 000000000..e3e321752 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test-min-cmake.yml @@ -0,0 +1,46 @@ +name: build-and-test-min-cmake + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + job: + name: ${{ matrix.os }}.min-cmake + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + + steps: + - uses: actions/checkout@v3 + + - uses: lukka/get-cmake@latest + with: + cmakeVersion: 3.10.0 + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: setup cmake initial cache + run: touch compiler-cache.cmake + + - name: configure cmake + env: + CXX: ${{ matrix.compiler }} + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake -C ${{ github.workspace }}/compiler-cache.cmake + $GITHUB_WORKSPACE + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_CXX_VISIBILITY_PRESET=hidden + -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test-perfcounters.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test-perfcounters.yml new file mode 100644 index 000000000..97e4d8ea6 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test-perfcounters.yml @@ -0,0 +1,51 @@ +name: build-and-test-perfcounters + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + job: + # TODO(dominic): Extend this to include compiler and set through env: CC/CXX. + name: ${{ matrix.os }}.${{ matrix.build_type }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, ubuntu-20.04] + build_type: ['Release', 'Debug'] + steps: + - uses: actions/checkout@v3 + + - name: install libpfm + run: | + sudo apt update + sudo apt -y install libpfm4-dev + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: configure cmake + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake $GITHUB_WORKSPACE + -DBENCHMARK_ENABLE_LIBPFM=1 + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . --config ${{ matrix.build_type }} + + # Skip testing, for now. It seems perf_event_open does not succeed on the + # hosting machine, very likely a permissions issue. + # TODO(mtrofin): Enable test. + # - name: test + # shell: bash + # working-directory: ${{ runner.workspace }}/_build + # run: ctest -C ${{ matrix.build_type }} --rerun-failed --output-on-failure + diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test.yml new file mode 100644 index 000000000..b35200a00 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/build-and-test.yml @@ -0,0 +1,114 @@ +name: build-and-test + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + # TODO: add 32-bit builds (g++ and clang++) for ubuntu + # (requires g++-multilib and libc6:i386) + # TODO: add coverage build (requires lcov) + # TODO: add clang + libc++ builds for ubuntu + job: + name: ${{ matrix.os }}.${{ matrix.build_type }}.${{ matrix.lib }}.${{ matrix.compiler }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, ubuntu-20.04, macos-latest] + build_type: ['Release', 'Debug'] + compiler: ['g++', 'clang++'] + lib: ['shared', 'static'] + + steps: + - uses: actions/checkout@v3 + + - uses: lukka/get-cmake@latest + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: setup cmake initial cache + run: touch compiler-cache.cmake + + - name: configure cmake + env: + CXX: ${{ matrix.compiler }} + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake -C ${{ github.workspace }}/compiler-cache.cmake + $GITHUB_WORKSPACE + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DBUILD_SHARED_LIBS=${{ matrix.lib == 'shared' }} + -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} + -DCMAKE_CXX_COMPILER=${{ env.CXX }} + -DCMAKE_CXX_VISIBILITY_PRESET=hidden + -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . --config ${{ matrix.build_type }} + + - name: test + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: ctest -C ${{ matrix.build_type }} -VV + + msvc: + name: ${{ matrix.os }}.${{ matrix.build_type }}.${{ matrix.lib }}.${{ matrix.msvc }} + runs-on: ${{ matrix.os }} + defaults: + run: + shell: powershell + strategy: + fail-fast: false + matrix: + msvc: + - VS-16-2019 + - VS-17-2022 + arch: + - x64 + build_type: + - Debug + - Release + lib: + - shared + - static + include: + - msvc: VS-16-2019 + os: windows-2019 + generator: 'Visual Studio 16 2019' + - msvc: VS-17-2022 + os: windows-2022 + generator: 'Visual Studio 17 2022' + + steps: + - uses: actions/checkout@v2 + + - uses: lukka/get-cmake@latest + + - name: configure cmake + run: > + cmake -S . -B _build/ + -A ${{ matrix.arch }} + -G "${{ matrix.generator }}" + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DBUILD_SHARED_LIBS=${{ matrix.lib == 'shared' }} + + - name: build + run: cmake --build _build/ --config ${{ matrix.build_type }} + + - name: setup test environment + # Make sure gmock and benchmark DLLs can be found + run: > + echo "$((Get-Item .).FullName)/_build/bin/${{ matrix.build_type }}" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append; + echo "$((Get-Item .).FullName)/_build/src/${{ matrix.build_type }}" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append; + + - name: test + run: ctest --test-dir _build/ -C ${{ matrix.build_type }} -VV + + diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/clang-format-lint.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/clang-format-lint.yml new file mode 100644 index 000000000..77ce1f8cd --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/clang-format-lint.yml @@ -0,0 +1,17 @@ +name: clang-format-lint +on: + push: {} + pull_request: {} + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: DoozyX/clang-format-lint-action@v0.13 + with: + source: './include/benchmark ./src ./test' + extensions: 'h,cc' + clangFormatVersion: 12 + style: Google diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/clang-tidy.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/clang-tidy.yml new file mode 100644 index 000000000..2eaab9c1e --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/clang-tidy.yml @@ -0,0 +1,38 @@ +name: clang-tidy + +on: + push: {} + pull_request: {} + +jobs: + job: + name: run-clang-tidy + runs-on: ubuntu-latest + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v3 + + - name: install clang-tidy + run: sudo apt update && sudo apt -y install clang-tidy + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: configure cmake + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + cmake $GITHUB_WORKSPACE + -DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF + -DBENCHMARK_ENABLE_LIBPFM=OFF + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_C_COMPILER=clang + -DCMAKE_CXX_COMPILER=clang++ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + -DGTEST_COMPILE_COMMANDS=OFF + + - name: run + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: run-clang-tidy diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/doxygen.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/doxygen.yml new file mode 100644 index 000000000..da92c46a2 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/doxygen.yml @@ -0,0 +1,28 @@ +name: doxygen + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + build-and-deploy: + name: Build HTML documentation + runs-on: ubuntu-latest + steps: + - name: Fetching sources + uses: actions/checkout@v3 + + - name: Installing build dependencies + run: | + sudo apt update + sudo apt install doxygen gcc git + + - name: Creating build directory + run: mkdir build + + - name: Building HTML documentation with Doxygen + run: | + cmake -S . -B build -DBENCHMARK_ENABLE_TESTING:BOOL=OFF -DBENCHMARK_ENABLE_DOXYGEN:BOOL=ON -DBENCHMARK_INSTALL_DOCS:BOOL=ON + cmake --build build --target benchmark_doxygen diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/pylint.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/pylint.yml new file mode 100644 index 000000000..c6939b50f --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/pylint.yml @@ -0,0 +1,28 @@ +name: pylint + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + pylint: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python 3.8 + uses: actions/setup-python@v1 + with: + python-version: 3.8 + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install pylint pylint-exit conan + + - name: Run pylint + run: | + pylint `find . -name '*.py'|xargs` || pylint-exit $? diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/sanitizer.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/sanitizer.yml new file mode 100644 index 000000000..86cccf410 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/sanitizer.yml @@ -0,0 +1,96 @@ +name: sanitizer + +on: + push: {} + pull_request: {} + +env: + UBSAN_OPTIONS: "print_stacktrace=1" + +jobs: + job: + name: ${{ matrix.sanitizer }}.${{ matrix.build_type }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + build_type: ['Debug', 'RelWithDebInfo'] + sanitizer: ['asan', 'ubsan', 'tsan', 'msan'] + + steps: + - uses: actions/checkout@v3 + + - name: configure msan env + if: matrix.sanitizer == 'msan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=memory -fsanitize-memory-track-origins" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=MemoryWithOrigins" >> $GITHUB_ENV + + - name: configure ubsan env + if: matrix.sanitizer == 'ubsan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=undefined -fno-sanitize-recover=all" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=Undefined" >> $GITHUB_ENV + + - name: configure asan env + if: matrix.sanitizer == 'asan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=address -fno-sanitize-recover=all" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=Address" >> $GITHUB_ENV + + - name: configure tsan env + if: matrix.sanitizer == 'tsan' + run: | + echo "EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=thread -fno-sanitize-recover=all" >> $GITHUB_ENV + echo "LIBCXX_SANITIZER=Thread" >> $GITHUB_ENV + + - name: fine-tune asan options + # in asan we get an error from std::regex. ignore it. + if: matrix.sanitizer == 'asan' + run: | + echo "ASAN_OPTIONS=alloc_dealloc_mismatch=0" >> $GITHUB_ENV + + - name: setup clang + uses: egor-tensin/setup-clang@v1 + with: + version: latest + platform: x64 + + - name: configure clang + run: | + echo "CC=cc" >> $GITHUB_ENV + echo "CXX=c++" >> $GITHUB_ENV + + - name: build libc++ (non-asan) + if: matrix.sanitizer != 'asan' + run: | + "${GITHUB_WORKSPACE}/.github/libcxx-setup.sh" + echo "EXTRA_CXX_FLAGS=-stdlib=libc++ -L ${GITHUB_WORKSPACE}/llvm-build/lib -lc++abi -Isystem${GITHUB_WORKSPACE}/llvm-build/include -Isystem${GITHUB_WORKSPACE}/llvm-build/include/c++/v1 -Wl,-rpath,${GITHUB_WORKSPACE}/llvm-build/lib" >> $GITHUB_ENV + + - name: create build environment + run: cmake -E make_directory ${{ runner.workspace }}/_build + + - name: configure cmake + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: > + VERBOSE=1 + cmake $GITHUB_WORKSPACE + -DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF + -DBENCHMARK_ENABLE_LIBPFM=OFF + -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON + -DCMAKE_C_COMPILER=${{ env.CC }} + -DCMAKE_CXX_COMPILER=${{ env.CXX }} + -DCMAKE_C_FLAGS="${{ env.EXTRA_FLAGS }}" + -DCMAKE_CXX_FLAGS="${{ env.EXTRA_FLAGS }} ${{ env.EXTRA_CXX_FLAGS }}" + -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} + + - name: build + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: cmake --build . --config ${{ matrix.build_type }} + + - name: test + shell: bash + working-directory: ${{ runner.workspace }}/_build + run: ctest -C ${{ matrix.build_type }} -VV diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/test_bindings.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/test_bindings.yml new file mode 100644 index 000000000..98fa7e1ca --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/test_bindings.yml @@ -0,0 +1,29 @@ +name: test-bindings + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + python_bindings: + name: Test GBM Python bindings on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest, macos-latest, windows-latest ] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.11 + - name: Install GBM Python bindings on ${{ matrix.os}} + run: + python -m pip install wheel . + - name: Run bindings example on ${{ matrix.os }} + run: + python bindings/python/google_benchmark/example.py diff --git a/thirdparty_builtin/benchmark-1.8.0/.github/workflows/wheels.yml b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/wheels.yml new file mode 100644 index 000000000..d3c4630e1 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/.github/workflows/wheels.yml @@ -0,0 +1,79 @@ +name: Build and upload Python wheels + +on: + workflow_dispatch: + release: + types: + - published + +jobs: + build_sdist: + name: Build source distribution + runs-on: ubuntu-latest + steps: + - name: Check out repo + uses: actions/checkout@v3 + + - name: Install Python 3.11 + uses: actions/setup-python@v4 + with: + python-version: 3.11 + + - name: Build and check sdist + run: | + python setup.py sdist + - name: Upload sdist + uses: actions/upload-artifact@v3 + with: + name: dist + path: dist/*.tar.gz + + build_wheels: + name: Build Google Benchmark wheels on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + + steps: + - name: Check out Google Benchmark + uses: actions/checkout@v3 + + - name: Set up QEMU + if: runner.os == 'Linux' + uses: docker/setup-qemu-action@v2 + with: + platforms: all + + - name: Build wheels on ${{ matrix.os }} using cibuildwheel + uses: pypa/cibuildwheel@v2.12.0 + env: + CIBW_BUILD: 'cp38-* cp39-* cp310-* cp311-*' + CIBW_SKIP: "*-musllinux_*" + CIBW_TEST_SKIP: "*-macosx_arm64" + CIBW_ARCHS_LINUX: x86_64 aarch64 + CIBW_ARCHS_MACOS: x86_64 arm64 + CIBW_ARCHS_WINDOWS: AMD64 + CIBW_BEFORE_ALL_LINUX: bash .github/install_bazel.sh + CIBW_TEST_COMMAND: python {project}/bindings/python/google_benchmark/example.py + + - name: Upload Google Benchmark ${{ matrix.os }} wheels + uses: actions/upload-artifact@v3 + with: + name: dist + path: ./wheelhouse/*.whl + + pypi_upload: + name: Publish google-benchmark wheels to PyPI + needs: [build_sdist, build_wheels] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v3 + with: + name: dist + path: dist + + - uses: pypa/gh-action-pypi-publish@v1.6.4 + with: + user: __token__ + password: ${{ secrets.PYPI_PASSWORD }} diff --git a/thirdparty_builtin/benchmark-1.5.0/.travis.yml b/thirdparty_builtin/benchmark-1.8.0/.travis.yml similarity index 87% rename from thirdparty_builtin/benchmark-1.5.0/.travis.yml rename to thirdparty_builtin/benchmark-1.8.0/.travis.yml index 6b6cfc704..8cfed3d10 100644 --- a/thirdparty_builtin/benchmark-1.5.0/.travis.yml +++ b/thirdparty_builtin/benchmark-1.8.0/.travis.yml @@ -2,10 +2,6 @@ sudo: required dist: trusty language: cpp -env: - global: - - /usr/local/bin:$PATH - matrix: include: - compiler: gcc @@ -14,10 +10,6 @@ matrix: packages: - lcov env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Coverage - - compiler: gcc - env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Debug - - compiler: gcc - env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Release - compiler: gcc addons: apt: @@ -48,10 +40,6 @@ matrix: - COMPILER=g++-6 C_COMPILER=gcc-6 BUILD_TYPE=Debug - ENABLE_SANITIZER=1 - EXTRA_FLAGS="-fno-omit-frame-pointer -g -O2 -fsanitize=undefined,address -fuse-ld=gold" - - compiler: clang - env: COMPILER=clang++ C_COMPILER=clang BUILD_TYPE=Debug - - compiler: clang - env: COMPILER=clang++ C_COMPILER=clang BUILD_TYPE=Release # Clang w/ libc++ - compiler: clang dist: xenial @@ -150,16 +138,6 @@ matrix: - ENABLE_SANITIZER=1 - EXTRA_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=thread -fno-sanitize-recover=all" - EXTRA_CXX_FLAGS="-stdlib=libc++" - - os: osx - osx_image: xcode8.3 - compiler: clang - env: - - COMPILER=clang++ BUILD_TYPE=Debug - - os: osx - osx_image: xcode8.3 - compiler: clang - env: - - COMPILER=clang++ BUILD_TYPE=Release - os: osx osx_image: xcode8.3 compiler: clang @@ -168,15 +146,10 @@ matrix: - BUILD_TYPE=Release - BUILD_32_BITS=ON - EXTRA_FLAGS="-m32" - - os: osx - osx_image: xcode8.3 - compiler: gcc - env: - - COMPILER=g++-7 C_COMPILER=gcc-7 BUILD_TYPE=Debug before_script: - if [ -n "${LIBCXX_BUILD}" ]; then - source .travis-libcxx-setup.sh; + source .libcxx-setup.sh; fi - if [ -n "${ENABLE_SANITIZER}" ]; then export EXTRA_OPTIONS="-DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF"; @@ -215,11 +188,11 @@ install: - if [ "${TRAVIS_OS_NAME}" == "linux" ]; then sudo apt-get update -qq; sudo apt-get install -qq unzip cmake3; - wget https://github.com/bazelbuild/bazel/releases/download/0.10.1/bazel-0.10.1-installer-linux-x86_64.sh --output-document bazel-installer.sh; + wget https://github.com/bazelbuild/bazel/releases/download/3.2.0/bazel-3.2.0-installer-linux-x86_64.sh --output-document bazel-installer.sh; travis_wait sudo bash bazel-installer.sh; fi - if [ "${TRAVIS_OS_NAME}" == "osx" ]; then - curl -L -o bazel-installer.sh https://github.com/bazelbuild/bazel/releases/download/0.10.1/bazel-0.10.1-installer-darwin-x86_64.sh; + curl -L -o bazel-installer.sh https://github.com/bazelbuild/bazel/releases/download/3.2.0/bazel-3.2.0-installer-darwin-x86_64.sh; travis_wait sudo bash bazel-installer.sh; fi diff --git a/thirdparty_builtin/benchmark-1.5.0/.ycm_extra_conf.py b/thirdparty_builtin/benchmark-1.8.0/.ycm_extra_conf.py similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/.ycm_extra_conf.py rename to thirdparty_builtin/benchmark-1.8.0/.ycm_extra_conf.py diff --git a/thirdparty_builtin/benchmark-1.5.0/AUTHORS b/thirdparty_builtin/benchmark-1.8.0/AUTHORS similarity index 70% rename from thirdparty_builtin/benchmark-1.5.0/AUTHORS rename to thirdparty_builtin/benchmark-1.8.0/AUTHORS index 912cbbc13..bafecaddb 100644 --- a/thirdparty_builtin/benchmark-1.5.0/AUTHORS +++ b/thirdparty_builtin/benchmark-1.8.0/AUTHORS @@ -13,39 +13,58 @@ Alex Steele Andriy Berestovskyy Arne Beer Carto +Cezary Skrzyński +Christian Wassermann Christopher Seymour +Colin Braley Daniel Harvey David Coeurjolly Deniz Evrenci Dirac Research Dominik Czarnota +Dominik Korman +Donald Aingworth +Eric Backus Eric Fiselier Eugene Zhuk Evgeny Safronov Federico Ficarelli Felix Homann +Gergő Szitár Google Inc. +Henrique Bucher International Business Machines Corporation Ismael Jimenez Martinez Jern-Kuan Leong JianXiong Zhou Joao Paulo Magalhaes +Jordan Williams Jussi Knuuttila Kaito Udagawa Kishan Kumar Lei Xu +Marcel Jacobse Matt Clarkson Maxim Vafin +Mike Apodaca MongoDB Inc. Nick Hutchinson +Norman Heino Oleksandr Sochka Ori Livneh Paul Redmond +Raghu Raja Radoslav Yovchev +Rainer Orth Roman Lebedev +Sayan Bhattacharjee +Shapr3D Shuo Chen +Staffan Tjernstrom Steinar H. Gunderson Stripe, Inc. +Tobias Schmidt Yixuan Qiu Yusuke Suzuki Zbigniew Skowron +Min-Yih Hsu diff --git a/thirdparty_builtin/benchmark-1.8.0/BUILD.bazel b/thirdparty_builtin/benchmark-1.8.0/BUILD.bazel new file mode 100644 index 000000000..99616163e --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/BUILD.bazel @@ -0,0 +1,83 @@ +licenses(["notice"]) + +config_setting( + name = "qnx", + constraint_values = ["@platforms//os:qnx"], + values = { + "cpu": "x64_qnx", + }, + visibility = [":__subpackages__"], +) + +config_setting( + name = "windows", + constraint_values = ["@platforms//os:windows"], + values = { + "cpu": "x64_windows", + }, + visibility = [":__subpackages__"], +) + +config_setting( + name = "macos", + constraint_values = ["@platforms//os:macos"], + visibility = ["//visibility:public"], +) + +config_setting( + name = "perfcounters", + define_values = { + "pfm": "1", + }, + visibility = [":__subpackages__"], +) + +cc_library( + name = "benchmark", + srcs = glob( + [ + "src/*.cc", + "src/*.h", + ], + exclude = ["src/benchmark_main.cc"], + ), + hdrs = [ + "include/benchmark/benchmark.h", + "include/benchmark/export.h", + ], + linkopts = select({ + ":windows": ["-DEFAULTLIB:shlwapi.lib"], + "//conditions:default": ["-pthread"], + }), + strip_include_prefix = "include", + visibility = ["//visibility:public"], + # Only static linking is allowed; no .so will be produced. + # Using `defines` (i.e. not `local_defines`) means that no + # dependent rules need to bother about defining the macro. + linkstatic = True, + defines = [ + "BENCHMARK_STATIC_DEFINE", + ] + select({ + ":perfcounters": ["HAVE_LIBPFM"], + "//conditions:default": [], + }), + deps = select({ + ":perfcounters": ["@libpfm//:libpfm"], + "//conditions:default": [], + }), +) + +cc_library( + name = "benchmark_main", + srcs = ["src/benchmark_main.cc"], + hdrs = ["include/benchmark/benchmark.h", "include/benchmark/export.h"], + strip_include_prefix = "include", + visibility = ["//visibility:public"], + deps = [":benchmark"], +) + +cc_library( + name = "benchmark_internal_headers", + hdrs = glob(["src/*.h"]), + visibility = ["//test:__pkg__"], +) diff --git a/thirdparty_builtin/benchmark-1.5.0/CMakeLists.txt b/thirdparty_builtin/benchmark-1.8.0/CMakeLists.txt similarity index 75% rename from thirdparty_builtin/benchmark-1.5.0/CMakeLists.txt rename to thirdparty_builtin/benchmark-1.8.0/CMakeLists.txt index c24d29fef..0dbf393d8 100644 --- a/thirdparty_builtin/benchmark-1.5.0/CMakeLists.txt +++ b/thirdparty_builtin/benchmark-1.8.0/CMakeLists.txt @@ -1,27 +1,31 @@ -foreach(p - CMP0048 # OK to clear PROJECT_VERSION on project() - CMP0054 # CMake 3.1 - CMP0056 # export EXE_LINKER_FLAGS to try_run - CMP0057 # Support no if() IN_LIST operator - CMP0063 # Honor visibility properties for all targets - ) - if(POLICY ${p}) - cmake_policy(SET ${p} NEW) - endif() -endforeach() - -project (benchmark CXX) +project (benchmark VERSION 1.8.0 LANGUAGES CXX) option(BENCHMARK_ENABLE_TESTING "Enable testing of the benchmark library." ON) option(BENCHMARK_ENABLE_EXCEPTIONS "Enable the use of exceptions in the benchmark library." ON) option(BENCHMARK_ENABLE_LTO "Enable link time optimisation of the benchmark library." OFF) option(BENCHMARK_USE_LIBCXX "Build and test using libc++ as the standard library." OFF) +option(BENCHMARK_ENABLE_WERROR "Build Release candidates with -Werror." ON) +option(BENCHMARK_FORCE_WERROR "Build Release candidates with -Werror regardless of compiler issues." OFF) + +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "PGI") + # PGC++ maybe reporting false positives. + set(BENCHMARK_ENABLE_WERROR OFF) +endif() +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "NVHPC") + set(BENCHMARK_ENABLE_WERROR OFF) +endif() +if(BENCHMARK_FORCE_WERROR) + set(BENCHMARK_ENABLE_WERROR ON) +endif(BENCHMARK_FORCE_WERROR) + if(NOT MSVC) option(BENCHMARK_BUILD_32_BITS "Build a 32 bit version of the library." OFF) else() set(BENCHMARK_BUILD_32_BITS OFF CACHE BOOL "Build a 32 bit version of the library - unsupported when using MSVC)" FORCE) endif() option(BENCHMARK_ENABLE_INSTALL "Enable installation of benchmark. (Projects embedding benchmark may want to turn this OFF.)" ON) +option(BENCHMARK_ENABLE_DOXYGEN "Build documentation with Doxygen." OFF) +option(BENCHMARK_INSTALL_DOCS "Enable installation of documentation." ON) # Allow unmet dependencies to be met using CMake's ExternalProject mechanics, which # may require downloading the source code. @@ -30,6 +34,24 @@ option(BENCHMARK_DOWNLOAD_DEPENDENCIES "Allow the downloading and in-tree buildi # This option can be used to disable building and running unit tests which depend on gtest # in cases where it is not possible to build or find a valid version of gtest. option(BENCHMARK_ENABLE_GTEST_TESTS "Enable building the unit tests which depend on gtest" ON) +option(BENCHMARK_USE_BUNDLED_GTEST "Use bundled GoogleTest. If disabled, the find_package(GTest) will be used." ON) + +option(BENCHMARK_ENABLE_LIBPFM "Enable performance counters provided by libpfm" OFF) + +# Export only public symbols +set(CMAKE_CXX_VISIBILITY_PRESET hidden) +set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) + +if(MSVC) + # As of CMake 3.18, CMAKE_SYSTEM_PROCESSOR is not set properly for MSVC and + # cross-compilation (e.g. Host=x86_64, target=aarch64) requires using the + # undocumented, but working variable. + # See https://gitlab.kitware.com/cmake/cmake/-/issues/15170 + set(CMAKE_SYSTEM_PROCESSOR ${MSVC_CXX_ARCHITECTURE_ID}) + if(${CMAKE_SYSTEM_PROCESSOR} MATCHES "ARM") + set(CMAKE_CROSSCOMPILING TRUE) + endif() +endif() set(ENABLE_ASSEMBLY_TESTS_DEFAULT OFF) function(should_enable_assembly_tests) @@ -77,8 +99,14 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") include(GetGitVersion) get_git_version(GIT_VERSION) +# If no git version can be determined, use the version +# from the project() command +if ("${GIT_VERSION}" STREQUAL "0.0.0") + set(VERSION "${benchmark_VERSION}") +else() + set(VERSION "${GIT_VERSION}") +endif() # Tell the user what versions we are using -string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" VERSION ${GIT_VERSION}) message(STATUS "Version: ${VERSION}") # The version of the libraries @@ -86,14 +114,27 @@ set(GENERIC_LIB_VERSION ${VERSION}) string(SUBSTRING ${VERSION} 0 1 GENERIC_LIB_SOVERSION) # Import our CMake modules -include(CheckCXXCompilerFlag) include(AddCXXCompilerFlag) +include(CheckCXXCompilerFlag) +include(CheckLibraryExists) include(CXXFeatureCheck) +check_library_exists(rt shm_open "" HAVE_LIB_RT) + if (BENCHMARK_BUILD_32_BITS) add_required_cxx_compiler_flag(-m32) endif() +if (MSVC) + set(BENCHMARK_CXX_STANDARD 14) +else() + set(BENCHMARK_CXX_STANDARD 11) +endif() + +set(CMAKE_CXX_STANDARD ${BENCHMARK_CXX_STANDARD}) +set(CMAKE_CXX_STANDARD_REQUIRED YES) +set(CMAKE_CXX_EXTENSIONS OFF) + if (MSVC) # Turn compiler warnings up to 11 string(REGEX REPLACE "[-/]W[1-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") @@ -126,17 +167,18 @@ if (MSVC) set(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} /LTCG") endif() else() - # Try and enable C++11. Don't use C++14 because it doesn't work in some - # configurations. - add_cxx_compiler_flag(-std=c++11) - if (NOT HAVE_CXX_FLAG_STD_CXX11) - add_cxx_compiler_flag(-std=c++0x) - endif() - # Turn compiler warnings up to 11 add_cxx_compiler_flag(-Wall) add_cxx_compiler_flag(-Wextra) add_cxx_compiler_flag(-Wshadow) + add_cxx_compiler_flag(-Wfloat-equal) + if(BENCHMARK_ENABLE_WERROR) + add_cxx_compiler_flag(-Werror) + endif() + if (NOT BENCHMARK_ENABLE_TESTING) + # Disable warning when compiling tests as gtest does not use 'override'. + add_cxx_compiler_flag(-Wsuggest-override) + endif() add_cxx_compiler_flag(-pedantic) add_cxx_compiler_flag(-pedantic-errors) add_cxx_compiler_flag(-Wshorten-64-to-32) @@ -151,9 +193,9 @@ else() add_cxx_compiler_flag(-wd1786) endif() # Disable deprecation warnings for release builds (when -Werror is enabled). - add_cxx_compiler_flag(-Wno-deprecated RELEASE) - add_cxx_compiler_flag(-Wno-deprecated RELWITHDEBINFO) - add_cxx_compiler_flag(-Wno-deprecated MINSIZEREL) + if(BENCHMARK_ENABLE_WERROR) + add_cxx_compiler_flag(-Wno-deprecated) + endif() if (NOT BENCHMARK_ENABLE_EXCEPTIONS) add_cxx_compiler_flag(-fno-exceptions) endif() @@ -168,12 +210,12 @@ else() add_cxx_compiler_flag(-wd654) add_cxx_compiler_flag(-Wthread-safety) if (HAVE_CXX_FLAG_WTHREAD_SAFETY) - cxx_feature_check(THREAD_SAFETY_ATTRIBUTES) + cxx_feature_check(THREAD_SAFETY_ATTRIBUTES "-DINCLUDE_DIRECTORIES=${PROJECT_SOURCE_DIR}/include") endif() # On most UNIX like platforms g++ and clang++ define _GNU_SOURCE as a # predefined macro, which turns on all of the wonderful libc extensions. - # However g++ doesn't do this in Cygwin so we have to define it ourselfs + # However g++ doesn't do this in Cygwin so we have to define it ourselves # since we depend on GNU/POSIX/BSD extensions. if (CYGWIN) add_definitions(-D_GNU_SOURCE=1) @@ -186,6 +228,7 @@ else() # Link time optimisation if (BENCHMARK_ENABLE_LTO) add_cxx_compiler_flag(-flto) + add_cxx_compiler_flag(-Wno-lto-type-mismatch) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") find_program(GCC_AR gcc-ar) if (GCC_AR) @@ -237,11 +280,17 @@ if (BENCHMARK_USE_LIBCXX) endif() endif(BENCHMARK_USE_LIBCXX) +set(EXTRA_CXX_FLAGS "") +if (WIN32 AND "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") + # Clang on Windows fails to compile the regex feature check under C++11 + set(EXTRA_CXX_FLAGS "-DCMAKE_CXX_STANDARD=14") +endif() + # C++ feature checks # Determine the correct regular expression engine to use -cxx_feature_check(STD_REGEX) -cxx_feature_check(GNU_POSIX_REGEX) -cxx_feature_check(POSIX_REGEX) +cxx_feature_check(STD_REGEX ${EXTRA_CXX_FLAGS}) +cxx_feature_check(GNU_POSIX_REGEX ${EXTRA_CXX_FLAGS}) +cxx_feature_check(POSIX_REGEX ${EXTRA_CXX_FLAGS}) if(NOT HAVE_STD_REGEX AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) message(FATAL_ERROR "Failed to determine the source files for the regular expression backend") endif() @@ -249,10 +298,16 @@ if (NOT BENCHMARK_ENABLE_EXCEPTIONS AND HAVE_STD_REGEX AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) message(WARNING "Using std::regex with exceptions disabled is not fully supported") endif() + cxx_feature_check(STEADY_CLOCK) # Ensure we have pthreads set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) +cxx_feature_check(PTHREAD_AFFINITY) + +if (BENCHMARK_ENABLE_LIBPFM) + find_package(PFM) +endif() # Set up directories include_directories(${PROJECT_SOURCE_DIR}/include) @@ -265,7 +320,15 @@ if (BENCHMARK_ENABLE_TESTING) if (BENCHMARK_ENABLE_GTEST_TESTS AND NOT (TARGET gtest AND TARGET gtest_main AND TARGET gmock AND TARGET gmock_main)) - include(GoogleTest) + if (BENCHMARK_USE_BUNDLED_GTEST) + include(GoogleTest) + else() + find_package(GTest CONFIG REQUIRED) + add_library(gtest ALIAS GTest::gtest) + add_library(gtest_main ALIAS GTest::gtest_main) + add_library(gmock ALIAS GTest::gmock) + add_library(gmock_main ALIAS GTest::gmock_main) + endif() endif() add_subdirectory(test) endif() diff --git a/thirdparty_builtin/benchmark-1.5.0/CONTRIBUTING.md b/thirdparty_builtin/benchmark-1.8.0/CONTRIBUTING.md similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/CONTRIBUTING.md rename to thirdparty_builtin/benchmark-1.8.0/CONTRIBUTING.md diff --git a/thirdparty_builtin/benchmark-1.5.0/CONTRIBUTORS b/thirdparty_builtin/benchmark-1.8.0/CONTRIBUTORS similarity index 76% rename from thirdparty_builtin/benchmark-1.5.0/CONTRIBUTORS rename to thirdparty_builtin/benchmark-1.8.0/CONTRIBUTORS index b680efc8c..56f03e2d6 100644 --- a/thirdparty_builtin/benchmark-1.5.0/CONTRIBUTORS +++ b/thirdparty_builtin/benchmark-1.8.0/CONTRIBUTORS @@ -22,51 +22,73 @@ # # Please keep the list sorted. +Abhina Sreeskantharajan Albert Pretorius Alex Steele Andriy Berestovskyy Arne Beer +Bátor Tallér Billy Robert O'Neal III +Cezary Skrzyński Chris Kennelly +Christian Wassermann Christopher Seymour +Colin Braley Cyrille Faucheux Daniel Harvey David Coeurjolly Deniz Evrenci Dominic Hamon Dominik Czarnota +Dominik Korman +Donald Aingworth +Eric Backus Eric Fiselier Eugene Zhuk Evgeny Safronov +Fanbo Meng Federico Ficarelli Felix Homann +Geoffrey Martin-Noble +Gergő Szitár Hannes Hauswedell +Henrique Bucher Ismael Jimenez Martinez Jern-Kuan Leong JianXiong Zhou Joao Paulo Magalhaes John Millikin +Jordan Williams Jussi Knuuttila Kai Wolf -Kishan Kumar Kaito Udagawa +Kishan Kumar Lei Xu +Marcel Jacobse Matt Clarkson Maxim Vafin +Mike Apodaca Nick Hutchinson +Norman Heino Oleksandr Sochka Ori Livneh Pascal Leroy Paul Redmond Pierre Phaneuf Radoslav Yovchev +Rainer Orth +Raghu Raja Raul Marin Ray Glover Robert Guo Roman Lebedev +Sayan Bhattacharjee Shuo Chen +Steven Wan +Tobias Schmidt Tobias Ulvgård Tom Madams Yixuan Qiu Yusuke Suzuki Zbigniew Skowron +Min-Yih Hsu diff --git a/thirdparty_builtin/benchmark-1.5.0/LICENSE b/thirdparty_builtin/benchmark-1.8.0/LICENSE similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/LICENSE rename to thirdparty_builtin/benchmark-1.8.0/LICENSE diff --git a/thirdparty_builtin/benchmark-1.8.0/README.md b/thirdparty_builtin/benchmark-1.8.0/README.md new file mode 100644 index 000000000..b64048b7d --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/README.md @@ -0,0 +1,224 @@ +# Benchmark + +[![build-and-test](https://github.com/google/benchmark/workflows/build-and-test/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Abuild-and-test) +[![bazel](https://github.com/google/benchmark/actions/workflows/bazel.yml/badge.svg)](https://github.com/google/benchmark/actions/workflows/bazel.yml) +[![pylint](https://github.com/google/benchmark/workflows/pylint/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Apylint) +[![test-bindings](https://github.com/google/benchmark/workflows/test-bindings/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Atest-bindings) + +[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=main)](https://travis-ci.org/google/benchmark) +[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark) + + +A library to benchmark code snippets, similar to unit tests. Example: + +```c++ +#include + +static void BM_SomeFunction(benchmark::State& state) { + // Perform setup here + for (auto _ : state) { + // This code gets timed + SomeFunction(); + } +} +// Register the function as a benchmark +BENCHMARK(BM_SomeFunction); +// Run the benchmark +BENCHMARK_MAIN(); +``` + +## Getting Started + +To get started, see [Requirements](#requirements) and +[Installation](#installation). See [Usage](#usage) for a full example and the +[User Guide](docs/user_guide.md) for a more comprehensive feature overview. + +It may also help to read the [Google Test documentation](https://github.com/google/googletest/blob/main/docs/primer.md) +as some of the structural aspects of the APIs are similar. + +## Resources + +[Discussion group](https://groups.google.com/d/forum/benchmark-discuss) + +IRC channels: +* [libera](https://libera.chat) #benchmark + +[Additional Tooling Documentation](docs/tools.md) + +[Assembly Testing Documentation](docs/AssemblyTests.md) + +[Building and installing Python bindings](docs/python_bindings.md) + +## Requirements + +The library can be used with C++03. However, it requires C++11 to build, +including compiler and standard library support. + +The following minimum versions are required to build the library: + +* GCC 4.8 +* Clang 3.4 +* Visual Studio 14 2015 +* Intel 2015 Update 1 + +See [Platform-Specific Build Instructions](docs/platform_specific_build_instructions.md). + +## Installation + +This describes the installation process using cmake. As pre-requisites, you'll +need git and cmake installed. + +_See [dependencies.md](docs/dependencies.md) for more details regarding supported +versions of build tools._ + +```bash +# Check out the library. +$ git clone https://github.com/google/benchmark.git +# Go to the library root directory +$ cd benchmark +# Make a build directory to place the build output. +$ cmake -E make_directory "build" +# Generate build system files with cmake, and download any dependencies. +$ cmake -E chdir "build" cmake -DBENCHMARK_DOWNLOAD_DEPENDENCIES=on -DCMAKE_BUILD_TYPE=Release ../ +# or, starting with CMake 3.13, use a simpler form: +# cmake -DCMAKE_BUILD_TYPE=Release -S . -B "build" +# Build the library. +$ cmake --build "build" --config Release +``` +This builds the `benchmark` and `benchmark_main` libraries and tests. +On a unix system, the build directory should now look something like this: + +``` +/benchmark + /build + /src + /libbenchmark.a + /libbenchmark_main.a + /test + ... +``` + +Next, you can run the tests to check the build. + +```bash +$ cmake -E chdir "build" ctest --build-config Release +``` + +If you want to install the library globally, also run: + +``` +sudo cmake --build "build" --config Release --target install +``` + +Note that Google Benchmark requires Google Test to build and run the tests. This +dependency can be provided two ways: + +* Checkout the Google Test sources into `benchmark/googletest`. +* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during + configuration as above, the library will automatically download and build + any required dependencies. + +If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF` +to `CMAKE_ARGS`. + +### Debug vs Release + +By default, benchmark builds as a debug library. You will see a warning in the +output when this is the case. To build it as a release library instead, add +`-DCMAKE_BUILD_TYPE=Release` when generating the build system files, as shown +above. The use of `--config Release` in build commands is needed to properly +support multi-configuration tools (like Visual Studio for example) and can be +skipped for other build systems (like Makefile). + +To enable link-time optimisation, also add `-DBENCHMARK_ENABLE_LTO=true` when +generating the build system files. + +If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake +cache variables, if autodetection fails. + +If you are using clang, you may need to set `LLVMAR_EXECUTABLE`, +`LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables. + +To enable sanitizer checks (eg., `asan` and `tsan`), add: +``` + -DCMAKE_C_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all" + -DCMAKE_CXX_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all " +``` + +### Stable and Experimental Library Versions + +The main branch contains the latest stable version of the benchmarking library; +the API of which can be considered largely stable, with source breaking changes +being made only upon the release of a new major version. + +Newer, experimental, features are implemented and tested on the +[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish +to use, test, and provide feedback on the new features are encouraged to try +this branch. However, this branch provides no stability guarantees and reserves +the right to change and break the API at any time. + +## Usage + +### Basic usage + +Define a function that executes the code to measure, register it as a benchmark +function using the `BENCHMARK` macro, and ensure an appropriate `main` function +is available: + +```c++ +#include + +static void BM_StringCreation(benchmark::State& state) { + for (auto _ : state) + std::string empty_string; +} +// Register the function as a benchmark +BENCHMARK(BM_StringCreation); + +// Define another benchmark +static void BM_StringCopy(benchmark::State& state) { + std::string x = "hello"; + for (auto _ : state) + std::string copy(x); +} +BENCHMARK(BM_StringCopy); + +BENCHMARK_MAIN(); +``` + +To run the benchmark, compile and link against the `benchmark` library +(libbenchmark.a/.so). If you followed the build steps above, this library will +be under the build directory you created. + +```bash +# Example on linux after running the build steps above. Assumes the +# `benchmark` and `build` directories are under the current directory. +$ g++ mybenchmark.cc -std=c++11 -isystem benchmark/include \ + -Lbenchmark/build/src -lbenchmark -lpthread -o mybenchmark +``` + +Alternatively, link against the `benchmark_main` library and remove +`BENCHMARK_MAIN();` above to get the same behavior. + +The compiled executable will run all benchmarks by default. Pass the `--help` +flag for option information or see the [User Guide](docs/user_guide.md). + +### Usage with CMake + +If using CMake, it is recommended to link against the project-provided +`benchmark::benchmark` and `benchmark::benchmark_main` targets using +`target_link_libraries`. +It is possible to use ```find_package``` to import an installed version of the +library. +```cmake +find_package(benchmark REQUIRED) +``` +Alternatively, ```add_subdirectory``` will incorporate the library directly in +to one's CMake project. +```cmake +add_subdirectory(benchmark) +``` +Either way, link to the library as follows. +```cmake +target_link_libraries(MyTarget benchmark::benchmark) +``` diff --git a/thirdparty_builtin/benchmark-1.8.0/WORKSPACE b/thirdparty_builtin/benchmark-1.8.0/WORKSPACE new file mode 100644 index 000000000..74e7ebcbe --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/WORKSPACE @@ -0,0 +1,22 @@ +workspace(name = "com_github_google_benchmark") + +load("//:bazel/benchmark_deps.bzl", "benchmark_deps") + +benchmark_deps() + +load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies") + +rules_foreign_cc_dependencies() + +load("@rules_python//python:pip.bzl", pip3_install="pip_install") + +pip3_install( + name = "py_deps", + requirements = "//:requirements.txt", +) + +new_local_repository( + name = "python_headers", + build_file = "@//bindings/python:python_headers.BUILD", + path = "", # May be overwritten by setup.py. +) diff --git a/thirdparty_builtin/benchmark-1.8.0/_config.yml b/thirdparty_builtin/benchmark-1.8.0/_config.yml new file mode 100644 index 000000000..1fa5ff852 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/_config.yml @@ -0,0 +1,2 @@ +theme: jekyll-theme-midnight +markdown: GFM diff --git a/thirdparty_builtin/benchmark-1.5.0/appveyor.yml b/thirdparty_builtin/benchmark-1.8.0/appveyor.yml similarity index 94% rename from thirdparty_builtin/benchmark-1.5.0/appveyor.yml rename to thirdparty_builtin/benchmark-1.8.0/appveyor.yml index cf240190b..81da955f0 100644 --- a/thirdparty_builtin/benchmark-1.5.0/appveyor.yml +++ b/thirdparty_builtin/benchmark-1.8.0/appveyor.yml @@ -41,7 +41,7 @@ build_script: - cmake --build . --config %configuration% test_script: - - ctest -c %configuration% --timeout 300 --output-on-failure + - ctest --build-config %configuration% --timeout 300 --output-on-failure artifacts: - path: '_build/CMakeFiles/*.log' diff --git a/thirdparty_builtin/benchmark-1.8.0/bazel/benchmark_deps.bzl b/thirdparty_builtin/benchmark-1.8.0/bazel/benchmark_deps.bzl new file mode 100644 index 000000000..e9ca2cec5 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bazel/benchmark_deps.bzl @@ -0,0 +1,66 @@ +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") +load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") + +def benchmark_deps(): + """Loads dependencies required to build Google Benchmark.""" + + if "bazel_skylib" not in native.existing_rules(): + http_archive( + name = "bazel_skylib", + sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz", + "https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz", + ], + ) + + if "rules_foreign_cc" not in native.existing_rules(): + http_archive( + name = "rules_foreign_cc", + sha256 = "bcd0c5f46a49b85b384906daae41d277b3dc0ff27c7c752cc51e43048a58ec83", + strip_prefix = "rules_foreign_cc-0.7.1", + url = "https://github.com/bazelbuild/rules_foreign_cc/archive/0.7.1.tar.gz", + ) + + if "rules_python" not in native.existing_rules(): + http_archive( + name = "rules_python", + url = "https://github.com/bazelbuild/rules_python/releases/download/0.1.0/rules_python-0.1.0.tar.gz", + sha256 = "b6d46438523a3ec0f3cead544190ee13223a52f6a6765a29eae7b7cc24cc83a0", + ) + + if "com_google_absl" not in native.existing_rules(): + http_archive( + name = "com_google_absl", + sha256 = "f41868f7a938605c92936230081175d1eae87f6ea2c248f41077c8f88316f111", + strip_prefix = "abseil-cpp-20200225.2", + urls = ["https://github.com/abseil/abseil-cpp/archive/20200225.2.tar.gz"], + ) + + if "com_google_googletest" not in native.existing_rules(): + new_git_repository( + name = "com_google_googletest", + remote = "https://github.com/google/googletest.git", + tag = "release-1.11.0", + ) + + if "nanobind" not in native.existing_rules(): + new_git_repository( + name = "nanobind", + remote = "https://github.com/wjakob/nanobind.git", + commit = "1ffbfe836c9dac599496a170274ee0075094a607", # v0.2.0 + shallow_since = "1677873085 +0100", + build_file = "@//bindings/python:nanobind.BUILD", + recursive_init_submodules = True, + ) + + if "libpfm" not in native.existing_rules(): + # Downloaded from v4.9.0 tag at https://sourceforge.net/p/perfmon2/libpfm4/ref/master/tags/ + http_archive( + name = "libpfm", + build_file = str(Label("//tools:libpfm.BUILD.bazel")), + sha256 = "5da5f8872bde14b3634c9688d980f68bda28b510268723cc12973eedbab9fecc", + type = "tar.gz", + strip_prefix = "libpfm-4.11.0", + urls = ["https://sourceforge.net/projects/perfmon2/files/libpfm4/libpfm-4.11.0.tar.gz/download"], + ) diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/BUILD b/thirdparty_builtin/benchmark-1.8.0/bindings/python/BUILD new file mode 100644 index 000000000..9559a76b3 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/BUILD @@ -0,0 +1,3 @@ +exports_files(glob(["*.BUILD"])) +exports_files(["build_defs.bzl"]) + diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/build_defs.bzl b/thirdparty_builtin/benchmark-1.8.0/bindings/python/build_defs.bzl new file mode 100644 index 000000000..009820afd --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/build_defs.bzl @@ -0,0 +1,25 @@ +_SHARED_LIB_SUFFIX = { + "//conditions:default": ".so", + "//:windows": ".dll", +} + +def py_extension(name, srcs, hdrs = [], copts = [], features = [], deps = []): + for shared_lib_suffix in _SHARED_LIB_SUFFIX.values(): + shared_lib_name = name + shared_lib_suffix + native.cc_binary( + name = shared_lib_name, + linkshared = True, + linkstatic = True, + srcs = srcs + hdrs, + copts = copts, + features = features, + deps = deps, + ) + + return native.py_library( + name = name, + data = select({ + platform: [name + shared_lib_suffix] + for platform, shared_lib_suffix in _SHARED_LIB_SUFFIX.items() + }), + ) diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/BUILD b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/BUILD new file mode 100644 index 000000000..89ec76e0d --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/BUILD @@ -0,0 +1,40 @@ +load("//bindings/python:build_defs.bzl", "py_extension") + +py_library( + name = "google_benchmark", + srcs = ["__init__.py"], + visibility = ["//visibility:public"], + deps = [ + ":_benchmark", + ], +) + +py_extension( + name = "_benchmark", + srcs = ["benchmark.cc"], + copts = [ + "-fexceptions", + "-fno-strict-aliasing", + ], + features = [ + "-use_header_modules", + "-parse_headers", + ], + deps = [ + "//:benchmark", + "@nanobind", + "@python_headers", + ], +) + +py_test( + name = "example", + srcs = ["example.py"], + python_version = "PY3", + srcs_version = "PY3", + visibility = ["//visibility:public"], + deps = [ + ":google_benchmark", + ], +) + diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/__init__.py b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/__init__.py new file mode 100644 index 000000000..a118dad7e --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/__init__.py @@ -0,0 +1,162 @@ +# Copyright 2020 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Python benchmarking utilities. + +Example usage: + import google_benchmark as benchmark + + @benchmark.register + def my_benchmark(state): + ... # Code executed outside `while` loop is not timed. + + while state: + ... # Code executed within `while` loop is timed. + + if __name__ == '__main__': + benchmark.main() +""" +import atexit + +from absl import app +from google_benchmark import _benchmark +from google_benchmark._benchmark import ( + Counter, + kNanosecond, + kMicrosecond, + kMillisecond, + kSecond, + oNone, + o1, + oN, + oNSquared, + oNCubed, + oLogN, + oNLogN, + oAuto, + oLambda, + State, +) + + +__all__ = [ + "register", + "main", + "Counter", + "kNanosecond", + "kMicrosecond", + "kMillisecond", + "kSecond", + "oNone", + "o1", + "oN", + "oNSquared", + "oNCubed", + "oLogN", + "oNLogN", + "oAuto", + "oLambda", + "State", +] + +__version__ = "1.8.0" + + +class __OptionMaker: + """A stateless class to collect benchmark options. + + Collect all decorator calls like @option.range(start=0, limit=1<<5). + """ + + class Options: + """Pure data class to store options calls, along with the benchmarked function.""" + + def __init__(self, func): + self.func = func + self.builder_calls = [] + + @classmethod + def make(cls, func_or_options): + """Make Options from Options or the benchmarked function.""" + if isinstance(func_or_options, cls.Options): + return func_or_options + return cls.Options(func_or_options) + + def __getattr__(self, builder_name): + """Append option call in the Options.""" + + # The function that get returned on @option.range(start=0, limit=1<<5). + def __builder_method(*args, **kwargs): + + # The decorator that get called, either with the benchmared function + # or the previous Options + def __decorator(func_or_options): + options = self.make(func_or_options) + options.builder_calls.append((builder_name, args, kwargs)) + # The decorator returns Options so it is not technically a decorator + # and needs a final call to @register + return options + + return __decorator + + return __builder_method + + +# Alias for nicer API. +# We have to instantiate an object, even if stateless, to be able to use __getattr__ +# on option.range +option = __OptionMaker() + + +def register(undefined=None, *, name=None): + """Register function for benchmarking.""" + if undefined is None: + # Decorator is called without parenthesis so we return a decorator + return lambda f: register(f, name=name) + + # We have either the function to benchmark (simple case) or an instance of Options + # (@option._ case). + options = __OptionMaker.make(undefined) + + if name is None: + name = options.func.__name__ + + # We register the benchmark and reproduce all the @option._ calls onto the + # benchmark builder pattern + benchmark = _benchmark.RegisterBenchmark(name, options.func) + for name, args, kwargs in options.builder_calls[::-1]: + getattr(benchmark, name)(*args, **kwargs) + + # return the benchmarked function because the decorator does not modify it + return options.func + + +def _flags_parser(argv): + argv = _benchmark.Initialize(argv) + return app.parse_flags_with_usage(argv) + + +def _run_benchmarks(argv): + if len(argv) > 1: + raise app.UsageError("Too many command-line arguments.") + return _benchmark.RunSpecifiedBenchmarks() + + +def main(argv=None): + return app.run(_run_benchmarks, argv=argv, flags_parser=_flags_parser) + + +# Methods for use with custom main function. +initialize = _benchmark.Initialize +run_benchmarks = _benchmark.RunSpecifiedBenchmarks +atexit.register(_benchmark.ClearRegisteredBenchmarks) diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/benchmark.cc b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/benchmark.cc new file mode 100644 index 000000000..f44476901 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/benchmark.cc @@ -0,0 +1,184 @@ +// Benchmark for Python. + +#include "benchmark/benchmark.h" + +#include "nanobind/nanobind.h" +#include "nanobind/operators.h" +#include "nanobind/stl/bind_map.h" +#include "nanobind/stl/string.h" +#include "nanobind/stl/vector.h" + +NB_MAKE_OPAQUE(benchmark::UserCounters); + +namespace { +namespace nb = nanobind; + +std::vector Initialize(const std::vector& argv) { + // The `argv` pointers here become invalid when this function returns, but + // benchmark holds the pointer to `argv[0]`. We create a static copy of it + // so it persists, and replace the pointer below. + static std::string executable_name(argv[0]); + std::vector ptrs; + ptrs.reserve(argv.size()); + for (auto& arg : argv) { + ptrs.push_back(const_cast(arg.c_str())); + } + ptrs[0] = const_cast(executable_name.c_str()); + int argc = static_cast(argv.size()); + benchmark::Initialize(&argc, ptrs.data()); + std::vector remaining_argv; + remaining_argv.reserve(argc); + for (int i = 0; i < argc; ++i) { + remaining_argv.emplace_back(ptrs[i]); + } + return remaining_argv; +} + +benchmark::internal::Benchmark* RegisterBenchmark(const std::string& name, + nb::callable f) { + return benchmark::RegisterBenchmark( + name, [f](benchmark::State& state) { f(&state); }); +} + +NB_MODULE(_benchmark, m) { + + using benchmark::TimeUnit; + nb::enum_(m, "TimeUnit") + .value("kNanosecond", TimeUnit::kNanosecond) + .value("kMicrosecond", TimeUnit::kMicrosecond) + .value("kMillisecond", TimeUnit::kMillisecond) + .value("kSecond", TimeUnit::kSecond) + .export_values(); + + using benchmark::BigO; + nb::enum_(m, "BigO") + .value("oNone", BigO::oNone) + .value("o1", BigO::o1) + .value("oN", BigO::oN) + .value("oNSquared", BigO::oNSquared) + .value("oNCubed", BigO::oNCubed) + .value("oLogN", BigO::oLogN) + .value("oNLogN", BigO::oNLogN) + .value("oAuto", BigO::oAuto) + .value("oLambda", BigO::oLambda) + .export_values(); + + using benchmark::internal::Benchmark; + nb::class_(m, "Benchmark") + // For methods returning a pointer to the current object, reference + // return policy is used to ask nanobind not to take ownership of the + // returned object and avoid calling delete on it. + // https://pybind11.readthedocs.io/en/stable/advanced/functions.html#return-value-policies + // + // For methods taking a const std::vector<...>&, a copy is created + // because a it is bound to a Python list. + // https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html + .def("unit", &Benchmark::Unit, nb::rv_policy::reference) + .def("arg", &Benchmark::Arg, nb::rv_policy::reference) + .def("args", &Benchmark::Args, nb::rv_policy::reference) + .def("range", &Benchmark::Range, nb::rv_policy::reference, + nb::arg("start"), nb::arg("limit")) + .def("dense_range", &Benchmark::DenseRange, + nb::rv_policy::reference, nb::arg("start"), + nb::arg("limit"), nb::arg("step") = 1) + .def("ranges", &Benchmark::Ranges, nb::rv_policy::reference) + .def("args_product", &Benchmark::ArgsProduct, + nb::rv_policy::reference) + .def("arg_name", &Benchmark::ArgName, nb::rv_policy::reference) + .def("arg_names", &Benchmark::ArgNames, + nb::rv_policy::reference) + .def("range_pair", &Benchmark::RangePair, + nb::rv_policy::reference, nb::arg("lo1"), nb::arg("hi1"), + nb::arg("lo2"), nb::arg("hi2")) + .def("range_multiplier", &Benchmark::RangeMultiplier, + nb::rv_policy::reference) + .def("min_time", &Benchmark::MinTime, nb::rv_policy::reference) + .def("min_warmup_time", &Benchmark::MinWarmUpTime, + nb::rv_policy::reference) + .def("iterations", &Benchmark::Iterations, + nb::rv_policy::reference) + .def("repetitions", &Benchmark::Repetitions, + nb::rv_policy::reference) + .def("report_aggregates_only", &Benchmark::ReportAggregatesOnly, + nb::rv_policy::reference, nb::arg("value") = true) + .def("display_aggregates_only", &Benchmark::DisplayAggregatesOnly, + nb::rv_policy::reference, nb::arg("value") = true) + .def("measure_process_cpu_time", &Benchmark::MeasureProcessCPUTime, + nb::rv_policy::reference) + .def("use_real_time", &Benchmark::UseRealTime, + nb::rv_policy::reference) + .def("use_manual_time", &Benchmark::UseManualTime, + nb::rv_policy::reference) + .def( + "complexity", + (Benchmark * (Benchmark::*)(benchmark::BigO)) & Benchmark::Complexity, + nb::rv_policy::reference, + nb::arg("complexity") = benchmark::oAuto); + + using benchmark::Counter; + nb::class_ py_counter(m, "Counter"); + + nb::enum_(py_counter, "Flags") + .value("kDefaults", Counter::Flags::kDefaults) + .value("kIsRate", Counter::Flags::kIsRate) + .value("kAvgThreads", Counter::Flags::kAvgThreads) + .value("kAvgThreadsRate", Counter::Flags::kAvgThreadsRate) + .value("kIsIterationInvariant", Counter::Flags::kIsIterationInvariant) + .value("kIsIterationInvariantRate", + Counter::Flags::kIsIterationInvariantRate) + .value("kAvgIterations", Counter::Flags::kAvgIterations) + .value("kAvgIterationsRate", Counter::Flags::kAvgIterationsRate) + .value("kInvert", Counter::Flags::kInvert) + .export_values() + .def(nb::self | nb::self); + + nb::enum_(py_counter, "OneK") + .value("kIs1000", Counter::OneK::kIs1000) + .value("kIs1024", Counter::OneK::kIs1024) + .export_values(); + + py_counter + .def(nb::init(), + nb::arg("value") = 0., nb::arg("flags") = Counter::kDefaults, + nb::arg("k") = Counter::kIs1000) + .def("__init__", ([](Counter *c, double value) { new (c) Counter(value); })) + .def_rw("value", &Counter::value) + .def_rw("flags", &Counter::flags) + .def_rw("oneK", &Counter::oneK) + .def(nb::init_implicit()); + + nb::implicitly_convertible(); + + nb::bind_map(m, "UserCounters"); + + using benchmark::State; + nb::class_(m, "State") + .def("__bool__", &State::KeepRunning) + .def_prop_ro("keep_running", &State::KeepRunning) + .def("pause_timing", &State::PauseTiming) + .def("resume_timing", &State::ResumeTiming) + .def("skip_with_error", &State::SkipWithError) + .def_prop_ro("error_occurred", &State::error_occurred) + .def("set_iteration_time", &State::SetIterationTime) + .def_prop_rw("bytes_processed", &State::bytes_processed, + &State::SetBytesProcessed) + .def_prop_rw("complexity_n", &State::complexity_length_n, + &State::SetComplexityN) + .def_prop_rw("items_processed", &State::items_processed, + &State::SetItemsProcessed) + .def("set_label", &State::SetLabel) + .def("range", &State::range, nb::arg("pos") = 0) + .def_prop_ro("iterations", &State::iterations) + .def_prop_ro("name", &State::name) + .def_rw("counters", &State::counters) + .def_prop_ro("thread_index", &State::thread_index) + .def_prop_ro("threads", &State::threads); + + m.def("Initialize", Initialize); + m.def("RegisterBenchmark", RegisterBenchmark, + nb::rv_policy::reference); + m.def("RunSpecifiedBenchmarks", + []() { benchmark::RunSpecifiedBenchmarks(); }); + m.def("ClearRegisteredBenchmarks", benchmark::ClearRegisteredBenchmarks); +}; +} // namespace diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/example.py b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/example.py new file mode 100644 index 000000000..d95a0438d --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/google_benchmark/example.py @@ -0,0 +1,136 @@ +# Copyright 2020 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Example of Python using C++ benchmark framework. + +To run this example, you must first install the `google_benchmark` Python package. + +To install using `setup.py`, download and extract the `google_benchmark` source. +In the extracted directory, execute: + python setup.py install +""" + +import random +import time + +import google_benchmark as benchmark +from google_benchmark import Counter + + +@benchmark.register +def empty(state): + while state: + pass + + +@benchmark.register +def sum_million(state): + while state: + sum(range(1_000_000)) + +@benchmark.register +def pause_timing(state): + """Pause timing every iteration.""" + while state: + # Construct a list of random ints every iteration without timing it + state.pause_timing() + random_list = [random.randint(0, 100) for _ in range(100)] + state.resume_timing() + # Time the in place sorting algorithm + random_list.sort() + + +@benchmark.register +def skipped(state): + if True: # Test some predicate here. + state.skip_with_error("some error") + return # NOTE: You must explicitly return, or benchmark will continue. + + ... # Benchmark code would be here. + + +@benchmark.register +def manual_timing(state): + while state: + # Manually count Python CPU time + start = time.perf_counter() # perf_counter_ns() in Python 3.7+ + # Something to benchmark + time.sleep(0.01) + end = time.perf_counter() + state.set_iteration_time(end - start) + + +@benchmark.register +def custom_counters(state): + """Collect custom metric using benchmark.Counter.""" + num_foo = 0.0 + while state: + # Benchmark some code here + pass + # Collect some custom metric named foo + num_foo += 0.13 + + # Automatic Counter from numbers. + state.counters["foo"] = num_foo + # Set a counter as a rate. + state.counters["foo_rate"] = Counter(num_foo, Counter.kIsRate) + # Set a counter as an inverse of rate. + state.counters["foo_inv_rate"] = Counter(num_foo, Counter.kIsRate | Counter.kInvert) + # Set a counter as a thread-average quantity. + state.counters["foo_avg"] = Counter(num_foo, Counter.kAvgThreads) + # There's also a combined flag: + state.counters["foo_avg_rate"] = Counter(num_foo, Counter.kAvgThreadsRate) + + +@benchmark.register +@benchmark.option.measure_process_cpu_time() +@benchmark.option.use_real_time() +def with_options(state): + while state: + sum(range(1_000_000)) + + +@benchmark.register(name="sum_million_microseconds") +@benchmark.option.unit(benchmark.kMicrosecond) +def with_options2(state): + while state: + sum(range(1_000_000)) + + +@benchmark.register +@benchmark.option.arg(100) +@benchmark.option.arg(1000) +def passing_argument(state): + while state: + sum(range(state.range(0))) + + +@benchmark.register +@benchmark.option.range(8, limit=8 << 10) +def using_range(state): + while state: + sum(range(state.range(0))) + + +@benchmark.register +@benchmark.option.range_multiplier(2) +@benchmark.option.range(1 << 10, 1 << 18) +@benchmark.option.complexity(benchmark.oN) +def computing_complexity(state): + while state: + sum(range(state.range(0))) + state.complexity_n = state.range(0) + + +if __name__ == "__main__": + benchmark.main() diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/nanobind.BUILD b/thirdparty_builtin/benchmark-1.8.0/bindings/python/nanobind.BUILD new file mode 100644 index 000000000..35536bba2 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/nanobind.BUILD @@ -0,0 +1,56 @@ + +config_setting( + name = "msvc_compiler", + flag_values = {"@bazel_tools//tools/cpp:compiler": "msvc-cl"}, +) + +cc_library( + name = "nanobind", + hdrs = glob( + include = [ + "include/nanobind/*.h", + "include/nanobind/stl/*.h", + "include/nanobind/detail/*.h", + ], + exclude = [], + ), + srcs = [ + "include/nanobind/stl/detail/nb_dict.h", + "include/nanobind/stl/detail/nb_list.h", + "include/nanobind/stl/detail/traits.h", + "ext/robin_map/include/tsl/robin_map.h", + "ext/robin_map/include/tsl/robin_hash.h", + "ext/robin_map/include/tsl/robin_growth_policy.h", + "ext/robin_map/include/tsl/robin_set.h", + "src/buffer.h", + "src/common.cpp", + "src/error.cpp", + "src/implicit.cpp", + "src/nb_enum.cpp", + "src/nb_func.cpp", + "src/nb_internals.cpp", + "src/nb_internals.h", + "src/nb_ndarray.cpp", + "src/nb_type.cpp", + "src/trampoline.cpp", + ], + copts = select({ + ":msvc_compiler": [], + "//conditions:default": [ + "-fexceptions", + "-Os", # size optimization + "-flto", # enable LTO + ], + }), + linkopts = select({ + "@com_github_google_benchmark//:macos": [ + "-undefined dynamic_lookup", + "-Wl,-no_fixup_chains", + "-Wl,-dead_strip", + ], + "//conditions:default": [], + }), + includes = ["include", "ext/robin_map/include"], + deps = ["@python_headers"], + visibility = ["//visibility:public"], +) diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/python_headers.BUILD b/thirdparty_builtin/benchmark-1.8.0/bindings/python/python_headers.BUILD new file mode 100644 index 000000000..9c34cf6ca --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/python_headers.BUILD @@ -0,0 +1,6 @@ +cc_library( + name = "python_headers", + hdrs = glob(["**/*.h"]), + includes = ["."], + visibility = ["//visibility:public"], +) diff --git a/thirdparty_builtin/benchmark-1.8.0/bindings/python/requirements.txt b/thirdparty_builtin/benchmark-1.8.0/bindings/python/requirements.txt new file mode 100644 index 000000000..f5bbe7eca --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/bindings/python/requirements.txt @@ -0,0 +1,2 @@ +absl-py>=0.7.1 + diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/AddCXXCompilerFlag.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/AddCXXCompilerFlag.cmake similarity index 94% rename from thirdparty_builtin/benchmark-1.5.0/cmake/AddCXXCompilerFlag.cmake rename to thirdparty_builtin/benchmark-1.8.0/cmake/AddCXXCompilerFlag.cmake index d0d209981..858589e97 100644 --- a/thirdparty_builtin/benchmark-1.5.0/cmake/AddCXXCompilerFlag.cmake +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/AddCXXCompilerFlag.cmake @@ -34,9 +34,11 @@ function(add_cxx_compiler_flag FLAG) check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") if(${MANGLED_FLAG}) - set(VARIANT ${ARGV1}) - if(ARGV1) + if(ARGC GREATER 1) + set(VARIANT ${ARGV1}) string(TOUPPER "_${VARIANT}" VARIANT) + else() + set(VARIANT "") endif() set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${BENCHMARK_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) endif() @@ -49,9 +51,11 @@ function(add_required_cxx_compiler_flag FLAG) check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") if(${MANGLED_FLAG}) - set(VARIANT ${ARGV1}) - if(ARGV1) + if(ARGC GREATER 1) + set(VARIANT ${ARGV1}) string(TOUPPER "_${VARIANT}" VARIANT) + else() + set(VARIANT "") endif() set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/CXXFeatureCheck.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/CXXFeatureCheck.cmake similarity index 56% rename from thirdparty_builtin/benchmark-1.5.0/cmake/CXXFeatureCheck.cmake rename to thirdparty_builtin/benchmark-1.8.0/cmake/CXXFeatureCheck.cmake index 99b56dd62..e51482659 100644 --- a/thirdparty_builtin/benchmark-1.5.0/cmake/CXXFeatureCheck.cmake +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/CXXFeatureCheck.cmake @@ -17,6 +17,8 @@ if(__cxx_feature_check) endif() set(__cxx_feature_check INCLUDED) +option(CXXFEATURECHECK_DEBUG OFF) + function(cxx_feature_check FILE) string(TOLOWER ${FILE} FILE) string(TOUPPER ${FILE} VAR) @@ -27,26 +29,38 @@ function(cxx_feature_check FILE) return() endif() + set(FEATURE_CHECK_CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) + if (ARGC GREATER 1) + message(STATUS "Enabling additional flags: ${ARGV1}") + list(APPEND FEATURE_CHECK_CMAKE_FLAGS ${ARGV1}) + endif() + if (NOT DEFINED COMPILE_${FEATURE}) - message(STATUS "Performing Test ${FEATURE}") if(CMAKE_CROSSCOMPILING) + message(STATUS "Cross-compiling to test ${FEATURE}") try_compile(COMPILE_${FEATURE} ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp - CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS} - LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES}) + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED ON + CMAKE_FLAGS ${FEATURE_CHECK_CMAKE_FLAGS} + LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES} + OUTPUT_VARIABLE COMPILE_OUTPUT_VAR) if(COMPILE_${FEATURE}) message(WARNING "If you see build failures due to cross compilation, try setting HAVE_${VAR} to 0") - set(RUN_${FEATURE} 0) + set(RUN_${FEATURE} 0 CACHE INTERNAL "") else() - set(RUN_${FEATURE} 1) + set(RUN_${FEATURE} 1 CACHE INTERNAL "") endif() else() - message(STATUS "Performing Test ${FEATURE}") + message(STATUS "Compiling and running to test ${FEATURE}") try_run(RUN_${FEATURE} COMPILE_${FEATURE} ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp - CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS} - LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES}) + CXX_STANDARD 11 + CXX_STANDARD_REQUIRED ON + CMAKE_FLAGS ${FEATURE_CHECK_CMAKE_FLAGS} + LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES} + COMPILE_OUTPUT_VARIABLE COMPILE_OUTPUT_VAR) endif() endif() @@ -56,7 +70,11 @@ function(cxx_feature_check FILE) add_definitions(-DHAVE_${VAR}) else() if(NOT COMPILE_${FEATURE}) - message(STATUS "Performing Test ${FEATURE} -- failed to compile") + if(CXXFEATURECHECK_DEBUG) + message(STATUS "Performing Test ${FEATURE} -- failed to compile: ${COMPILE_OUTPUT_VAR}") + else() + message(STATUS "Performing Test ${FEATURE} -- failed to compile") + endif() else() message(STATUS "Performing Test ${FEATURE} -- compiled but failed to run") endif() diff --git a/thirdparty_builtin/benchmark-1.8.0/cmake/Config.cmake.in b/thirdparty_builtin/benchmark-1.8.0/cmake/Config.cmake.in new file mode 100644 index 000000000..2e15f0cf8 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/Config.cmake.in @@ -0,0 +1,7 @@ +@PACKAGE_INIT@ + +include (CMakeFindDependencyMacro) + +find_dependency (Threads) + +include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/GetGitVersion.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/GetGitVersion.cmake similarity index 61% rename from thirdparty_builtin/benchmark-1.5.0/cmake/GetGitVersion.cmake rename to thirdparty_builtin/benchmark-1.8.0/cmake/GetGitVersion.cmake index 4f10f226d..04a1f9b70 100644 --- a/thirdparty_builtin/benchmark-1.5.0/cmake/GetGitVersion.cmake +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/GetGitVersion.cmake @@ -20,16 +20,20 @@ set(__get_git_version INCLUDED) function(get_git_version var) if(GIT_EXECUTABLE) - execute_process(COMMAND ${GIT_EXECUTABLE} describe --match "v[0-9]*.[0-9]*.[0-9]*" --abbrev=8 + execute_process(COMMAND ${GIT_EXECUTABLE} describe --tags --match "v[0-9]*.[0-9]*.[0-9]*" --abbrev=8 WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} RESULT_VARIABLE status - OUTPUT_VARIABLE GIT_VERSION + OUTPUT_VARIABLE GIT_DESCRIBE_VERSION ERROR_QUIET) - if(${status}) - set(GIT_VERSION "v0.0.0") + if(status) + set(GIT_DESCRIBE_VERSION "v0.0.0") + endif() + + string(STRIP ${GIT_DESCRIBE_VERSION} GIT_DESCRIBE_VERSION) + if(GIT_DESCRIBE_VERSION MATCHES v[^-]*-) + string(REGEX REPLACE "v([^-]*)-([0-9]+)-.*" "\\1.\\2" GIT_VERSION ${GIT_DESCRIBE_VERSION}) else() - string(STRIP ${GIT_VERSION} GIT_VERSION) - string(REGEX REPLACE "-[0-9]+-g" "-" GIT_VERSION ${GIT_VERSION}) + string(REGEX REPLACE "v(.*)" "\\1" GIT_VERSION ${GIT_DESCRIBE_VERSION}) endif() # Work out if the repository is dirty @@ -43,12 +47,12 @@ function(get_git_version var) ERROR_QUIET) string(COMPARE NOTEQUAL "${GIT_DIFF_INDEX}" "" GIT_DIRTY) if (${GIT_DIRTY}) - set(GIT_VERSION "${GIT_VERSION}-dirty") + set(GIT_DESCRIBE_VERSION "${GIT_DESCRIBE_VERSION}-dirty") endif() + message(STATUS "git version: ${GIT_DESCRIBE_VERSION} normalized to ${GIT_VERSION}") else() - set(GIT_VERSION "v0.0.0") + set(GIT_VERSION "0.0.0") endif() - message(STATUS "git Version: ${GIT_VERSION}") set(${var} ${GIT_VERSION} PARENT_SCOPE) endfunction() diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/GoogleTest.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/GoogleTest.cmake similarity index 73% rename from thirdparty_builtin/benchmark-1.5.0/cmake/GoogleTest.cmake rename to thirdparty_builtin/benchmark-1.8.0/cmake/GoogleTest.cmake index fb7c6be25..44adbfbe4 100644 --- a/thirdparty_builtin/benchmark-1.5.0/cmake/GoogleTest.cmake +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/GoogleTest.cmake @@ -2,7 +2,7 @@ set(GOOGLETEST_PREFIX "${benchmark_BINARY_DIR}/third_party/googletest") configure_file(${benchmark_SOURCE_DIR}/cmake/GoogleTest.cmake.in ${GOOGLETEST_PREFIX}/CMakeLists.txt @ONLY) -set(GOOGLETEST_PATH "${CMAKE_CURRENT_SOURCE_DIR}/googletest") # Mind the quotes +set(GOOGLETEST_PATH "${CMAKE_CURRENT_SOURCE_DIR}/googletest" CACHE PATH "") # Mind the quotes execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" -DALLOW_DOWNLOADING_GOOGLETEST=${BENCHMARK_DOWNLOAD_DEPENDENCIES} -DGOOGLETEST_PATH:PATH=${GOOGLETEST_PATH} . RESULT_VARIABLE result @@ -29,13 +29,24 @@ set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) include(${GOOGLETEST_PREFIX}/googletest-paths.cmake) +# googletest doesn't seem to want to stay build warning clean so let's not hurt ourselves. +if (MSVC) + add_compile_options(/wd4244 /wd4722) +else() + add_compile_options(-w) +endif() + # Add googletest directly to our build. This defines # the gtest and gtest_main targets. add_subdirectory(${GOOGLETEST_SOURCE_DIR} ${GOOGLETEST_BINARY_DIR} EXCLUDE_FROM_ALL) -set_target_properties(gtest PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) -set_target_properties(gtest_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) -set_target_properties(gmock PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) -set_target_properties(gmock_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) +if(NOT DEFINED GTEST_COMPILE_COMMANDS) + set(GTEST_COMPILE_COMMANDS ON) +endif() + +set_target_properties(gtest PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) +set_target_properties(gtest_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) +set_target_properties(gmock PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) +set_target_properties(gmock_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $ EXPORT_COMPILE_COMMANDS ${GTEST_COMPILE_COMMANDS}) diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/GoogleTest.cmake.in b/thirdparty_builtin/benchmark-1.8.0/cmake/GoogleTest.cmake.in similarity index 90% rename from thirdparty_builtin/benchmark-1.5.0/cmake/GoogleTest.cmake.in rename to thirdparty_builtin/benchmark-1.8.0/cmake/GoogleTest.cmake.in index 28818ee29..ce653ac37 100644 --- a/thirdparty_builtin/benchmark-1.5.0/cmake/GoogleTest.cmake.in +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/GoogleTest.cmake.in @@ -31,13 +31,14 @@ if(EXISTS "${GOOGLETEST_PATH}" AND IS_DIRECTORY "${GOOGLETEST_PATH}" ) else() if(NOT ALLOW_DOWNLOADING_GOOGLETEST) - message(SEND_ERROR "Did not find Google Test sources! Either pass correct path in GOOGLETEST_PATH, or enable ALLOW_DOWNLOADING_GOOGLETEST, or disable BENCHMARK_ENABLE_GTEST_TESTS / BENCHMARK_ENABLE_TESTING.") + message(SEND_ERROR "Did not find Google Test sources! Either pass correct path in GOOGLETEST_PATH, or enable BENCHMARK_DOWNLOAD_DEPENDENCIES, or disable BENCHMARK_USE_BUNDLED_GTEST, or disable BENCHMARK_ENABLE_GTEST_TESTS / BENCHMARK_ENABLE_TESTING.") + return() else() message(WARNING "Did not find Google Test sources! Fetching from web...") ExternalProject_Add( googletest GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG master + GIT_TAG "release-1.11.0" PREFIX "${CMAKE_BINARY_DIR}" STAMP_DIR "${CMAKE_BINARY_DIR}/stamp" DOWNLOAD_DIR "${CMAKE_BINARY_DIR}/download" diff --git a/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMAr.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMAr.cmake new file mode 100644 index 000000000..23469813c --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMAr.cmake @@ -0,0 +1,16 @@ +include(FeatureSummary) + +find_program(LLVMAR_EXECUTABLE + NAMES llvm-ar + DOC "The llvm-ar executable" + ) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(LLVMAr + DEFAULT_MSG + LLVMAR_EXECUTABLE) + +SET_PACKAGE_PROPERTIES(LLVMAr PROPERTIES + URL https://llvm.org/docs/CommandGuide/llvm-ar.html + DESCRIPTION "create, modify, and extract from archives" +) diff --git a/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMNm.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMNm.cmake new file mode 100644 index 000000000..e56430a04 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMNm.cmake @@ -0,0 +1,16 @@ +include(FeatureSummary) + +find_program(LLVMNM_EXECUTABLE + NAMES llvm-nm + DOC "The llvm-nm executable" + ) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(LLVMNm + DEFAULT_MSG + LLVMNM_EXECUTABLE) + +SET_PACKAGE_PROPERTIES(LLVMNm PROPERTIES + URL https://llvm.org/docs/CommandGuide/llvm-nm.html + DESCRIPTION "list LLVM bitcode and object file’s symbol table" +) diff --git a/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMRanLib.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMRanLib.cmake new file mode 100644 index 000000000..7b53e1a79 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindLLVMRanLib.cmake @@ -0,0 +1,15 @@ +include(FeatureSummary) + +find_program(LLVMRANLIB_EXECUTABLE + NAMES llvm-ranlib + DOC "The llvm-ranlib executable" + ) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(LLVMRanLib + DEFAULT_MSG + LLVMRANLIB_EXECUTABLE) + +SET_PACKAGE_PROPERTIES(LLVMRanLib PROPERTIES + DESCRIPTION "generate index for LLVM archive" +) diff --git a/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindPFM.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindPFM.cmake new file mode 100644 index 000000000..cf807a1ee --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/Modules/FindPFM.cmake @@ -0,0 +1,26 @@ +# If successful, the following variables will be defined: +# HAVE_LIBPFM. +# Set BENCHMARK_ENABLE_LIBPFM to 0 to disable, regardless of libpfm presence. +include(CheckIncludeFile) +include(CheckLibraryExists) +include(FeatureSummary) +enable_language(C) + +set_package_properties(PFM PROPERTIES + URL http://perfmon2.sourceforge.net/ + DESCRIPTION "a helper library to develop monitoring tools" + PURPOSE "Used to program specific performance monitoring events") + +check_library_exists(libpfm.a pfm_initialize "" HAVE_LIBPFM_INITIALIZE) +if(HAVE_LIBPFM_INITIALIZE) + check_include_file(perfmon/perf_event.h HAVE_PERFMON_PERF_EVENT_H) + check_include_file(perfmon/pfmlib.h HAVE_PERFMON_PFMLIB_H) + check_include_file(perfmon/pfmlib_perf_event.h HAVE_PERFMON_PFMLIB_PERF_EVENT_H) + if(HAVE_PERFMON_PERF_EVENT_H AND HAVE_PERFMON_PFMLIB_H AND HAVE_PERFMON_PFMLIB_PERF_EVENT_H) + message("Using Perf Counters.") + set(HAVE_LIBPFM 1) + set(PFM_FOUND 1) + endif() +else() + message("Perf Counters support requested, but was unable to find libpfm.") +endif() diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/benchmark.pc.in b/thirdparty_builtin/benchmark-1.8.0/cmake/benchmark.pc.in similarity index 73% rename from thirdparty_builtin/benchmark-1.5.0/cmake/benchmark.pc.in rename to thirdparty_builtin/benchmark-1.8.0/cmake/benchmark.pc.in index 43ca8f91d..9dae881c7 100644 --- a/thirdparty_builtin/benchmark-1.5.0/cmake/benchmark.pc.in +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/benchmark.pc.in @@ -1,7 +1,7 @@ prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} -libdir=${prefix}/lib -includedir=${prefix}/include +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: @PROJECT_NAME@ Description: Google microbenchmark framework diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/gnu_posix_regex.cpp b/thirdparty_builtin/benchmark-1.8.0/cmake/gnu_posix_regex.cpp similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/cmake/gnu_posix_regex.cpp rename to thirdparty_builtin/benchmark-1.8.0/cmake/gnu_posix_regex.cpp diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/llvm-toolchain.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/llvm-toolchain.cmake similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/cmake/llvm-toolchain.cmake rename to thirdparty_builtin/benchmark-1.8.0/cmake/llvm-toolchain.cmake diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/posix_regex.cpp b/thirdparty_builtin/benchmark-1.8.0/cmake/posix_regex.cpp similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/cmake/posix_regex.cpp rename to thirdparty_builtin/benchmark-1.8.0/cmake/posix_regex.cpp diff --git a/thirdparty_builtin/benchmark-1.8.0/cmake/pthread_affinity.cpp b/thirdparty_builtin/benchmark-1.8.0/cmake/pthread_affinity.cpp new file mode 100644 index 000000000..7b143bc02 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/cmake/pthread_affinity.cpp @@ -0,0 +1,16 @@ +#include +int main() { + cpu_set_t set; + CPU_ZERO(&set); + for (int i = 0; i < CPU_SETSIZE; ++i) { + CPU_SET(i, &set); + CPU_CLR(i, &set); + } + pthread_t self = pthread_self(); + int ret; + ret = pthread_getaffinity_np(self, sizeof(set), &set); + if (ret != 0) return ret; + ret = pthread_setaffinity_np(self, sizeof(set), &set); + if (ret != 0) return ret; + return 0; +} diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/split_list.cmake b/thirdparty_builtin/benchmark-1.8.0/cmake/split_list.cmake similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/cmake/split_list.cmake rename to thirdparty_builtin/benchmark-1.8.0/cmake/split_list.cmake diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/std_regex.cpp b/thirdparty_builtin/benchmark-1.8.0/cmake/std_regex.cpp similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/cmake/std_regex.cpp rename to thirdparty_builtin/benchmark-1.8.0/cmake/std_regex.cpp diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/steady_clock.cpp b/thirdparty_builtin/benchmark-1.8.0/cmake/steady_clock.cpp similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/cmake/steady_clock.cpp rename to thirdparty_builtin/benchmark-1.8.0/cmake/steady_clock.cpp diff --git a/thirdparty_builtin/benchmark-1.5.0/cmake/thread_safety_attributes.cpp b/thirdparty_builtin/benchmark-1.8.0/cmake/thread_safety_attributes.cpp similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/cmake/thread_safety_attributes.cpp rename to thirdparty_builtin/benchmark-1.8.0/cmake/thread_safety_attributes.cpp diff --git a/thirdparty_builtin/benchmark-1.5.0/docs/AssemblyTests.md b/thirdparty_builtin/benchmark-1.8.0/docs/AssemblyTests.md similarity index 99% rename from thirdparty_builtin/benchmark-1.5.0/docs/AssemblyTests.md rename to thirdparty_builtin/benchmark-1.8.0/docs/AssemblyTests.md index 1fbdc269b..89df7ca52 100644 --- a/thirdparty_builtin/benchmark-1.5.0/docs/AssemblyTests.md +++ b/thirdparty_builtin/benchmark-1.8.0/docs/AssemblyTests.md @@ -111,6 +111,7 @@ between compilers or compiler versions. A common example of this is matching stack frame addresses. In this case regular expressions can be used to match the differing bits of output. For example: + ```c++ int ExternInt; struct Point { int x, y, z; }; @@ -127,6 +128,7 @@ extern "C" void test_store_point() { // CHECK: ret } ``` + ## Current Requirements and Limitations diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/_config.yml b/thirdparty_builtin/benchmark-1.8.0/docs/_config.yml new file mode 100644 index 000000000..fff4ab923 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-minimal diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/dependencies.md b/thirdparty_builtin/benchmark-1.8.0/docs/dependencies.md new file mode 100644 index 000000000..07760e10e --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/dependencies.md @@ -0,0 +1,13 @@ +# Build tool dependency policy + +We follow the [Foundational C++ support policy](https://opensource.google/documentation/policies/cplusplus-support) for our build tools. In +particular the ["Build Systems" section](https://opensource.google/documentation/policies/cplusplus-support#build-systems). + +## CMake + +The current supported version is CMake 3.10 as of 2023-08-10. Most modern +distributions include newer versions, for example: + +* Ubuntu 20.04 provides CMake 3.16.3 +* Debian 11.4 provides CMake 3.18.4 +* Ubuntu 22.04 provides CMake 3.22.1 diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/index.md b/thirdparty_builtin/benchmark-1.8.0/docs/index.md new file mode 100644 index 000000000..9cada9688 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/index.md @@ -0,0 +1,12 @@ +# Benchmark + +* [Assembly Tests](AssemblyTests.md) +* [Dependencies](dependencies.md) +* [Perf Counters](perf_counters.md) +* [Platform Specific Build Instructions](platform_specific_build_instructions.md) +* [Python Bindings](python_bindings.md) +* [Random Interleaving](random_interleaving.md) +* [Reducing Variance](reducing_variance.md) +* [Releasing](releasing.md) +* [Tools](tools.md) +* [User Guide](user_guide.md) diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/perf_counters.md b/thirdparty_builtin/benchmark-1.8.0/docs/perf_counters.md new file mode 100644 index 000000000..f342092c9 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/perf_counters.md @@ -0,0 +1,35 @@ + + +# User-Requested Performance Counters + +When running benchmarks, the user may choose to request collection of +performance counters. This may be useful in investigation scenarios - narrowing +down the cause of a regression; or verifying that the underlying cause of a +performance improvement matches expectations. + +This feature is available if: + +* The benchmark is run on an architecture featuring a Performance Monitoring + Unit (PMU), +* The benchmark is compiled with support for collecting counters. Currently, + this requires [libpfm](http://perfmon2.sourceforge.net/), which is built as a + dependency via Bazel. + +The feature does not require modifying benchmark code. Counter collection is +handled at the boundaries where timer collection is also handled. + +To opt-in: +* If using a Bazel build, add `--define pfm=1` to your build flags +* If using CMake: + * Install `libpfm4-dev`, e.g. `apt-get install libpfm4-dev`. + * Enable the CMake flag `BENCHMARK_ENABLE_LIBPFM` in `CMakeLists.txt`. + +To use, pass a comma-separated list of counter names through the +`--benchmark_perf_counters` flag. The names are decoded through libpfm - meaning, +they are platform specific, but some (e.g. `CYCLES` or `INSTRUCTIONS`) are +mapped by libpfm to platform-specifics - see libpfm +[documentation](http://perfmon2.sourceforge.net/docs.html) for more details. + +The counter values are reported back through the [User Counters](../README.md#custom-counters) +mechanism, meaning, they are available in all the formats (e.g. JSON) supported +by User Counters. diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/platform_specific_build_instructions.md b/thirdparty_builtin/benchmark-1.8.0/docs/platform_specific_build_instructions.md new file mode 100644 index 000000000..2d5d6c47e --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/platform_specific_build_instructions.md @@ -0,0 +1,48 @@ +# Platform Specific Build Instructions + +## Building with GCC + +When the library is built using GCC it is necessary to link with the pthread +library due to how GCC implements `std::thread`. Failing to link to pthread will +lead to runtime exceptions (unless you're using libc++), not linker errors. See +[issue #67](https://github.com/google/benchmark/issues/67) for more details. You +can link to pthread by adding `-pthread` to your linker command. Note, you can +also use `-lpthread`, but there are potential issues with ordering of command +line parameters if you use that. + +On QNX, the pthread library is part of libc and usually included automatically +(see +[`pthread_create()`](https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.lib_ref/topic/p/pthread_create.html)). +There's no separate pthread library to link. + +## Building with Visual Studio 2015 or 2017 + +The `shlwapi` library (`-lshlwapi`) is required to support a call to `CPUInfo` which reads the registry. Either add `shlwapi.lib` under `[ Configuration Properties > Linker > Input ]`, or use the following: + +``` +// Alternatively, can add libraries using linker options. +#ifdef _WIN32 +#pragma comment ( lib, "Shlwapi.lib" ) +#ifdef _DEBUG +#pragma comment ( lib, "benchmarkd.lib" ) +#else +#pragma comment ( lib, "benchmark.lib" ) +#endif +#endif +``` + +Can also use the graphical version of CMake: +* Open `CMake GUI`. +* Under `Where to build the binaries`, same path as source plus `build`. +* Under `CMAKE_INSTALL_PREFIX`, same path as source plus `install`. +* Click `Configure`, `Generate`, `Open Project`. +* If build fails, try deleting entire directory and starting again, or unticking options to build less. + +## Building with Intel 2015 Update 1 or Intel System Studio Update 4 + +See instructions for building with Visual Studio. Once built, right click on the solution and change the build to Intel. + +## Building on Solaris + +If you're running benchmarks on solaris, you'll want the kstat library linked in +too (`-lkstat`). \ No newline at end of file diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/python_bindings.md b/thirdparty_builtin/benchmark-1.8.0/docs/python_bindings.md new file mode 100644 index 000000000..6a7aab0a2 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/python_bindings.md @@ -0,0 +1,34 @@ +# Building and installing Python bindings + +Python bindings are available as wheels on [PyPI](https://pypi.org/project/google-benchmark/) for importing and +using Google Benchmark directly in Python. +Currently, pre-built wheels exist for macOS (both ARM64 and Intel x86), Linux x86-64 and 64-bit Windows. +Supported Python versions are Python 3.7 - 3.10. + +To install Google Benchmark's Python bindings, run: + +```bash +python -m pip install --upgrade pip # for manylinux2014 support +python -m pip install google-benchmark +``` + +In order to keep your system Python interpreter clean, it is advisable to run these commands in a virtual +environment. See the [official Python documentation](https://docs.python.org/3/library/venv.html) +on how to create virtual environments. + +To build a wheel directly from source, you can follow these steps: +```bash +git clone https://github.com/google/benchmark.git +cd benchmark +# create a virtual environment and activate it +python3 -m venv venv --system-site-packages +source venv/bin/activate # .\venv\Scripts\Activate.ps1 on Windows + +# upgrade Python's system-wide packages +python -m pip install --upgrade pip setuptools wheel +# builds the wheel and stores it in the directory "wheelhouse". +python -m pip wheel . -w wheelhouse +``` + +NB: Building wheels from source requires Bazel. For platform-specific instructions on how to install Bazel, +refer to the [Bazel installation docs](https://bazel.build/install). diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/random_interleaving.md b/thirdparty_builtin/benchmark-1.8.0/docs/random_interleaving.md new file mode 100644 index 000000000..c08303684 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/random_interleaving.md @@ -0,0 +1,13 @@ + + +# Random Interleaving + +[Random Interleaving](https://github.com/google/benchmark/issues/1051) is a +technique to lower run-to-run variance. It randomly interleaves repetitions of a +microbenchmark with repetitions from other microbenchmarks in the same benchmark +test. Data shows it is able to lower run-to-run variance by +[40%](https://github.com/google/benchmark/issues/1051) on average. + +To use, you mainly need to set `--benchmark_enable_random_interleaving=true`, +and optionally specify non-zero repetition count `--benchmark_repetitions=9` +and optionally decrease the per-repetition time `--benchmark_min_time=0.1`. diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/reducing_variance.md b/thirdparty_builtin/benchmark-1.8.0/docs/reducing_variance.md new file mode 100644 index 000000000..e566ab985 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/reducing_variance.md @@ -0,0 +1,100 @@ +# Reducing Variance + + + +## Disabling CPU Frequency Scaling + +If you see this error: + +``` +***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead. +``` + +you might want to disable the CPU frequency scaling while running the +benchmark, as well as consider other ways to stabilize the performance of +your system while benchmarking. + +See [Reducing Variance](reducing_variance.md) for more information. + +Exactly how to do this depends on the Linux distribution, +desktop environment, and installed programs. Specific details are a moving +target, so we will not attempt to exhaustively document them here. + +One simple option is to use the `cpupower` program to change the +performance governor to "performance". This tool is maintained along with +the Linux kernel and provided by your distribution. + +It must be run as root, like this: + +```bash +sudo cpupower frequency-set --governor performance +``` + +After this you can verify that all CPUs are using the performance governor +by running this command: + +```bash +cpupower frequency-info -o proc +``` + +The benchmarks you subsequently run will have less variance. + + + +## Reducing Variance in Benchmarks + +The Linux CPU frequency governor [discussed +above](user_guide#disabling-cpu-frequency-scaling) is not the only source +of noise in benchmarks. Some, but not all, of the sources of variance +include: + +1. On multi-core machines not all CPUs/CPU cores/CPU threads run the same + speed, so running a benchmark one time and then again may give a + different result depending on which CPU it ran on. +2. CPU scaling features that run on the CPU, like Intel's Turbo Boost and + AMD Turbo Core and Precision Boost, can temporarily change the CPU + frequency even when the using the "performance" governor on Linux. +3. Context switching between CPUs, or scheduling competition on the CPU the + benchmark is running on. +4. Intel Hyperthreading or AMD SMT causing the same issue as above. +5. Cache effects caused by code running on other CPUs. +6. Non-uniform memory architectures (NUMA). + +These can cause variance in benchmarks results within a single run +(`--benchmark_repetitions=N`) or across multiple runs of the benchmark +program. + +Reducing sources of variance is OS and architecture dependent, which is one +reason some companies maintain machines dedicated to performance testing. + +Some of the easier and and effective ways of reducing variance on a typical +Linux workstation are: + +1. Use the performance governor as [discussed +above](user_guide#disabling-cpu-frequency-scaling). +1. Disable processor boosting by: + ```sh + echo 0 | sudo tee /sys/devices/system/cpu/cpufreq/boost + ``` + See the Linux kernel's + [boost.txt](https://www.kernel.org/doc/Documentation/cpu-freq/boost.txt) + for more information. +2. Set the benchmark program's task affinity to a fixed cpu. For example: + ```sh + taskset -c 0 ./mybenchmark + ``` +3. Disabling Hyperthreading/SMT. This can be done in the Bios or using the + `/sys` file system (see the LLVM project's [Benchmarking + tips](https://llvm.org/docs/Benchmarking.html)). +4. Close other programs that do non-trivial things based on timers, such as + your web browser, desktop environment, etc. +5. Reduce the working set of your benchmark to fit within the L1 cache, but + do be aware that this may lead you to optimize for an unrelistic + situation. + +Further resources on this topic: + +1. The LLVM project's [Benchmarking + tips](https://llvm.org/docs/Benchmarking.html). +1. The Arch Wiki [Cpu frequency +scaling](https://wiki.archlinux.org/title/CPU_frequency_scaling) page. diff --git a/thirdparty_builtin/benchmark-1.8.0/docs/releasing.md b/thirdparty_builtin/benchmark-1.8.0/docs/releasing.md new file mode 100644 index 000000000..6d3b6138c --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/docs/releasing.md @@ -0,0 +1,37 @@ +# How to release + +* Make sure you're on main and synced to HEAD +* Ensure the project builds and tests run + * `parallel -j0 exec ::: test/*_test` can help ensure everything at least + passes +* Prepare release notes + * `git log $(git describe --abbrev=0 --tags)..HEAD` gives you the list of + commits between the last annotated tag and HEAD + * Pick the most interesting. +* Create one last commit that updates the version saved in `CMakeLists.txt` and the + `__version__` variable in `bindings/python/google_benchmark/__init__.py`to the release + version you're creating. (This version will be used if benchmark is installed from the + archive you'll be creating in the next step.) + +``` +project (benchmark VERSION 1.6.0 LANGUAGES CXX) +``` + +```python +# bindings/python/google_benchmark/__init__.py + +# ... + +__version__ = "1.6.0" # <-- change this to the release version you are creating + +# ... +``` + +* Create a release through github's interface + * Note this will create a lightweight tag. + * Update this to an annotated tag: + * `git pull --tags` + * `git tag -a -f ` + * `git push --force --tags origin` +* Confirm that the "Build and upload Python wheels" action runs to completion + * run it manually if it hasn't run diff --git a/thirdparty_builtin/benchmark-1.5.0/docs/tools.md b/thirdparty_builtin/benchmark-1.8.0/docs/tools.md similarity index 98% rename from thirdparty_builtin/benchmark-1.5.0/docs/tools.md rename to thirdparty_builtin/benchmark-1.8.0/docs/tools.md index 4a3b2e9bd..f2d0c497f 100644 --- a/thirdparty_builtin/benchmark-1.5.0/docs/tools.md +++ b/thirdparty_builtin/benchmark-1.8.0/docs/tools.md @@ -4,7 +4,11 @@ The `compare.py` can be used to compare the result of benchmarks. -**NOTE**: the utility relies on the scipy package which can be installed using [these instructions](https://www.scipy.org/install.html). +### Dependencies +The utility relies on the [scipy](https://www.scipy.org) package which can be installed using pip: +```bash +pip3 install -r requirements.txt +``` ### Displaying aggregates only diff --git a/thirdparty_builtin/benchmark-1.5.0/README.md b/thirdparty_builtin/benchmark-1.8.0/docs/user_guide.md similarity index 70% rename from thirdparty_builtin/benchmark-1.5.0/README.md rename to thirdparty_builtin/benchmark-1.8.0/docs/user_guide.md index 45e415884..133fca5b6 100644 --- a/thirdparty_builtin/benchmark-1.5.0/README.md +++ b/thirdparty_builtin/benchmark-1.8.0/docs/user_guide.md @@ -1,224 +1,29 @@ -# Benchmark -[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=master)](https://travis-ci.org/google/benchmark) -[![Build status](https://ci.appveyor.com/api/projects/status/u0qsyp7t1tk7cpxs/branch/master?svg=true)](https://ci.appveyor.com/project/google/benchmark/branch/master) -[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark) -[![slackin](https://slackin-iqtfqnpzxd.now.sh/badge.svg)](https://slackin-iqtfqnpzxd.now.sh/) +# User Guide +## Command Line -A library to benchmark code snippets, similar to unit tests. Example: - -```c++ -#include - -static void BM_SomeFunction(benchmark::State& state) { - // Perform setup here - for (auto _ : state) { - // This code gets timed - SomeFunction(); - } -} -// Register the function as a benchmark -BENCHMARK(BM_SomeFunction); -// Run the benchmark -BENCHMARK_MAIN(); -``` - -To get started, see [Requirements](#requirements) and -[Installation](#installation). See [Usage](#usage) for a full example and the -[User Guide](#user-guide) for a more comprehensive feature overview. - -It may also help to read the [Google Test documentation](https://github.com/google/googletest/blob/master/googletest/docs/primer.md) -as some of the structural aspects of the APIs are similar. - -### Resources - -[Discussion group](https://groups.google.com/d/forum/benchmark-discuss) - -IRC channel: [freenode](https://freenode.net) #googlebenchmark - -[Additional Tooling Documentation](docs/tools.md) - -[Assembly Testing Documentation](docs/AssemblyTests.md) - -## Requirements - -The library can be used with C++03. However, it requires C++11 to build, -including compiler and standard library support. - -The following minimum versions are required to build the library: - -* GCC 4.8 -* Clang 3.4 -* Visual Studio 2013 -* Intel 2015 Update 1 - -## Installation - -This describes the installation process using cmake. As pre-requisites, you'll -need git and cmake installed. - -_See [dependencies.md](dependencies.md) for more details regarding supported -versions of build tools._ - -```bash -# Check out the library. -$ git clone https://github.com/google/benchmark.git -# Benchmark requires Google Test as a dependency. Add the source tree as a subdirectory. -$ git clone https://github.com/google/googletest.git benchmark/googletest -# Make a build directory to place the build output. -$ mkdir build && cd build -# Generate a Makefile with cmake. -# Use cmake -G to generate a different file type. -$ cmake ../benchmark -# Build the library. -$ make -``` -This builds the `benchmark` and `benchmark_main` libraries and tests. -On a unix system, the build directory should now look something like this: - -``` -/benchmark -/build - /src - /libbenchmark.a - /libbenchmark_main.a - /test - ... -``` - -Next, you can run the tests to check the build. - -```bash -$ make test -``` - -If you want to install the library globally, also run: - -``` -sudo make install -``` - -Note that Google Benchmark requires Google Test to build and run the tests. This -dependency can be provided two ways: - -* Checkout the Google Test sources into `benchmark/googletest` as above. -* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during - configuration, the library will automatically download and build any required - dependencies. - -If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF` -to `CMAKE_ARGS`. - -### Debug vs Release - -By default, benchmark builds as a debug library. You will see a warning in the -output when this is the case. To build it as a release library instead, use: - -``` -cmake -DCMAKE_BUILD_TYPE=Release -``` - -To enable link-time optimisation, use - -``` -cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true -``` - -If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake -cache variables, if autodetection fails. - -If you are using clang, you may need to set `LLVMAR_EXECUTABLE`, -`LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables. - - -### Stable and Experimental Library Versions - -The main branch contains the latest stable version of the benchmarking library; -the API of which can be considered largely stable, with source breaking changes -being made only upon the release of a new major version. - -Newer, experimental, features are implemented and tested on the -[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish -to use, test, and provide feedback on the new features are encouraged to try -this branch. However, this branch provides no stability guarantees and reserves -the right to change and break the API at any time. - -## Usage -### Basic usage -Define a function that executes the code to measure, register it as a benchmark -function using the `BENCHMARK` macro, and ensure an appropriate `main` function -is available: - -```c++ -#include - -static void BM_StringCreation(benchmark::State& state) { - for (auto _ : state) - std::string empty_string; -} -// Register the function as a benchmark -BENCHMARK(BM_StringCreation); - -// Define another benchmark -static void BM_StringCopy(benchmark::State& state) { - std::string x = "hello"; - for (auto _ : state) - std::string copy(x); -} -BENCHMARK(BM_StringCopy); - -BENCHMARK_MAIN(); -``` - -To run the benchmark, compile and link against the `benchmark` library -(libbenchmark.a/.so). If you followed the build steps above, this -library will be under the build directory you created. - -```bash -# Example on linux after running the build steps above. Assumes the -# `benchmark` and `build` directories are under the current directory. -$ g++ -std=c++11 -isystem benchmark/include -Lbuild/src -lpthread \ - -lbenchmark mybenchmark.cc -o mybenchmark -``` - -Alternatively, link against the `benchmark_main` library and remove -`BENCHMARK_MAIN();` above to get the same behavior. - -The compiled executable will run all benchmarks by default. Pass the `--help` -flag for option information or see the guide below. - -### Platform-specific instructions - -When the library is built using GCC it is necessary to link with the pthread -library due to how GCC implements `std::thread`. Failing to link to pthread will -lead to runtime exceptions (unless you're using libc++), not linker errors. See -[issue #67](https://github.com/google/benchmark/issues/67) for more details. You -can link to pthread by adding `-pthread` to your linker command. Note, you can -also use `-lpthread`, but there are potential issues with ordering of command -line parameters if you use that. - -If you're running benchmarks on Windows, the shlwapi library (`-lshlwapi`) is -also required. - -If you're running benchmarks on solaris, you'll want the kstat library linked in -too (`-lkstat`). - -## User Guide - -### Command Line [Output Formats](#output-formats) [Output Files](#output-files) +[Running Benchmarks](#running-benchmarks) + [Running a Subset of Benchmarks](#running-a-subset-of-benchmarks) [Result Comparison](#result-comparison) -### Library +[Extra Context](#extra-context) + +## Library + [Runtime and Reporting Considerations](#runtime-and-reporting-considerations) +[Setup/Teardown](#setupteardown) + [Passing Arguments](#passing-arguments) +[Custom Benchmark Name](#custom-benchmark-name) + [Calculating Asymptotic Complexity](#asymptotic-complexity) [Templated Benchmarks](#templated-benchmarks) @@ -235,31 +40,43 @@ too (`-lkstat`). [Setting the Time Unit](#setting-the-time-unit) +[Random Interleaving](random_interleaving.md) + +[User-Requested Performance Counters](perf_counters.md) + [Preventing Optimization](#preventing-optimization) [Reporting Statistics](#reporting-statistics) [Custom Statistics](#custom-statistics) +[Memory Usage](#memory-usage) + [Using RegisterBenchmark](#using-register-benchmark) [Exiting with an Error](#exiting-with-an-error) -[A Faster KeepRunning Loop](#a-faster-keep-running-loop) +[A Faster `KeepRunning` Loop](#a-faster-keep-running-loop) + +## Benchmarking Tips [Disabling CPU Frequency Scaling](#disabling-cpu-frequency-scaling) +[Reducing Variance in Benchmarks](reducing_variance.md) + -### Output Formats +## Output Formats The library supports multiple output formats. Use the -`--benchmark_format=` flag to set the format type. `console` -is the default format. +`--benchmark_format=` flag (or set the +`BENCHMARK_FORMAT=` environment variable) to set +the format type. `console` is the default format. The Console format is intended to be a human readable format. By default the format generates color output. Context is output on stderr and the tabular data on stdout. Example tabular output looks like: + ``` Benchmark Time(ns) CPU(ns) Iterations ---------------------------------------------------------------------- @@ -273,6 +90,7 @@ The `context` attribute contains information about the run in general, including information about the CPU and the date. The `benchmarks` attribute contains a list of every benchmark run. Example json output looks like: + ```json { "context": { @@ -313,6 +131,7 @@ output looks like: The CSV format outputs comma-separated values. The `context` is output on stderr and the CSV itself on stdout. Example CSV output looks like: + ``` name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label "BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942, @@ -322,18 +141,37 @@ name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label -### Output Files +## Output Files + +Write benchmark results to a file with the `--benchmark_out=` option +(or set `BENCHMARK_OUT`). Specify the output format with +`--benchmark_out_format={json|console|csv}` (or set +`BENCHMARK_OUT_FORMAT={json|console|csv}`). Note that the 'csv' reporter is +deprecated and the saved `.csv` file +[is not parsable](https://github.com/google/benchmark/issues/794) by csv +parsers. + +Specifying `--benchmark_out` does not suppress the console output. -Write benchmark results to a file with the `--benchmark_out=` option. -Specify the output format with `--benchmark_out_format={json|console|csv}`. Note that Specifying -`--benchmark_out` does not suppress the console output. + + +## Running Benchmarks + +Benchmarks are executed by running the produced binaries. Benchmarks binaries, +by default, accept options that may be specified either through their command +line interface or by setting environment variables before execution. For every +`--option_flag=` CLI switch, a corresponding environment variable +`OPTION_FLAG=` exist and is used as default if set (CLI switches always + prevails). A complete list of CLI options is available running benchmarks + with the `--help` switch. -### Running a Subset of Benchmarks +## Running a Subset of Benchmarks -The `--benchmark_filter=` option can be used to only run the benchmarks -which match the specified ``. For example: +The `--benchmark_filter=` option (or `BENCHMARK_FILTER=` +environment variable) can be used to only run the benchmarks that match +the specified ``. For example: ```bash $ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32 @@ -347,15 +185,50 @@ BM_memcpy/32 12 ns 12 ns 54687500 BM_memcpy/32k 1834 ns 1837 ns 357143 ``` +## Disabling Benchmarks + +It is possible to temporarily disable benchmarks by renaming the benchmark +function to have the prefix "DISABLED_". This will cause the benchmark to +be skipped at runtime. + -### Result comparison +## Result comparison + +It is possible to compare the benchmarking results. +See [Additional Tooling Documentation](tools.md) + + + +## Extra Context + +Sometimes it's useful to add extra context to the content printed before the +results. By default this section includes information about the CPU on which +the benchmarks are running. If you do want to add more context, you can use +the `benchmark_context` command line flag: + +```bash +$ ./run_benchmarks --benchmark_context=pwd=`pwd` +Run on (1 x 2300 MHz CPU) +pwd: /home/user/benchmark/ +Benchmark Time CPU Iterations +---------------------------------------------------- +BM_memcpy/32 11 ns 11 ns 79545455 +BM_memcpy/32k 2181 ns 2185 ns 324074 +``` -It is possible to compare the benchmarking results. See [Additional Tooling Documentation](docs/tools.md) +You can get the same effect with the API: + +```c++ + benchmark::AddCustomContext("foo", "bar"); +``` + +Note that attempts to add a second value with the same key will fail with an +error message. -### Runtime and Reporting Considerations +## Runtime and Reporting Considerations When the benchmark binary is executed, each benchmark function is run serially. The number of iterations to run is determined dynamically by running the @@ -370,6 +243,19 @@ iterations is at least one, not more than 1e9, until CPU time is greater than the minimum time, or the wallclock time is 5x minimum time. The minimum time is set per benchmark by calling `MinTime` on the registered benchmark object. +Furthermore warming up a benchmark might be necessary in order to get +stable results because of e.g caching effects of the code under benchmark. +Warming up means running the benchmark a given amount of time, before +results are actually taken into account. The amount of time for which +the warmup should be run can be set per benchmark by calling +`MinWarmUpTime` on the registered benchmark object or for all benchmarks +using the `--benchmark_min_warmup_time` command-line option. Note that +`MinWarmUpTime` will overwrite the value of `--benchmark_min_warmup_time` +for the single benchmark. How many iterations the warmup run of each +benchmark takes is determined the same way as described in the paragraph +above. Per default the warmup phase is set to 0 seconds and is therefore +disabled. + Average timings are then reported over the iterations run. If multiple repetitions are requested using the `--benchmark_repetitions` command-line option, or at registration time, the benchmark function will be run several @@ -378,9 +264,43 @@ times and statistical results across these repetitions will also be reported. As well as the per-benchmark entries, a preamble in the report will include information about the machine on which the benchmarks are run. + + +## Setup/Teardown + +Global setup/teardown specific to each benchmark can be done by +passing a callback to Setup/Teardown: + +The setup/teardown callbacks will be invoked once for each benchmark. If the +benchmark is multi-threaded (will run in k threads), they will be invoked +exactly once before each run with k threads. + +If the benchmark uses different size groups of threads, the above will be true +for each size group. + +Eg., + +```c++ +static void DoSetup(const benchmark::State& state) { +} + +static void DoTeardown(const benchmark::State& state) { +} + +static void BM_func(benchmark::State& state) {...} + +BENCHMARK(BM_func)->Arg(1)->Arg(3)->Threads(16)->Threads(32)->Setup(DoSetup)->Teardown(DoTeardown); + +``` + +In this example, `DoSetup` and `DoTearDown` will be invoked 4 times each, +specifically, once for each of this family: + - BM_func_Arg_1_Threads_16, BM_func_Arg_1_Threads_32 + - BM_func_Arg_3_Threads_16, BM_func_Arg_3_Threads_32 + -### Passing Arguments +## Passing Arguments Sometimes a family of benchmarks can be implemented with just one routine that takes an extra argument to specify which one of the family of benchmarks to @@ -399,7 +319,7 @@ static void BM_memcpy(benchmark::State& state) { delete[] src; delete[] dst; } -BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10); +BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(4<<10)->Arg(8<<10); ``` The preceding code is quite repetitive, and can be replaced with the following @@ -417,8 +337,27 @@ range multiplier is changed to multiples of two. ```c++ BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10); ``` + Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ]. +The preceding code shows a method of defining a sparse range. The following +example shows a method of defining a dense range. It is then used to benchmark +the performance of `std::vector` initialization for uniformly increasing sizes. + +```c++ +static void BM_DenseRange(benchmark::State& state) { + for(auto _ : state) { + std::vector v(state.range(0), state.range(0)); + auto data = v.data(); + benchmark::DoNotOptimize(data); + benchmark::ClobberMemory(); + } +} +BENCHMARK(BM_DenseRange)->DenseRange(0, 1024, 128); +``` + +Now arguments generated are [ 0, 128, 256, 384, 512, 640, 768, 896, 1024 ]. + You might have a benchmark that depends on two or more inputs. For example, the following code defines a family of benchmarks for measuring the speed of set insertion. @@ -450,9 +389,53 @@ short-hand. The following macro will pick a few appropriate arguments in the product of the two specified ranges and will generate a benchmark for each such pair. + ```c++ BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}}); ``` + + +Some benchmarks may require specific argument values that cannot be expressed +with `Ranges`. In this case, `ArgsProduct` offers the ability to generate a +benchmark input for each combination in the product of the supplied vectors. + + +```c++ +BENCHMARK(BM_SetInsert) + ->ArgsProduct({{1<<10, 3<<10, 8<<10}, {20, 40, 60, 80}}) +// would generate the same benchmark arguments as +BENCHMARK(BM_SetInsert) + ->Args({1<<10, 20}) + ->Args({3<<10, 20}) + ->Args({8<<10, 20}) + ->Args({3<<10, 40}) + ->Args({8<<10, 40}) + ->Args({1<<10, 40}) + ->Args({1<<10, 60}) + ->Args({3<<10, 60}) + ->Args({8<<10, 60}) + ->Args({1<<10, 80}) + ->Args({3<<10, 80}) + ->Args({8<<10, 80}); +``` + + +For the most common scenarios, helper methods for creating a list of +integers for a given sparse or dense range are provided. + +```c++ +BENCHMARK(BM_SetInsert) + ->ArgsProduct({ + benchmark::CreateRange(8, 128, /*multi=*/2), + benchmark::CreateDenseRange(1, 4, /*step=*/1) + }) +// would generate the same benchmark arguments as +BENCHMARK(BM_SetInsert) + ->ArgsProduct({ + {8, 16, 32, 64, 128}, + {1, 2, 3, 4} + }); +``` For more complex patterns of inputs, passing a custom function to `Apply` allows programmatic specification of an arbitrary set of arguments on which to run the @@ -468,7 +451,7 @@ static void CustomArguments(benchmark::internal::Benchmark* b) { BENCHMARK(BM_SetInsert)->Apply(CustomArguments); ``` -#### Passing Arbitrary Arguments to a Benchmark +### Passing Arbitrary Arguments to a Benchmark In C++11 it is possible to define a benchmark that takes an arbitrary number of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)` @@ -478,20 +461,30 @@ The `test_case_name` is appended to the name of the benchmark and should describe the values passed. ```c++ -template -void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { - [...] +template +void BM_takes_args(benchmark::State& state, Args&&... args) { + auto args_tuple = std::make_tuple(std::move(args)...); + for (auto _ : state) { + std::cout << std::get<0>(args_tuple) << ": " << std::get<1>(args_tuple) + << '\n'; + [...] + } } // Registers a benchmark named "BM_takes_args/int_string_test" that passes -// the specified values to `extra_args`. +// the specified values to `args`. BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc")); + +// Registers the same benchmark "BM_takes_args/int_test" that passes +// the specified values to `args`. +BENCHMARK_CAPTURE(BM_takes_args, int_test, 42, 43); ``` + Note that elements of `...args` may refer to global variables. Users should avoid modifying global state inside of a benchmark. -### Calculating Asymptotic Complexity (Big O) +## Calculating Asymptotic Complexity (Big O) Asymptotic complexity might be calculated for a family of benchmarks. The following code will calculate the coefficient for the high-order term in the @@ -502,7 +495,8 @@ static void BM_StringCompare(benchmark::State& state) { std::string s1(state.range(0), '-'); std::string s2(state.range(0), '-'); for (auto _ : state) { - benchmark::DoNotOptimize(s1.compare(s2)); + auto comparison_result = s1.compare(s2); + benchmark::DoNotOptimize(comparison_result); } state.SetComplexityN(state.range(0)); } @@ -523,12 +517,25 @@ that might be used to customize high-order term calculation. ```c++ BENCHMARK(BM_StringCompare)->RangeMultiplier(2) - ->Range(1<<10, 1<<18)->Complexity([](int64_t n)->double{return n; }); + ->Range(1<<10, 1<<18)->Complexity([](benchmark::IterationCount n)->double{return n; }); +``` + + + +## Custom Benchmark Name + +You can change the benchmark's name as follows: + +```c++ +BENCHMARK(BM_memcpy)->Name("memcpy")->RangeMultiplier(2)->Range(8, 8<<10); ``` +The invocation will execute the benchmark as before using `BM_memcpy` but changes +the prefix in the report to `memcpy`. + -### Templated Benchmarks +## Templated Benchmarks This example produces and consumes messages of size `sizeof(v)` `range_x` times. It also outputs throughput in the absence of multiprogramming. @@ -547,14 +554,19 @@ template void BM_Sequential(benchmark::State& state) { state.SetBytesProcessed( static_cast(state.iterations())*state.range(0)); } +// C++03 BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue)->Range(1<<0, 1<<10); + +// C++11 or newer, you can use the BENCHMARK macro with template parameters: +BENCHMARK(BM_Sequential>)->Range(1<<0, 1<<10); + ``` Three macros are provided for adding benchmark templates. ```c++ #ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters. +#define BENCHMARK(func<...>) // Takes any number of parameters. #else // C++ < C++11 #define BENCHMARK_TEMPLATE(func, arg1) #endif @@ -564,7 +576,7 @@ Three macros are provided for adding benchmark templates. -### Fixtures +## Fixtures Fixture tests are created by first defining a type that derives from `::benchmark::Fixture` and then creating/registering the tests using the @@ -602,7 +614,7 @@ BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2); /* BarTest is now registered */ ``` -#### Templated Fixtures +### Templated Fixtures Also you can create templated fixture by using the following macros: @@ -610,6 +622,7 @@ Also you can create templated fixture by using the following macros: * `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)` For example: + ```c++ template class MyFixture : public benchmark::Fixture {}; @@ -631,7 +644,7 @@ BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2); -### Custom Counters +## Custom Counters You can add your own counters with user-defined names. The example below will add columns "Foo", "Bar" and "Baz" in its output: @@ -659,9 +672,9 @@ the resulting sum is the value which will be shown for the benchmark. The `Counter` constructor accepts three parameters: the value as a `double` ; a bit flag which allows you to show counters as rates, and/or as per-thread -iteration, and/or as per-thread averages, and/or iteration invariants; -and a flag specifying the 'unit' - i.e. is 1k a 1000 (default, -`benchmark::Counter::OneK::kIs1000`), or 1024 +iteration, and/or as per-thread averages, and/or iteration invariants, +and/or finally inverting the result; and a flag specifying the 'unit' - i.e. +is 1k a 1000 (default, `benchmark::Counter::OneK::kIs1000`), or 1024 (`benchmark::Counter::OneK::kIs1024`)? ```c++ @@ -670,8 +683,14 @@ and a flag specifying the 'unit' - i.e. is 1k a 1000 (default, // Set the counter as a rate. It will be presented divided // by the duration of the benchmark. + // Meaning: per one second, how many 'foo's are processed? state.counters["FooRate"] = Counter(numFoos, benchmark::Counter::kIsRate); + // Set the counter as a rate. It will be presented divided + // by the duration of the benchmark, and the result inverted. + // Meaning: how many seconds it takes to process one 'foo'? + state.counters["FooInvRate"] = Counter(numFoos, benchmark::Counter::kIsRate | benchmark::Counter::kInvert); + // Set the counter as a thread-average quantity. It will // be presented divided by the number of threads. state.counters["FooAvg"] = Counter(numFoos, benchmark::Counter::kAvgThreads); @@ -686,6 +705,7 @@ and a flag specifying the 'unit' - i.e. is 1k a 1000 (default, When you're compiling in C++11 mode or later you can use `insert()` with `std::initializer_list`: + ```c++ // With C++11, this can be done: state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}}); @@ -694,10 +714,11 @@ When you're compiling in C++11 mode or later you can use `insert()` with state.counters["Bar"] = numBars; state.counters["Baz"] = numBazs; ``` + -#### Counter Reporting +### Counter Reporting -When using the console reporter, by default, user counters are are printed at +When using the console reporter, by default, user counters are printed at the end after the table, the same way as ``bytes_processed`` and ``items_processed``. This is best for cases in which there are few counters, or where there are only a couple of lines per benchmark. Here's an example of @@ -758,13 +779,14 @@ BM_CalculatePiRange/256k 2434095 ns 2434186 ns 288 3.1416 BM_CalculatePiRange/1024k 9721140 ns 9721413 ns 71 3.14159 BM_CalculatePi/threads:8 2255 ns 9943 ns 70936 ``` + Note above the additional header printed when the benchmark changes from ``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does not have the same counter set as ``BM_UserCounter``. -### Multithreaded Benchmarks +## Multithreaded Benchmarks In a multithreaded test (benchmark invoked by multiple threads simultaneously), it is guaranteed that none of the threads will start until all have reached @@ -775,19 +797,29 @@ index: ```c++ static void BM_MultiThreaded(benchmark::State& state) { - if (state.thread_index == 0) { + if (state.thread_index() == 0) { // Setup code here. } for (auto _ : state) { // Run the test as normal. } - if (state.thread_index == 0) { + if (state.thread_index() == 0) { // Teardown code here. } } BENCHMARK(BM_MultiThreaded)->Threads(2); ``` +To run the benchmark across a range of thread counts, instead of `Threads`, use +`ThreadRange`. This takes two parameters (`min_threads` and `max_threads`) and +runs the benchmark once for values in the inclusive range. For example: + +```c++ +BENCHMARK(BM_MultiThreaded)->ThreadRange(1, 8); +``` + +will run `BM_MultiThreaded` with thread counts 1, 2, 4, and 8. + If the benchmarked code itself uses threads and you want to compare it to single-threaded code, you may want to use real-time ("wallclock") measurements for latency comparisons: @@ -800,7 +832,7 @@ Without `UseRealTime`, CPU time is used by default. -### CPU Timers +## CPU Timers By default, the CPU timer only measures the time spent by the main thread. If the benchmark itself uses threads internally, this measurement may not @@ -818,7 +850,7 @@ static void MyMain(int size) { static void BM_OpenMP(benchmark::State& state) { for (auto _ : state) - MyMain(state.range(0); + MyMain(state.range(0)); } // Measure the time spent by the main thread, use it to decide for how long to @@ -844,13 +876,14 @@ BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime(); BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime()->UseRealTime(); ``` -#### Controlling Timers +### Controlling Timers Normally, the entire duration of the work loop (`for (auto _ : state) {}`) is measured. But sometimes, it is necessary to do some work inside of that loop, every iteration, but without counting that time to the benchmark time. -That is possible, althought it is not recommended, since it has high overhead. +That is possible, although it is not recommended, since it has high overhead. + ```c++ static void BM_SetInsert_With_Timer_Control(benchmark::State& state) { std::set data; @@ -865,10 +898,11 @@ static void BM_SetInsert_With_Timer_Control(benchmark::State& state) { } BENCHMARK(BM_SetInsert_With_Timer_Control)->Ranges({{1<<10, 8<<10}, {128, 512}}); ``` + -### Manual Timing +## Manual Timing For benchmarking something for which neither CPU time nor real-time are correct or accurate enough, completely manual timing is supported using @@ -895,7 +929,7 @@ static void BM_ManualTiming(benchmark::State& state) { auto start = std::chrono::high_resolution_clock::now(); // Simulate some useful workload with a sleep std::this_thread::sleep_for(sleep_duration); - auto end = std::chrono::high_resolution_clock::now(); + auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast>( @@ -909,7 +943,7 @@ BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime(); -### Setting the Time Unit +## Setting the Time Unit If a benchmark runs a few milliseconds it may be hard to visually compare the measured times, since the output data is given in nanoseconds per default. In @@ -919,9 +953,13 @@ order to manually set the time unit, you can specify it manually: BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); ``` +Additionally the default time unit can be set globally with the +`--benchmark_time_unit={ns|us|ms|s}` command line argument. The argument only +affects benchmarks where the time unit is not set explicitly. + -### Preventing Optimization +## Preventing Optimization To prevent a value or expression from being optimized away by the compiler the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()` @@ -971,7 +1009,8 @@ static void BM_vector_push_back(benchmark::State& state) { for (auto _ : state) { std::vector v; v.reserve(1); - benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered. + auto data = v.data(); // Allow v.data() to be clobbered. Pass as non-const + benchmark::DoNotOptimize(data); // lvalue to avoid undesired compiler optimizations v.push_back(42); benchmark::ClobberMemory(); // Force 42 to be written to memory. } @@ -982,7 +1021,7 @@ Note that `ClobberMemory()` is only available for GNU or MSVC based compilers. -### Statistics: Reporting the Mean, Median and Standard Deviation of Repeated Benchmarks +## Statistics: Reporting the Mean, Median and Standard Deviation / Coefficient of variation of Repeated Benchmarks By default each benchmark is run once and that single result is reported. However benchmarks are often noisy and a single result may not be representative @@ -992,16 +1031,17 @@ benchmark. The number of runs of each benchmark is specified globally by the `--benchmark_repetitions` flag or on a per benchmark basis by calling `Repetitions` on the registered benchmark object. When a benchmark is run more -than once the mean, median and standard deviation of the runs will be reported. +than once the mean, median, standard deviation and coefficient of variation +of the runs will be reported. Additionally the `--benchmark_report_aggregates_only={true|false}`, `--benchmark_display_aggregates_only={true|false}` flags or `ReportAggregatesOnly(bool)`, `DisplayAggregatesOnly(bool)` functions can be used to change how repeated tests are reported. By default the result of each repeated run is reported. When `report aggregates only` option is `true`, -only the aggregates (i.e. mean, median and standard deviation, maybe complexity -measurements if they were requested) of the runs is reported, to both the -reporters - standard output (console), and the file. +only the aggregates (i.e. mean, median, standard deviation and coefficient +of variation, maybe complexity measurements if they were requested) of the runs +is reported, to both the reporters - standard output (console), and the file. However when only the `display aggregates only` option is `true`, only the aggregates are displayed in the standard output, while the file output still contains everything. @@ -1011,13 +1051,12 @@ benchmark. -### Custom Statistics +## Custom Statistics -While having mean, median and standard deviation is nice, this may not be -enough for everyone. For example you may want to know what the largest -observation is, e.g. because you have some real-time constraints. This is easy. -The following code will specify a custom statistic to be calculated, defined -by a lambda function. +While having these aggregates is nice, this may not be enough for everyone. +For example you may want to know what the largest observation is, e.g. because +you have some real-time constraints. This is easy. The following code will +specify a custom statistic to be calculated, defined by a lambda function. ```c++ void BM_spin_empty(benchmark::State& state) { @@ -1035,9 +1074,43 @@ BENCHMARK(BM_spin_empty) ->Arg(512); ``` +While usually the statistics produce values in time units, +you can also produce percentages: + +```c++ +void BM_spin_empty(benchmark::State& state) { + for (auto _ : state) { + for (int x = 0; x < state.range(0); ++x) { + benchmark::DoNotOptimize(x); + } + } +} + +BENCHMARK(BM_spin_empty) + ->ComputeStatistics("ratio", [](const std::vector& v) -> double { + return std::begin(v) / std::end(v); + }, benchmark::StatisticUnit::kPercentage) + ->Arg(512); +``` + + + +## Memory Usage + +It's often useful to also track memory usage for benchmarks, alongside CPU +performance. For this reason, benchmark offers the `RegisterMemoryManager` +method that allows a custom `MemoryManager` to be injected. + +If set, the `MemoryManager::Start` and `MemoryManager::Stop` methods will be +called at the start and end of benchmark runs to allow user code to fill out +a report on the number of allocations, bytes used, etc. + +This data will then be reported alongside other performance data, currently +only when using JSON output. + -### Using RegisterBenchmark(name, fn, args...) +## Using RegisterBenchmark(name, fn, args...) The `RegisterBenchmark(name, func, args...)` function provides an alternative way to create and register benchmarks. @@ -1061,23 +1134,26 @@ int main(int argc, char** argv) { benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input); benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); + benchmark::Shutdown(); } ``` -### Exiting with an Error +## Exiting with an Error When errors caused by external influences, such as file I/O and network communication, occur within a benchmark the -`State::SkipWithError(const char* msg)` function can be used to skip that run +`State::SkipWithError(const std::string& msg)` function can be used to skip that run of benchmark and report the error. Note that only future iterations of the `KeepRunning()` are skipped. For the ranged-for version of the benchmark loop Users must explicitly exit the loop, otherwise all iterations will be performed. Users may explicitly return to exit the benchmark immediately. The `SkipWithError(...)` function may be used at any point within the benchmark, -including before and after the benchmark loop. +including before and after the benchmark loop. Moreover, if `SkipWithError(...)` +has been used, it is not required to reach the benchmark loop and one may return +from the benchmark function early. For example: @@ -1085,30 +1161,38 @@ For example: static void BM_test(benchmark::State& state) { auto resource = GetResource(); if (!resource.good()) { - state.SkipWithError("Resource is not good!"); - // KeepRunning() loop will not be entered. + state.SkipWithError("Resource is not good!"); + // KeepRunning() loop will not be entered. } - for (state.KeepRunning()) { - auto data = resource.read_data(); - if (!resource.good()) { - state.SkipWithError("Failed to read data!"); - break; // Needed to skip the rest of the iteration. - } - do_stuff(data); + while (state.KeepRunning()) { + auto data = resource.read_data(); + if (!resource.good()) { + state.SkipWithError("Failed to read data!"); + break; // Needed to skip the rest of the iteration. + } + do_stuff(data); } } static void BM_test_ranged_fo(benchmark::State & state) { - state.SkipWithError("test will not be entered"); + auto resource = GetResource(); + if (!resource.good()) { + state.SkipWithError("Resource is not good!"); + return; // Early return is allowed when SkipWithError() has been used. + } for (auto _ : state) { - state.SkipWithError("Failed!"); - break; // REQUIRED to prevent all further iterations. + auto data = resource.read_data(); + if (!resource.good()) { + state.SkipWithError("Failed to read data!"); + break; // REQUIRED to prevent all further iterations. + } + do_stuff(data); } } ``` -### A Faster KeepRunning Loop +## A Faster KeepRunning Loop In C++11 mode, a ranged-based for loop should be used in preference to the `KeepRunning` loop for running the benchmarks. For example: @@ -1166,14 +1250,17 @@ the benchmark loop should be preferred. -### Disabling CPU Frequency Scaling +## Disabling CPU Frequency Scaling + If you see this error: + ``` -***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead. -``` -you might want to disable the CPU frequency scaling while running the benchmark: -```bash -sudo cpupower frequency-set --governor performance -./mybench -sudo cpupower frequency-set --governor powersave +***WARNING*** CPU scaling is enabled, the benchmark real time measurements may +be noisy and will incur extra overhead. ``` + +you might want to disable the CPU frequency scaling while running the +benchmark, as well as consider other ways to stabilize the performance of +your system while benchmarking. + +See [Reducing Variance](reducing_variance.md) for more information. diff --git a/thirdparty_builtin/benchmark-1.5.0/include/benchmark/benchmark.h b/thirdparty_builtin/benchmark-1.8.0/include/benchmark/benchmark.h similarity index 69% rename from thirdparty_builtin/benchmark-1.5.0/include/benchmark/benchmark.h rename to thirdparty_builtin/benchmark-1.8.0/include/benchmark/benchmark.h index 0b1f45148..e44d53412 100644 --- a/thirdparty_builtin/benchmark-1.5.0/include/benchmark/benchmark.h +++ b/thirdparty_builtin/benchmark-1.8.0/include/benchmark/benchmark.h @@ -34,7 +34,7 @@ static void BM_StringCopy(benchmark::State& state) { BENCHMARK(BM_StringCopy); // Augment the main() program to invoke benchmarks if specified -// via the --benchmarks command line flag. E.g., +// via the --benchmark_filter command line flag. E.g., // my_unittest --benchmark_filter=all // my_unittest --benchmark_filter=BM_StringCreation // my_unittest --benchmark_filter=String @@ -42,6 +42,7 @@ BENCHMARK(BM_StringCopy); int main(int argc, char** argv) { benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); + benchmark::Shutdown(); return 0; } @@ -139,13 +140,13 @@ thread exits the loop body. As such, any global setup or teardown you want to do can be wrapped in a check against the thread index: static void BM_MultiThreaded(benchmark::State& state) { - if (state.thread_index == 0) { + if (state.thread_index() == 0) { // Setup code here. } for (auto _ : state) { // Run the test as normal. } - if (state.thread_index == 0) { + if (state.thread_index() == 0) { // Teardown code here. } } @@ -167,22 +168,29 @@ BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); #define BENCHMARK_HAS_CXX11 #endif +// This _MSC_VER check should detect VS 2017 v15.3 and newer. +#if __cplusplus >= 201703L || \ + (defined(_MSC_VER) && _MSC_VER >= 1911 && _MSVC_LANG >= 201703L) +#define BENCHMARK_HAS_CXX17 +#endif + #include #include #include #include #include -// BLT PATCH START -// gcc@11 requires this for std::numeric_limits #include -// BLT PATCH END #include #include #include +#include #include +#include "benchmark/export.h" + #if defined(BENCHMARK_HAS_CXX11) +#include #include #include #include @@ -202,42 +210,63 @@ BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); TypeName& operator=(const TypeName&) = delete #endif -#if defined(__GNUC__) +#ifdef BENCHMARK_HAS_CXX17 +#define BENCHMARK_UNUSED [[maybe_unused]] +#elif defined(__GNUC__) || defined(__clang__) #define BENCHMARK_UNUSED __attribute__((unused)) -#define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline)) -#define BENCHMARK_NOEXCEPT noexcept -#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) -#elif defined(_MSC_VER) && !defined(__clang__) +#else #define BENCHMARK_UNUSED -#define BENCHMARK_ALWAYS_INLINE __forceinline -#if _MSC_VER >= 1900 -#define BENCHMARK_NOEXCEPT noexcept -#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) +#endif + +// Used to annotate functions, methods and classes so they +// are not optimized by the compiler. Useful for tests +// where you expect loops to stay in place churning cycles +#if defined(__clang__) +#define BENCHMARK_DONT_OPTIMIZE __attribute__((optnone)) +#elif defined(__GNUC__) || defined(__GNUG__) +#define BENCHMARK_DONT_OPTIMIZE __attribute__((optimize(0))) #else -#define BENCHMARK_NOEXCEPT -#define BENCHMARK_NOEXCEPT_OP(x) +// MSVC & Intel do not have a no-optimize attribute, only line pragmas +#define BENCHMARK_DONT_OPTIMIZE #endif + +#if defined(__GNUC__) || defined(__clang__) +#define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline)) +#elif defined(_MSC_VER) && !defined(__clang__) +#define BENCHMARK_ALWAYS_INLINE __forceinline #define __func__ __FUNCTION__ #else -#define BENCHMARK_UNUSED #define BENCHMARK_ALWAYS_INLINE -#define BENCHMARK_NOEXCEPT -#define BENCHMARK_NOEXCEPT_OP(x) #endif #define BENCHMARK_INTERNAL_TOSTRING2(x) #x #define BENCHMARK_INTERNAL_TOSTRING(x) BENCHMARK_INTERNAL_TOSTRING2(x) -#if defined(__GNUC__) || defined(__clang__) +// clang-format off +#if (defined(__GNUC__) && !defined(__NVCC__) && !defined(__NVCOMPILER)) || defined(__clang__) +#define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y) +#define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg))) +#define BENCHMARK_DISABLE_DEPRECATED_WARNING \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#define BENCHMARK_RESTORE_DEPRECATED_WARNING _Pragma("GCC diagnostic pop") +#elif defined(__NVCOMPILER) #define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y) #define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg))) +#define BENCHMARK_DISABLE_DEPRECATED_WARNING \ + _Pragma("diagnostic push") \ + _Pragma("diag_suppress deprecated_entity_with_custom_message") +#define BENCHMARK_RESTORE_DEPRECATED_WARNING _Pragma("diagnostic pop") #else #define BENCHMARK_BUILTIN_EXPECT(x, y) x #define BENCHMARK_DEPRECATED_MSG(msg) #define BENCHMARK_WARNING_MSG(msg) \ __pragma(message(__FILE__ "(" BENCHMARK_INTERNAL_TOSTRING( \ __LINE__) ") : warning note: " msg)) +#define BENCHMARK_DISABLE_DEPRECATED_WARNING +#define BENCHMARK_RESTORE_DEPRECATED_WARNING #endif +// clang-format on #if defined(__GNUC__) && !defined(__clang__) #define BENCHMARK_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) @@ -255,21 +284,60 @@ BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); #define BENCHMARK_UNREACHABLE() ((void)0) #endif +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_OVERRIDE override +#else +#define BENCHMARK_OVERRIDE +#endif + +#if defined(_MSC_VER) +#pragma warning(push) +// C4251: needs to have dll-interface to be used by clients of class +#pragma warning(disable : 4251) +#endif + namespace benchmark { class BenchmarkReporter; -class MemoryManager; -void Initialize(int* argc, char** argv); +// Default number of minimum benchmark running time in seconds. +const char kDefaultMinTimeStr[] = "0.5s"; + +BENCHMARK_EXPORT void PrintDefaultHelp(); + +BENCHMARK_EXPORT void Initialize(int* argc, char** argv, + void (*HelperPrinterf)() = PrintDefaultHelp); +BENCHMARK_EXPORT void Shutdown(); // Report to stdout all arguments in 'argv' as unrecognized except the first. // Returns true there is at least on unrecognized argument (i.e. 'argc' > 1). -bool ReportUnrecognizedArguments(int argc, char** argv); +BENCHMARK_EXPORT bool ReportUnrecognizedArguments(int argc, char** argv); + +// Returns the current value of --benchmark_filter. +BENCHMARK_EXPORT std::string GetBenchmarkFilter(); + +// Sets a new value to --benchmark_filter. (This will override this flag's +// current value). +// Should be called after `benchmark::Initialize()`, as +// `benchmark::Initialize()` will override the flag's value. +BENCHMARK_EXPORT void SetBenchmarkFilter(std::string value); + +// Returns the current value of --v (command line value for verbosity). +BENCHMARK_EXPORT int32_t GetBenchmarkVerbosity(); + +// Creates a default display reporter. Used by the library when no display +// reporter is provided, but also made available for external use in case a +// custom reporter should respect the `--benchmark_format` flag as a fallback +BENCHMARK_EXPORT BenchmarkReporter* CreateDefaultDisplayReporter(); // Generate a list of benchmarks matching the specified --benchmark_filter flag // and if --benchmark_list_tests is specified return after printing the name // of each matching benchmark. Otherwise run each matching benchmark and // report the results. // +// spec : Specify the benchmarks to run. If users do not specify this arg, +// then the value of FLAGS_benchmark_filter +// will be used. +// // The second and third overload use the specified 'display_reporter' and // 'file_reporter' respectively. 'file_reporter' will write to the file // specified @@ -277,28 +345,94 @@ bool ReportUnrecognizedArguments(int argc, char** argv); // 'file_reporter' is ignored. // // RETURNS: The number of matching benchmarks. -size_t RunSpecifiedBenchmarks(); -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter); -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, - BenchmarkReporter* file_reporter); +BENCHMARK_EXPORT size_t RunSpecifiedBenchmarks(); +BENCHMARK_EXPORT size_t RunSpecifiedBenchmarks(std::string spec); + +BENCHMARK_EXPORT size_t +RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter); +BENCHMARK_EXPORT size_t +RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, std::string spec); + +BENCHMARK_EXPORT size_t RunSpecifiedBenchmarks( + BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter); +BENCHMARK_EXPORT size_t +RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter, std::string spec); + +// TimeUnit is passed to a benchmark in order to specify the order of magnitude +// for the measured time. +enum TimeUnit { kNanosecond, kMicrosecond, kMillisecond, kSecond }; + +BENCHMARK_EXPORT TimeUnit GetDefaultTimeUnit(); + +// Sets the default time unit the benchmarks use +// Has to be called before the benchmark loop to take effect +BENCHMARK_EXPORT void SetDefaultTimeUnit(TimeUnit unit); + +// If a MemoryManager is registered (via RegisterMemoryManager()), +// it can be used to collect and report allocation metrics for a run of the +// benchmark. +class MemoryManager { + public: + static const int64_t TombstoneValue; + + struct Result { + Result() + : num_allocs(0), + max_bytes_used(0), + total_allocated_bytes(TombstoneValue), + net_heap_growth(TombstoneValue) {} + + // The number of allocations made in total between Start and Stop. + int64_t num_allocs; + + // The peak memory use between Start and Stop. + int64_t max_bytes_used; + + // The total memory allocated, in bytes, between Start and Stop. + // Init'ed to TombstoneValue if metric not available. + int64_t total_allocated_bytes; + + // The net changes in memory, in bytes, between Start and Stop. + // ie., total_allocated_bytes - total_deallocated_bytes. + // Init'ed to TombstoneValue if metric not available. + int64_t net_heap_growth; + }; + + virtual ~MemoryManager() {} + + // Implement this to start recording allocation information. + virtual void Start() = 0; + + // Implement this to stop recording and fill out the given Result structure. + virtual void Stop(Result& result) = 0; +}; // Register a MemoryManager instance that will be used to collect and report // allocation measurements for benchmark runs. +BENCHMARK_EXPORT void RegisterMemoryManager(MemoryManager* memory_manager); +// Add a key-value pair to output as part of the context stanza in the report. +BENCHMARK_EXPORT +void AddCustomContext(const std::string& key, const std::string& value); + namespace internal { class Benchmark; class BenchmarkImp; class BenchmarkFamilies; +BENCHMARK_EXPORT std::map*& GetGlobalContext(); + +BENCHMARK_EXPORT void UseCharPointer(char const volatile*); // Take ownership of the pointer and register the benchmark. Return the // registered benchmark. -Benchmark* RegisterBenchmarkInternal(Benchmark*); +BENCHMARK_EXPORT Benchmark* RegisterBenchmarkInternal(Benchmark*); // Ensure that the standard streams are properly initialized in every TU. -int InitializeStreams(); +BENCHMARK_EXPORT int InitializeStreams(); BENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams(); } // namespace internal @@ -308,12 +442,24 @@ BENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams(); #define BENCHMARK_HAS_NO_INLINE_ASSEMBLY #endif +// Force the compiler to flush pending writes to global memory. Acts as an +// effective read/write barrier +#ifdef BENCHMARK_HAS_CXX11 +inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { + std::atomic_signal_fence(std::memory_order_acq_rel); +} +#endif + // The DoNotOptimize(...) function can be used to prevent a value or // expression from being optimized away by the compiler. This function is // intended to add little to no overhead. // See: https://youtu.be/nXaxk27zwlk?t=2441 #ifndef BENCHMARK_HAS_NO_INLINE_ASSEMBLY +#if !defined(__GNUC__) || defined(__llvm__) || defined(__INTEL_COMPILER) template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { asm volatile("" : : "r,m"(value) : "memory"); } @@ -326,26 +472,92 @@ inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { asm volatile("" : "+m,r"(value) : : "memory"); #endif } +#elif defined(BENCHMARK_HAS_CXX11) && (__GNUC__ >= 5) +// Workaround for a bug with full argument copy overhead with GCC. +// See: #1340 and https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105519 +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value && + (sizeof(Tp) <= sizeof(Tp*))>::type + DoNotOptimize(Tp const& value) { + asm volatile("" : : "r,m"(value) : "memory"); +} -// Force the compiler to flush pending writes to global memory. Acts as an -// effective read/write barrier +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value || + (sizeof(Tp) > sizeof(Tp*))>::type + DoNotOptimize(Tp const& value) { + asm volatile("" : : "m"(value) : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value && + (sizeof(Tp) <= sizeof(Tp*))>::type + DoNotOptimize(Tp& value) { + asm volatile("" : "+m,r"(value) : : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE + typename std::enable_if::value || + (sizeof(Tp) > sizeof(Tp*))>::type + DoNotOptimize(Tp& value) { + asm volatile("" : "+m"(value) : : "memory"); +} + +#else +// Fallback for GCC < 5. Can add some overhead because the compiler is forced +// to use memory operations instead of operations with registers. +// TODO: Remove if GCC < 5 will be unsupported. +template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { + asm volatile("" : : "m"(value) : "memory"); +} + +template +inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { + asm volatile("" : "+m"(value) : : "memory"); +} +#endif + +#ifndef BENCHMARK_HAS_CXX11 inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { asm volatile("" : : : "memory"); } +#endif #elif defined(_MSC_VER) template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { internal::UseCharPointer(&reinterpret_cast(value)); _ReadWriteBarrier(); } +#ifndef BENCHMARK_HAS_CXX11 inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { _ReadWriteBarrier(); } +#endif #else template +BENCHMARK_DEPRECATED_MSG( + "The const-ref version of this method can permit " + "undesired compiler optimizations in benchmarks") inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { internal::UseCharPointer(&reinterpret_cast(value)); } -// FIXME Add ClobberMemory() for non-gnu and non-msvc compilers +// FIXME Add ClobberMemory() for non-gnu and non-msvc compilers, before C++11. #endif // This class is used for user-defined counters. @@ -355,24 +567,27 @@ class Counter { kDefaults = 0, // Mark the counter as a rate. It will be presented divided // by the duration of the benchmark. - kIsRate = 1U << 0U, + kIsRate = 1 << 0, // Mark the counter as a thread-average quantity. It will be // presented divided by the number of threads. - kAvgThreads = 1U << 1U, + kAvgThreads = 1 << 1, // Mark the counter as a thread-average rate. See above. kAvgThreadsRate = kIsRate | kAvgThreads, // Mark the counter as a constant value, valid/same for *every* iteration. // When reporting, it will be *multiplied* by the iteration count. - kIsIterationInvariant = 1U << 2U, + kIsIterationInvariant = 1 << 2, // Mark the counter as a constant rate. // When reporting, it will be *multiplied* by the iteration count // and then divided by the duration of the benchmark. kIsIterationInvariantRate = kIsRate | kIsIterationInvariant, // Mark the counter as a iteration-average quantity. // It will be presented divided by the number of iterations. - kAvgIterations = 1U << 3U, + kAvgIterations = 1 << 3, // Mark the counter as a iteration-average rate. See above. - kAvgIterationsRate = kIsRate | kAvgIterations + kAvgIterationsRate = kIsRate | kAvgIterations, + + // In the end, invert the result. This is always done last! + kInvert = 1 << 31 }; enum OneK { @@ -390,7 +605,7 @@ class Counter { Counter(double v = 0., Flags f = kDefaults, OneK k = kIs1000) : value(v), flags(f), oneK(k) {} - BENCHMARK_ALWAYS_INLINE operator double const&() const { return value; } + BENCHMARK_ALWAYS_INLINE operator double const &() const { return value; } BENCHMARK_ALWAYS_INLINE operator double&() { return value; } }; @@ -405,17 +620,15 @@ Counter::Flags inline operator|(const Counter::Flags& LHS, // This is the container for the user-defined counters. typedef std::map UserCounters; -// TimeUnit is passed to a benchmark in order to specify the order of magnitude -// for the measured time. -enum TimeUnit { kNanosecond, kMicrosecond, kMillisecond }; - // BigO is passed to a benchmark in order to specify the asymptotic // computational // complexity for the benchmark. In case oAuto is selected, complexity will be // calculated automatically to the best fit. enum BigO { oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda }; -typedef uint64_t IterationCount; +typedef int64_t IterationCount; + +enum StatisticUnit { kTime, kPercentage }; // BigOFunc is passed to a benchmark in order to specify the asymptotic // computational complexity for the benchmark. @@ -429,14 +642,17 @@ namespace internal { struct Statistics { std::string name_; StatisticsFunc* compute_; + StatisticUnit unit_; - Statistics(const std::string& name, StatisticsFunc* compute) - : name_(name), compute_(compute) {} + Statistics(const std::string& name, StatisticsFunc* compute, + StatisticUnit unit = kTime) + : name_(name), compute_(compute), unit_(unit) {} }; -struct BenchmarkInstance; +class BenchmarkInstance; class ThreadTimer; class ThreadManager; +class PerfCountersMeasurement; enum AggregationReportMode #if defined(BENCHMARK_HAS_CXX11) @@ -458,11 +674,21 @@ enum AggregationReportMode ARM_FileReportAggregatesOnly | ARM_DisplayReportAggregatesOnly }; +enum Skipped +#if defined(BENCHMARK_HAS_CXX11) + : unsigned +#endif +{ + NotSkipped = 0, + SkippedWithMessage, + SkippedWithError +}; + } // namespace internal // State is passed to a running Benchmark and contains state for the // benchmark to use. -class State { +class BENCHMARK_EXPORT State { public: struct StateIterator; friend struct StateIterator; @@ -494,8 +720,8 @@ class State { // } bool KeepRunningBatch(IterationCount n); - // REQUIRES: timer is running and 'SkipWithError(...)' has not been called - // by the current thread. + // REQUIRES: timer is running and 'SkipWithMessage(...)' or + // 'SkipWithError(...)' has not been called by the current thread. // Stop the benchmark timer. If not called, the timer will be // automatically stopped after the last iteration of the benchmark loop. // @@ -510,8 +736,8 @@ class State { // within each benchmark iteration, if possible. void PauseTiming(); - // REQUIRES: timer is not running and 'SkipWithError(...)' has not been called - // by the current thread. + // REQUIRES: timer is not running and 'SkipWithMessage(...)' or + // 'SkipWithError(...)' has not been called by the current thread. // Start the benchmark timer. The timer is NOT running on entrance to the // benchmark function. It begins running after control flow enters the // benchmark loop. @@ -521,8 +747,30 @@ class State { // within each benchmark iteration, if possible. void ResumeTiming(); - // REQUIRES: 'SkipWithError(...)' has not been called previously by the - // current thread. + // REQUIRES: 'SkipWithMessage(...)' or 'SkipWithError(...)' has not been + // called previously by the current thread. + // Report the benchmark as resulting in being skipped with the specified + // 'msg'. + // After this call the user may explicitly 'return' from the benchmark. + // + // If the ranged-for style of benchmark loop is used, the user must explicitly + // break from the loop, otherwise all future iterations will be run. + // If the 'KeepRunning()' loop is used the current thread will automatically + // exit the loop at the end of the current iteration. + // + // For threaded benchmarks only the current thread stops executing and future + // calls to `KeepRunning()` will block until all threads have completed + // the `KeepRunning()` loop. If multiple threads report being skipped only the + // first skip message is used. + // + // NOTE: Calling 'SkipWithMessage(...)' does not cause the benchmark to exit + // the current scope immediately. If the function is called from within + // the 'KeepRunning()' loop the current iteration will finish. It is the users + // responsibility to exit the scope as needed. + void SkipWithMessage(const std::string& msg); + + // REQUIRES: 'SkipWithMessage(...)' or 'SkipWithError(...)' has not been + // called previously by the current thread. // Report the benchmark as resulting in an error with the specified 'msg'. // After this call the user may explicitly 'return' from the benchmark. // @@ -540,7 +788,13 @@ class State { // the current scope immediately. If the function is called from within // the 'KeepRunning()' loop the current iteration will finish. It is the users // responsibility to exit the scope as needed. - void SkipWithError(const char* msg); + void SkipWithError(const std::string& msg); + + // Returns true if 'SkipWithMessage(...)' or 'SkipWithError(...)' was called. + bool skipped() const { return internal::NotSkipped != skipped_; } + + // Returns true if an error has been reported with 'SkipWithError(...)'. + bool error_occurred() const { return internal::SkippedWithError == skipped_; } // REQUIRES: called exactly once per iteration of the benchmarking loop. // Set the manually measured time for this benchmark iteration, which @@ -578,7 +832,7 @@ class State { void SetComplexityN(int64_t complexity_n) { complexity_n_ = complexity_n; } BENCHMARK_ALWAYS_INLINE - int64_t complexity_length_n() { return complexity_n_; } + int64_t complexity_length_n() const { return complexity_n_; } // If this routine is called with items > 0, then an items/s // label is printed on the benchmark report line for the currently @@ -611,11 +865,7 @@ class State { // BM_Compress 50 50 14115038 compress:27.3% // // REQUIRES: a benchmark has exited its benchmarking loop. - void SetLabel(const char* label); - - void BENCHMARK_ALWAYS_INLINE SetLabel(const std::string& str) { - this->SetLabel(str.c_str()); - } + void SetLabel(const std::string& label); // Range arguments for this run. CHECKs if the argument has been set. BENCHMARK_ALWAYS_INLINE @@ -630,6 +880,14 @@ class State { BENCHMARK_DEPRECATED_MSG("use 'range(1)' instead") int64_t range_y() const { return range(1); } + // Number of threads concurrently executing the benchmark. + BENCHMARK_ALWAYS_INLINE + int threads() const { return threads_; } + + // Index of the executing thread. Values from [0, threads). + BENCHMARK_ALWAYS_INLINE + int thread_index() const { return thread_index_; } + BENCHMARK_ALWAYS_INLINE IterationCount iterations() const { if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) { @@ -638,8 +896,11 @@ class State { return max_iterations - total_iterations_ + batch_leftover_; } - private - : // items we expect on the first cache line (ie 64 bytes of the struct) + BENCHMARK_ALWAYS_INLINE + std::string name() const { return name_; } + + private: + // items we expect on the first cache line (ie 64 bytes of the struct) // When total_iterations_ is 0, KeepRunning() and friends will return false. // May be larger than max_iterations. IterationCount total_iterations_; @@ -655,9 +916,9 @@ class State { private: bool started_; bool finished_; - bool error_occurred_; + internal::Skipped skipped_; - private: // items we don't need on the first cache line + // items we don't need on the first cache line std::vector range_; int64_t complexity_n_; @@ -665,25 +926,28 @@ class State { public: // Container for user-defined counters. UserCounters counters; - // Index of the executing thread. Values from [0, threads). - const int thread_index; - // Number of threads concurrently executing the benchmark. - const int threads; private: - State(IterationCount max_iters, const std::vector& ranges, - int thread_i, int n_threads, internal::ThreadTimer* timer, - internal::ThreadManager* manager); + State(std::string name, IterationCount max_iters, + const std::vector& ranges, int thread_i, int n_threads, + internal::ThreadTimer* timer, internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement); void StartKeepRunning(); // Implementation of KeepRunning() and KeepRunningBatch(). // is_batch must be true unless n is 1. bool KeepRunningInternal(IterationCount n, bool is_batch); void FinishKeepRunning(); - internal::ThreadTimer* timer_; - internal::ThreadManager* manager_; - friend struct internal::BenchmarkInstance; + const std::string name_; + const int thread_index_; + const int threads_; + + internal::ThreadTimer* const timer_; + internal::ThreadManager* const manager_; + internal::PerfCountersMeasurement* const perf_counters_measurement_; + + friend class internal::BenchmarkInstance; }; inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunning() { @@ -707,7 +971,7 @@ inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningInternal(IterationCount n, } if (!started_) { StartKeepRunning(); - if (!error_occurred_ && total_iterations_ >= n) { + if (!skipped() && total_iterations_ >= n) { total_iterations_ -= n; return true; } @@ -737,7 +1001,7 @@ struct State::StateIterator { BENCHMARK_ALWAYS_INLINE explicit StateIterator(State* st) - : cached_(st->error_occurred_ ? 0 : st->max_iterations), parent_(st) {} + : cached_(st->skipped() ? 0 : st->max_iterations), parent_(st) {} public: BENCHMARK_ALWAYS_INLINE @@ -780,13 +1044,16 @@ typedef void(Function)(State&); // be called on this object to change the properties of the benchmark. // Each method returns "this" so that multiple method calls can // chained into one expression. -class Benchmark { +class BENCHMARK_EXPORT Benchmark { public: virtual ~Benchmark(); // Note: the following methods all return "this" so that multiple // method calls can be chained together in one expression. + // Specify the name of the benchmark + Benchmark* Name(const std::string& name); + // Run this benchmark once with "x" as the extra argument passed // to the function. // REQUIRES: The function passed to the constructor must accept an arg1. @@ -825,6 +1092,11 @@ class Benchmark { // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... Benchmark* Ranges(const std::vector >& ranges); + // Run this benchmark once for each combination of values in the (cartesian) + // product of the supplied argument lists. + // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... + Benchmark* ArgsProduct(const std::vector >& arglists); + // Equivalent to ArgNames({name}) Benchmark* ArgName(const std::string& name); @@ -842,6 +1114,23 @@ class Benchmark { return Ranges(ranges); } + // Have "setup" and/or "teardown" invoked once for every benchmark run. + // If the benchmark is multi-threaded (will run in k threads concurrently), + // the setup callback will be be invoked exactly once (not k times) before + // each run with k threads. Time allowing (e.g. for a short benchmark), there + // may be multiple such runs per benchmark, each run with its own + // "setup"/"teardown". + // + // If the benchmark uses different size groups of threads (e.g. via + // ThreadRange), the above will be true for each size group. + // + // The callback will be passed a State object, which includes the number + // of threads, thread-index, benchmark arguments, etc. + // + // The callback must not be NULL or self-deleting. + Benchmark* Setup(void (*setup)(const benchmark::State&)); + Benchmark* Teardown(void (*teardown)(const benchmark::State&)); + // Pass this benchmark object to *func, which can customize // the benchmark by calling various methods like Arg, Args, // Threads, etc. @@ -856,12 +1145,19 @@ class Benchmark { // REQUIRES: `t > 0` and `Iterations` has not been called on this benchmark. Benchmark* MinTime(double t); + // Set the minimum amount of time to run the benchmark before taking runtimes + // of this benchmark into account. This + // option overrides the `benchmark_min_warmup_time` flag. + // REQUIRES: `t >= 0` and `Iterations` has not been called on this benchmark. + Benchmark* MinWarmUpTime(double t); + // Specify the amount of iterations that should be run by this benchmark. + // This option overrides the `benchmark_min_time` flag. // REQUIRES: 'n > 0' and `MinTime` has not been called on this benchmark. // // NOTE: This function should only be used when *exact* iteration control is // needed and never to control or limit how long a benchmark runs, where - // `--benchmark_min_time=N` or `MinTime(...)` should be used instead. + // `--benchmark_min_time=s` or `MinTime(...)` should be used instead. Benchmark* Iterations(IterationCount n); // Specify the amount of times to repeat this benchmark. This option overrides @@ -881,7 +1177,7 @@ class Benchmark { // By default, the CPU time is measured only for the main thread, which may // be unrepresentative if the benchmark uses threads internally. If called, // the total CPU time spent by all the threads will be measured instead. - // By default, the only the main thread CPU time will be measured. + // By default, only the main thread CPU time will be measured. Benchmark* MeasureProcessCPUTime(); // If a particular benchmark should use the Wall clock instead of the CPU time @@ -910,7 +1206,9 @@ class Benchmark { Benchmark* Complexity(BigOFunc* complexity); // Add this statistics to be computed over all the values of benchmark run - Benchmark* ComputeStatistics(std::string name, StatisticsFunc* statistics); + Benchmark* ComputeStatistics(const std::string& name, + StatisticsFunc* statistics, + StatisticUnit unit = kTime); // Support for running multiple copies of the same benchmark concurrently // in multiple threads. This may be useful when measuring the scaling @@ -944,23 +1242,32 @@ class Benchmark { virtual void Run(State& state) = 0; + TimeUnit GetTimeUnit() const; + protected: - explicit Benchmark(const char* name); - Benchmark(Benchmark const&); - void SetName(const char* name); + explicit Benchmark(const std::string& name); + void SetName(const std::string& name); + public: + const char* GetName() const; int ArgsCnt() const; + const char* GetArgName(int arg) const; private: friend class BenchmarkFamilies; + friend class BenchmarkInstance; std::string name_; AggregationReportMode aggregation_report_mode_; std::vector arg_names_; // Args for all benchmark runs std::vector > args_; // Args for all benchmark runs + TimeUnit time_unit_; + bool use_default_time_unit_; + int range_multiplier_; double min_time_; + double min_warmup_time_; IterationCount iterations_; int repetitions_; bool measure_process_cpu_time_; @@ -971,7 +1278,21 @@ class Benchmark { std::vector statistics_; std::vector thread_counts_; - Benchmark& operator=(Benchmark const&); + typedef void (*callback_function)(const benchmark::State&); + callback_function setup_; + callback_function teardown_; + + Benchmark(Benchmark const&) +#if defined(BENCHMARK_HAS_CXX11) + = delete +#endif + ; + + Benchmark& operator=(Benchmark const&) +#if defined(BENCHMARK_HAS_CXX11) + = delete +#endif + ; }; } // namespace internal @@ -980,27 +1301,27 @@ class Benchmark { // the specified functor 'fn'. // // RETURNS: A pointer to the registered benchmark. -internal::Benchmark* RegisterBenchmark(const char* name, +internal::Benchmark* RegisterBenchmark(const std::string& name, internal::Function* fn); #if defined(BENCHMARK_HAS_CXX11) template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn); +internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn); #endif // Remove all registered benchmarks. All pointers to previously registered // benchmarks are invalidated. -void ClearRegisteredBenchmarks(); +BENCHMARK_EXPORT void ClearRegisteredBenchmarks(); namespace internal { // The class used to hold all Benchmarks created from static function. // (ie those created using the BENCHMARK(...) macros. -class FunctionBenchmark : public Benchmark { +class BENCHMARK_EXPORT FunctionBenchmark : public Benchmark { public: - FunctionBenchmark(const char* name, Function* func) + FunctionBenchmark(const std::string& name, Function* func) : Benchmark(name), func_(func) {} - virtual void Run(State& st); + void Run(State& st) BENCHMARK_OVERRIDE; private: Function* func_; @@ -1010,26 +1331,24 @@ class FunctionBenchmark : public Benchmark { template class LambdaBenchmark : public Benchmark { public: - virtual void Run(State& st) { lambda_(st); } + void Run(State& st) BENCHMARK_OVERRIDE { lambda_(st); } private: template - LambdaBenchmark(const char* name, OLambda&& lam) + LambdaBenchmark(const std::string& name, OLambda&& lam) : Benchmark(name), lambda_(std::forward(lam)) {} LambdaBenchmark(LambdaBenchmark const&) = delete; - private: - template - friend Benchmark* ::benchmark::RegisterBenchmark(const char*, Lam&&); + template // NOLINTNEXTLINE(readability-redundant-declaration) + friend Benchmark* ::benchmark::RegisterBenchmark(const std::string&, Lam&&); Lambda lambda_; }; #endif - } // namespace internal -inline internal::Benchmark* RegisterBenchmark(const char* name, +inline internal::Benchmark* RegisterBenchmark(const std::string& name, internal::Function* fn) { return internal::RegisterBenchmarkInternal( ::new internal::FunctionBenchmark(name, fn)); @@ -1037,7 +1356,7 @@ inline internal::Benchmark* RegisterBenchmark(const char* name, #ifdef BENCHMARK_HAS_CXX11 template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) { +internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn) { using BenchType = internal::LambdaBenchmark::type>; return internal::RegisterBenchmarkInternal( @@ -1048,7 +1367,7 @@ internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) { #if defined(BENCHMARK_HAS_CXX11) && \ (!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409) template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn, +internal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn, Args&&... args) { return benchmark::RegisterBenchmark( name, [=](benchmark::State& st) { fn(st, args...); }); @@ -1062,7 +1381,7 @@ class Fixture : public internal::Benchmark { public: Fixture() : internal::Benchmark("") {} - virtual void Run(State& st) { + void Run(State& st) BENCHMARK_OVERRIDE { this->SetUp(st); this->BenchmarkCase(st); this->TearDown(st); @@ -1078,7 +1397,6 @@ class Fixture : public internal::Benchmark { protected: virtual void BenchmarkCase(State&) = 0; }; - } // namespace benchmark // ------------------------------------------------------ @@ -1094,19 +1412,37 @@ class Fixture : public internal::Benchmark { #endif // Helpers for generating unique variable names +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK_PRIVATE_NAME(...) \ + BENCHMARK_PRIVATE_CONCAT(benchmark_uniq_, BENCHMARK_PRIVATE_UNIQUE_ID, \ + __VA_ARGS__) +#else #define BENCHMARK_PRIVATE_NAME(n) \ - BENCHMARK_PRIVATE_CONCAT(_benchmark_, BENCHMARK_PRIVATE_UNIQUE_ID, n) + BENCHMARK_PRIVATE_CONCAT(benchmark_uniq_, BENCHMARK_PRIVATE_UNIQUE_ID, n) +#endif // BENCHMARK_HAS_CXX11 + #define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c) #define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c +// Helper for concatenation with macro name expansion +#define BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method) \ + BaseClass##_##Method##_Benchmark #define BENCHMARK_PRIVATE_DECLARE(n) \ static ::benchmark::internal::Benchmark* BENCHMARK_PRIVATE_NAME(n) \ BENCHMARK_UNUSED +#ifdef BENCHMARK_HAS_CXX11 +#define BENCHMARK(...) \ + BENCHMARK_PRIVATE_DECLARE(_benchmark_) = \ + (::benchmark::internal::RegisterBenchmarkInternal( \ + new ::benchmark::internal::FunctionBenchmark(#__VA_ARGS__, \ + __VA_ARGS__))) +#else #define BENCHMARK(n) \ BENCHMARK_PRIVATE_DECLARE(n) = \ (::benchmark::internal::RegisterBenchmarkInternal( \ new ::benchmark::internal::FunctionBenchmark(#n, n))) +#endif // BENCHMARK_HAS_CXX11 // Old-style macros #define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a)) @@ -1167,49 +1503,49 @@ class Fixture : public internal::Benchmark { #define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a) #endif -#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - class BaseClass##_##Method##_Benchmark : public BaseClass { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ - this->SetName(#BaseClass "/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ +#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ + class BaseClass##_##Method##_Benchmark : public BaseClass { \ + public: \ + BaseClass##_##Method##_Benchmark() { \ + this->SetName(#BaseClass "/" #Method); \ + } \ + \ + protected: \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ }; #define BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ class BaseClass##_##Method##_Benchmark : public BaseClass { \ public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ + BaseClass##_##Method##_Benchmark() { \ this->SetName(#BaseClass "<" #a ">/" #Method); \ } \ \ protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ }; #define BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ class BaseClass##_##Method##_Benchmark : public BaseClass { \ public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ + BaseClass##_##Method##_Benchmark() { \ this->SetName(#BaseClass "<" #a "," #b ">/" #Method); \ } \ \ protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ }; #ifdef BENCHMARK_HAS_CXX11 #define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, ...) \ class BaseClass##_##Method##_Benchmark : public BaseClass<__VA_ARGS__> { \ public: \ - BaseClass##_##Method##_Benchmark() : BaseClass<__VA_ARGS__>() { \ + BaseClass##_##Method##_Benchmark() { \ this->SetName(#BaseClass "<" #__VA_ARGS__ ">/" #Method); \ } \ \ protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ + void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \ }; #else #define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(n, a) \ @@ -1218,27 +1554,27 @@ class Fixture : public internal::Benchmark { #define BENCHMARK_DEFINE_F(BaseClass, Method) \ BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #define BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) \ BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #define BENCHMARK_TEMPLATE2_DEFINE_F(BaseClass, Method, a, b) \ BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #ifdef BENCHMARK_HAS_CXX11 #define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, ...) \ BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #else #define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, a) \ BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) #endif #define BENCHMARK_REGISTER_F(BaseClass, Method) \ - BENCHMARK_PRIVATE_REGISTER_F(BaseClass##_##Method##_Benchmark) + BENCHMARK_PRIVATE_REGISTER_F(BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)) #define BENCHMARK_PRIVATE_REGISTER_F(TestName) \ BENCHMARK_PRIVATE_DECLARE(TestName) = \ @@ -1248,34 +1584,43 @@ class Fixture : public internal::Benchmark { #define BENCHMARK_F(BaseClass, Method) \ BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #define BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) \ BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #define BENCHMARK_TEMPLATE2_F(BaseClass, Method, a, b) \ BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #ifdef BENCHMARK_HAS_CXX11 #define BENCHMARK_TEMPLATE_F(BaseClass, Method, ...) \ BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase + void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase #else #define BENCHMARK_TEMPLATE_F(BaseClass, Method, a) \ BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) #endif // Helper macro to create a main routine in a test that runs the benchmarks +// Note the workaround for Hexagon simulator passing argc != 0, argv = NULL. #define BENCHMARK_MAIN() \ int main(int argc, char** argv) { \ + char arg0_default[] = "benchmark"; \ + char* args_default = arg0_default; \ + if (!argv) { \ + argc = 1; \ + argv = &args_default; \ + } \ ::benchmark::Initialize(&argc, argv); \ if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; \ ::benchmark::RunSpecifiedBenchmarks(); \ + ::benchmark::Shutdown(); \ + return 0; \ } \ int main(int, char**) @@ -1284,7 +1629,7 @@ class Fixture : public internal::Benchmark { namespace benchmark { -struct CPUInfo { +struct BENCHMARK_EXPORT CPUInfo { struct CacheInfo { std::string type; int level; @@ -1292,10 +1637,12 @@ struct CPUInfo { int num_sharing; }; + enum Scaling { UNKNOWN, ENABLED, DISABLED }; + int num_cpus; + Scaling scaling; double cycles_per_second; std::vector caches; - bool scaling_enabled; std::vector load_avg; static const CPUInfo& Get(); @@ -1306,7 +1653,7 @@ struct CPUInfo { }; // Adding Struct for System Information -struct SystemInfo { +struct BENCHMARK_EXPORT SystemInfo { std::string name; static const SystemInfo& Get(); @@ -1318,10 +1665,11 @@ struct SystemInfo { // BenchmarkName contains the components of the Benchmark's name // which allows individual fields to be modified or cleared before // building the final name using 'str()'. -struct BenchmarkName { +struct BENCHMARK_EXPORT BenchmarkName { std::string function_name; std::string args; std::string min_time; + std::string min_warmup_time; std::string iterations; std::string repetitions; std::string time_type; @@ -1337,7 +1685,7 @@ struct BenchmarkName { // can control the destination of the reports by calling // RunSpecifiedBenchmarks and passing it a custom reporter object. // The reporter object must implement the following interface. -class BenchmarkReporter { +class BENCHMARK_EXPORT BenchmarkReporter { public: struct Context { CPUInfo const& cpu_info; @@ -1348,16 +1696,17 @@ class BenchmarkReporter { Context(); }; - struct Run { + struct BENCHMARK_EXPORT Run { static const int64_t no_repetition_index = -1; enum RunType { RT_Iteration, RT_Aggregate }; Run() : run_type(RT_Iteration), - error_occurred(false), + aggregate_unit(kTime), + skipped(internal::NotSkipped), iterations(1), threads(1), - time_unit(kNanosecond), + time_unit(GetDefaultTimeUnit()), real_accumulated_time(0), cpu_accumulated_time(0), max_heapbytes_used(0), @@ -1366,18 +1715,19 @@ class BenchmarkReporter { complexity_n(0), report_big_o(false), report_rms(false), - counters(), - has_memory_result(false), - allocs_per_iter(0.0), - max_bytes_used(0) {} + memory_result(NULL), + allocs_per_iter(0.0) {} std::string benchmark_name() const; BenchmarkName run_name; + int64_t family_index; + int64_t per_family_instance_index; RunType run_type; std::string aggregate_name; + StatisticUnit aggregate_unit; std::string report_label; // Empty if not set by benchmark. - bool error_occurred; - std::string error_message; + internal::Skipped skipped; + std::string skip_message; IterationCount iterations; int64_t threads; @@ -1417,9 +1767,21 @@ class BenchmarkReporter { UserCounters counters; // Memory metrics. - bool has_memory_result; + const MemoryManager::Result* memory_result; double allocs_per_iter; - int64_t max_bytes_used; + }; + + struct PerFamilyRunReports { + PerFamilyRunReports() : num_runs_total(0), num_runs_done(0) {} + + // How many runs will all instances of this benchmark perform? + int num_runs_total; + + // How many runs have happened already? + int num_runs_done; + + // The reports about (non-errneous!) runs of this family. + std::vector Runs; }; // Construct a BenchmarkReporter with the output stream set to 'std::cout' @@ -1434,6 +1796,12 @@ class BenchmarkReporter { // to skip runs based on the context information. virtual bool ReportContext(const Context& context) = 0; + // Called once for each group of benchmark runs, gives information about + // the configurations of the runs. + virtual void ReportRunsConfig(double /*min_time*/, + bool /*has_explicit_iters*/, + IterationCount /*iters*/) {} + // Called once for each group of benchmark runs, gives information about // cpu-time and heap memory usage during the benchmark run. If the group // of runs contained more than two entries then 'report' contains additional @@ -1479,7 +1847,7 @@ class BenchmarkReporter { // Simple reporter that outputs benchmark data to the console. This is the // default reporter used by RunSpecifiedBenchmarks(). -class ConsoleReporter : public BenchmarkReporter { +class BENCHMARK_EXPORT ConsoleReporter : public BenchmarkReporter { public: enum OutputOptions { OO_None = 0, @@ -1489,13 +1857,10 @@ class ConsoleReporter : public BenchmarkReporter { OO_Defaults = OO_ColorTabular }; explicit ConsoleReporter(OutputOptions opts_ = OO_Defaults) - : output_options_(opts_), - name_field_width_(0), - prev_counters_(), - printed_header_(false) {} + : output_options_(opts_), name_field_width_(0), printed_header_(false) {} - virtual bool ReportContext(const Context& context); - virtual void ReportRuns(const std::vector& reports); + bool ReportContext(const Context& context) BENCHMARK_OVERRIDE; + void ReportRuns(const std::vector& reports) BENCHMARK_OVERRIDE; protected: virtual void PrintRunData(const Run& report); @@ -1507,12 +1872,12 @@ class ConsoleReporter : public BenchmarkReporter { bool printed_header_; }; -class JSONReporter : public BenchmarkReporter { +class BENCHMARK_EXPORT JSONReporter : public BenchmarkReporter { public: JSONReporter() : first_report_(true) {} - virtual bool ReportContext(const Context& context); - virtual void ReportRuns(const std::vector& reports); - virtual void Finalize(); + bool ReportContext(const Context& context) BENCHMARK_OVERRIDE; + void ReportRuns(const std::vector& reports) BENCHMARK_OVERRIDE; + void Finalize() BENCHMARK_OVERRIDE; private: void PrintRunData(const Run& report); @@ -1520,13 +1885,13 @@ class JSONReporter : public BenchmarkReporter { bool first_report_; }; -class BENCHMARK_DEPRECATED_MSG( +class BENCHMARK_EXPORT BENCHMARK_DEPRECATED_MSG( "The CSV Reporter will be removed in a future release") CSVReporter : public BenchmarkReporter { public: CSVReporter() : printed_header_(false) {} - virtual bool ReportContext(const Context& context); - virtual void ReportRuns(const std::vector& reports); + bool ReportContext(const Context& context) BENCHMARK_OVERRIDE; + void ReportRuns(const std::vector& reports) BENCHMARK_OVERRIDE; private: void PrintRunData(const Run& report); @@ -1535,31 +1900,10 @@ class BENCHMARK_DEPRECATED_MSG( std::set user_counter_names_; }; -// If a MemoryManager is registered, it can be used to collect and report -// allocation metrics for a run of the benchmark. -class MemoryManager { - public: - struct Result { - Result() : num_allocs(0), max_bytes_used(0) {} - - // The number of allocations made in total between Start and Stop. - int64_t num_allocs; - - // The peak memory use between Start and Stop. - int64_t max_bytes_used; - }; - - virtual ~MemoryManager() {} - - // Implement this to start recording allocation information. - virtual void Start() = 0; - - // Implement this to stop recording and fill out the given Result structure. - virtual void Stop(Result* result) = 0; -}; - inline const char* GetTimeUnitString(TimeUnit unit) { switch (unit) { + case kSecond: + return "s"; case kMillisecond: return "ms"; case kMicrosecond: @@ -1572,6 +1916,8 @@ inline const char* GetTimeUnitString(TimeUnit unit) { inline double GetTimeUnitMultiplier(TimeUnit unit) { switch (unit) { + case kSecond: + return 1; case kMillisecond: return 1e3; case kMicrosecond: @@ -1582,6 +1928,26 @@ inline double GetTimeUnitMultiplier(TimeUnit unit) { BENCHMARK_UNREACHABLE(); } +// Creates a list of integer values for the given range and multiplier. +// This can be used together with ArgsProduct() to allow multiple ranges +// with different multipliers. +// Example: +// ArgsProduct({ +// CreateRange(0, 1024, /*multi=*/32), +// CreateRange(0, 100, /*multi=*/4), +// CreateDenseRange(0, 4, /*step=*/1), +// }); +BENCHMARK_EXPORT +std::vector CreateRange(int64_t lo, int64_t hi, int multi); + +// Creates a list of integer values for the given range and step. +BENCHMARK_EXPORT +std::vector CreateDenseRange(int64_t start, int64_t limit, int step); + } // namespace benchmark +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + #endif // BENCHMARK_BENCHMARK_H_ diff --git a/thirdparty_builtin/benchmark-1.8.0/include/benchmark/export.h b/thirdparty_builtin/benchmark-1.8.0/include/benchmark/export.h new file mode 100644 index 000000000..f96f8596c --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/include/benchmark/export.h @@ -0,0 +1,47 @@ +#ifndef BENCHMARK_EXPORT_H +#define BENCHMARK_EXPORT_H + +#if defined(_WIN32) +#define EXPORT_ATTR __declspec(dllexport) +#define IMPORT_ATTR __declspec(dllimport) +#define NO_EXPORT_ATTR +#define DEPRECATED_ATTR __declspec(deprecated) +#else // _WIN32 +#define EXPORT_ATTR __attribute__((visibility("default"))) +#define IMPORT_ATTR __attribute__((visibility("default"))) +#define NO_EXPORT_ATTR __attribute__((visibility("hidden"))) +#define DEPRECATE_ATTR __attribute__((__deprecated__)) +#endif // _WIN32 + +#ifdef BENCHMARK_STATIC_DEFINE +#define BENCHMARK_EXPORT +#define BENCHMARK_NO_EXPORT +#else // BENCHMARK_STATIC_DEFINE +#ifndef BENCHMARK_EXPORT +#ifdef benchmark_EXPORTS +/* We are building this library */ +#define BENCHMARK_EXPORT EXPORT_ATTR +#else // benchmark_EXPORTS +/* We are using this library */ +#define BENCHMARK_EXPORT IMPORT_ATTR +#endif // benchmark_EXPORTS +#endif // !BENCHMARK_EXPORT + +#ifndef BENCHMARK_NO_EXPORT +#define BENCHMARK_NO_EXPORT NO_EXPORT_ATTR +#endif // !BENCHMARK_NO_EXPORT +#endif // BENCHMARK_STATIC_DEFINE + +#ifndef BENCHMARK_DEPRECATED +#define BENCHMARK_DEPRECATED DEPRECATE_ATTR +#endif // BENCHMARK_DEPRECATED + +#ifndef BENCHMARK_DEPRECATED_EXPORT +#define BENCHMARK_DEPRECATED_EXPORT BENCHMARK_EXPORT BENCHMARK_DEPRECATED +#endif // BENCHMARK_DEPRECATED_EXPORT + +#ifndef BENCHMARK_DEPRECATED_NO_EXPORT +#define BENCHMARK_DEPRECATED_NO_EXPORT BENCHMARK_NO_EXPORT BENCHMARK_DEPRECATED +#endif // BENCHMARK_DEPRECATED_EXPORT + +#endif /* BENCHMARK_EXPORT_H */ diff --git a/thirdparty_builtin/benchmark-1.8.0/requirements.txt b/thirdparty_builtin/benchmark-1.8.0/requirements.txt new file mode 100644 index 000000000..1c8a4bd12 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/requirements.txt @@ -0,0 +1,2 @@ +numpy == 1.22 +scipy == 1.5.4 diff --git a/thirdparty_builtin/benchmark-1.8.0/setup.py b/thirdparty_builtin/benchmark-1.8.0/setup.py new file mode 100644 index 000000000..2388f59b9 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/setup.py @@ -0,0 +1,166 @@ +import contextlib +import os +import platform +import shutil +import sysconfig +from pathlib import Path +from typing import List + +import setuptools +from setuptools.command import build_ext + + +PYTHON_INCLUDE_PATH_PLACEHOLDER = "" + +IS_WINDOWS = platform.system() == "Windows" +IS_MAC = platform.system() == "Darwin" + + +def _get_long_description(fp: str) -> str: + with open(fp, "r", encoding="utf-8") as f: + return f.read() + + +def _get_version(fp: str) -> str: + """Parse a version string from a file.""" + with open(fp, "r") as f: + for line in f: + if "__version__" in line: + delim = '"' + return line.split(delim)[1] + raise RuntimeError(f"could not find a version string in file {fp!r}.") + + +def _parse_requirements(fp: str) -> List[str]: + with open(fp) as requirements: + return [ + line.rstrip() + for line in requirements + if not (line.isspace() or line.startswith("#")) + ] + + +@contextlib.contextmanager +def temp_fill_include_path(fp: str): + """Temporarily set the Python include path in a file.""" + with open(fp, "r+") as f: + try: + content = f.read() + replaced = content.replace( + PYTHON_INCLUDE_PATH_PLACEHOLDER, + Path(sysconfig.get_paths()['include']).as_posix(), + ) + f.seek(0) + f.write(replaced) + f.truncate() + yield + finally: + # revert to the original content after exit + f.seek(0) + f.write(content) + f.truncate() + + +class BazelExtension(setuptools.Extension): + """A C/C++ extension that is defined as a Bazel BUILD target.""" + + def __init__(self, name: str, bazel_target: str): + super().__init__(name=name, sources=[]) + + self.bazel_target = bazel_target + stripped_target = bazel_target.split("//")[-1] + self.relpath, self.target_name = stripped_target.split(":") + + +class BuildBazelExtension(build_ext.build_ext): + """A command that runs Bazel to build a C/C++ extension.""" + + def run(self): + for ext in self.extensions: + self.bazel_build(ext) + build_ext.build_ext.run(self) + + def bazel_build(self, ext: BazelExtension): + """Runs the bazel build to create the package.""" + with temp_fill_include_path("WORKSPACE"): + temp_path = Path(self.build_temp) + + bazel_argv = [ + "bazel", + "build", + ext.bazel_target, + f"--symlink_prefix={temp_path / 'bazel-'}", + f"--compilation_mode={'dbg' if self.debug else 'opt'}", + # C++17 is required by nanobind + f"--cxxopt={'/std:c++17' if IS_WINDOWS else '-std=c++17'}", + ] + + if IS_WINDOWS: + # Link with python*.lib. + for library_dir in self.library_dirs: + bazel_argv.append("--linkopt=/LIBPATH:" + library_dir) + elif IS_MAC: + if platform.machine() == "x86_64": + # C++17 needs macOS 10.14 at minimum + bazel_argv.append("--macos_minimum_os=10.14") + + # cross-compilation for Mac ARM64 on GitHub Mac x86 runners. + # ARCHFLAGS is set by cibuildwheel before macOS wheel builds. + archflags = os.getenv("ARCHFLAGS", "") + if "arm64" in archflags: + bazel_argv.append("--cpu=darwin_arm64") + bazel_argv.append("--macos_cpus=arm64") + + elif platform.machine() == "arm64": + bazel_argv.append("--macos_minimum_os=11.0") + + self.spawn(bazel_argv) + + shared_lib_suffix = '.dll' if IS_WINDOWS else '.so' + ext_name = ext.target_name + shared_lib_suffix + ext_bazel_bin_path = temp_path / 'bazel-bin' / ext.relpath / ext_name + + ext_dest_path = Path(self.get_ext_fullpath(ext.name)) + shutil.copyfile(ext_bazel_bin_path, ext_dest_path) + + # explicitly call `bazel shutdown` for graceful exit + self.spawn(["bazel", "shutdown"]) + + +setuptools.setup( + name="google_benchmark", + version=_get_version("bindings/python/google_benchmark/__init__.py"), + url="https://github.com/google/benchmark", + description="A library to benchmark code snippets.", + long_description=_get_long_description("README.md"), + long_description_content_type="text/markdown", + author="Google", + author_email="benchmark-py@google.com", + # Contained modules and scripts. + package_dir={"": "bindings/python"}, + packages=setuptools.find_packages("bindings/python"), + install_requires=_parse_requirements("bindings/python/requirements.txt"), + cmdclass=dict(build_ext=BuildBazelExtension), + ext_modules=[ + BazelExtension( + "google_benchmark._benchmark", + "//bindings/python/google_benchmark:_benchmark", + ) + ], + zip_safe=False, + # PyPI package information. + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Topic :: Software Development :: Testing", + "Topic :: System :: Benchmark", + ], + license="Apache 2.0", + keywords="benchmark", +) diff --git a/thirdparty_builtin/benchmark-1.5.0/src/CMakeLists.txt b/thirdparty_builtin/benchmark-1.8.0/src/CMakeLists.txt similarity index 51% rename from thirdparty_builtin/benchmark-1.5.0/src/CMakeLists.txt rename to thirdparty_builtin/benchmark-1.8.0/src/CMakeLists.txt index b47de6791..91ea5f42b 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/CMakeLists.txt +++ b/thirdparty_builtin/benchmark-1.8.0/src/CMakeLists.txt @@ -18,74 +18,97 @@ foreach(item ${BENCHMARK_MAIN}) endforeach() add_library(benchmark ${SOURCE_FILES}) +add_library(benchmark::benchmark ALIAS benchmark) set_target_properties(benchmark PROPERTIES OUTPUT_NAME "benchmark" VERSION ${GENERIC_LIB_VERSION} SOVERSION ${GENERIC_LIB_SOVERSION} ) target_include_directories(benchmark PUBLIC - $ - ) + $ +) -# Link threads. -target_link_libraries(benchmark ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) -find_library(LIBRT rt) -if(LIBRT) - target_link_libraries(benchmark ${LIBRT}) +# libpfm, if available +if (HAVE_LIBPFM) + target_link_libraries(benchmark PRIVATE pfm) + target_compile_definitions(benchmark PRIVATE -DHAVE_LIBPFM) endif() -if(CMAKE_BUILD_TYPE) - string(TOUPPER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_UPPER) -endif() -if(NOT CMAKE_THREAD_LIBS_INIT AND "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE_UPPER}}" MATCHES ".*-fsanitize=[^ ]*address.*") - message(WARNING "CMake's FindThreads.cmake did not fail, but CMAKE_THREAD_LIBS_INIT ended up being empty. This was fixed in https://github.com/Kitware/CMake/commit/d53317130e84898c5328c237186dbd995aaf1c12 Let's guess that -pthread is sufficient.") - target_link_libraries(benchmark -pthread) +# pthread affinity, if available +if(HAVE_PTHREAD_AFFINITY) + target_compile_definitions(benchmark PRIVATE -DBENCHMARK_HAS_PTHREAD_AFFINITY) endif() +# Link threads. +target_link_libraries(benchmark PRIVATE Threads::Threads) + +target_link_libraries(benchmark PRIVATE ${BENCHMARK_CXX_LIBRARIES}) + +if(HAVE_LIB_RT) + target_link_libraries(benchmark PRIVATE rt) +endif(HAVE_LIB_RT) + + # We need extra libraries on Windows if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - target_link_libraries(benchmark Shlwapi) + target_link_libraries(benchmark PRIVATE shlwapi) endif() # We need extra libraries on Solaris if(${CMAKE_SYSTEM_NAME} MATCHES "SunOS") - target_link_libraries(benchmark kstat) + target_link_libraries(benchmark PRIVATE kstat) +endif() + +if (NOT BUILD_SHARED_LIBS) + target_compile_definitions(benchmark PUBLIC -DBENCHMARK_STATIC_DEFINE) endif() # Benchmark main library add_library(benchmark_main "benchmark_main.cc") +add_library(benchmark::benchmark_main ALIAS benchmark_main) set_target_properties(benchmark_main PROPERTIES OUTPUT_NAME "benchmark_main" VERSION ${GENERIC_LIB_VERSION} SOVERSION ${GENERIC_LIB_SOVERSION} + DEFINE_SYMBOL benchmark_EXPORTS ) -target_include_directories(benchmark PUBLIC - $ - ) -target_link_libraries(benchmark_main benchmark) - +target_link_libraries(benchmark_main PUBLIC benchmark::benchmark) -set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") +set(generated_dir "${PROJECT_BINARY_DIR}") set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake") set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake") set(pkg_config "${generated_dir}/${PROJECT_NAME}.pc") +set(targets_to_export benchmark benchmark_main) set(targets_export_name "${PROJECT_NAME}Targets") set(namespace "${PROJECT_NAME}::") include(CMakePackageConfigHelpers) + +configure_package_config_file ( + ${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in + ${project_config} + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + NO_SET_AND_CHECK_MACRO + NO_CHECK_REQUIRED_COMPONENTS_MACRO +) write_basic_package_version_file( "${version_config}" VERSION ${GENERIC_LIB_VERSION} COMPATIBILITY SameMajorVersion ) -configure_file("${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in" "${project_config}" @ONLY) configure_file("${PROJECT_SOURCE_DIR}/cmake/benchmark.pc.in" "${pkg_config}" @ONLY) +export ( + TARGETS ${targets_to_export} + NAMESPACE "${namespace}" + FILE ${generated_dir}/${targets_export_name}.cmake +) + if (BENCHMARK_ENABLE_INSTALL) # Install target (will install the library to specified CMAKE_INSTALL_PREFIX variable) install( - TARGETS benchmark benchmark_main + TARGETS ${targets_to_export} EXPORT ${targets_export_name} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} @@ -94,6 +117,7 @@ if (BENCHMARK_ENABLE_INSTALL) install( DIRECTORY "${PROJECT_SOURCE_DIR}/include/benchmark" + "${PROJECT_BINARY_DIR}/include/benchmark" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.*h") @@ -110,3 +134,37 @@ if (BENCHMARK_ENABLE_INSTALL) NAMESPACE "${namespace}" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") endif() + +if (BENCHMARK_ENABLE_DOXYGEN) + find_package(Doxygen REQUIRED) + set(DOXYGEN_QUIET YES) + set(DOXYGEN_RECURSIVE YES) + set(DOXYGEN_GENERATE_HTML YES) + set(DOXYGEN_GENERATE_MAN NO) + set(DOXYGEN_MARKDOWN_SUPPORT YES) + set(DOXYGEN_BUILTIN_STL_SUPPORT YES) + set(DOXYGEN_EXTRACT_PACKAGE YES) + set(DOXYGEN_EXTRACT_STATIC YES) + set(DOXYGEN_SHOW_INCLUDE_FILES YES) + set(DOXYGEN_BINARY_TOC YES) + set(DOXYGEN_TOC_EXPAND YES) + set(DOXYGEN_USE_MDFILE_AS_MAINPAGE "index.md") + doxygen_add_docs(benchmark_doxygen + docs + include + src + ALL + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + COMMENT "Building documentation with Doxygen.") + if (BENCHMARK_ENABLE_INSTALL AND BENCHMARK_INSTALL_DOCS) + install( + DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/html/" + DESTINATION ${CMAKE_INSTALL_DOCDIR}) + endif() +else() + if (BENCHMARK_ENABLE_INSTALL AND BENCHMARK_INSTALL_DOCS) + install( + DIRECTORY "${PROJECT_SOURCE_DIR}/docs/" + DESTINATION ${CMAKE_INSTALL_DOCDIR}) + endif() +endif() diff --git a/thirdparty_builtin/benchmark-1.5.0/src/arraysize.h b/thirdparty_builtin/benchmark-1.8.0/src/arraysize.h similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/src/arraysize.h rename to thirdparty_builtin/benchmark-1.8.0/src/arraysize.h diff --git a/thirdparty_builtin/benchmark-1.8.0/src/benchmark.cc b/thirdparty_builtin/benchmark-1.8.0/src/benchmark.cc new file mode 100644 index 000000000..f1633b703 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark.cc @@ -0,0 +1,765 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "benchmark/benchmark.h" + +#include "benchmark_api_internal.h" +#include "benchmark_runner.h" +#include "internal_macros.h" + +#ifndef BENCHMARK_OS_WINDOWS +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +#include +#endif +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "check.h" +#include "colorprint.h" +#include "commandlineflags.h" +#include "complexity.h" +#include "counter.h" +#include "internal_macros.h" +#include "log.h" +#include "mutex.h" +#include "perf_counters.h" +#include "re.h" +#include "statistics.h" +#include "string_util.h" +#include "thread_manager.h" +#include "thread_timer.h" + +namespace benchmark { +// Print a list of benchmarks. This option overrides all other options. +BM_DEFINE_bool(benchmark_list_tests, false); + +// A regular expression that specifies the set of benchmarks to execute. If +// this flag is empty, or if this flag is the string \"all\", all benchmarks +// linked into the binary are run. +BM_DEFINE_string(benchmark_filter, ""); + +// Specification of how long to run the benchmark. +// +// It can be either an exact number of iterations (specified as `x`), +// or a minimum number of seconds (specified as `s`). If the latter +// format (ie., min seconds) is used, the system may run the benchmark longer +// until the results are considered significant. +// +// For backward compatibility, the `s` suffix may be omitted, in which case, +// the specified number is interpreted as the number of seconds. +// +// For cpu-time based tests, this is the lower bound +// on the total cpu time used by all threads that make up the test. For +// real-time based tests, this is the lower bound on the elapsed time of the +// benchmark execution, regardless of number of threads. +BM_DEFINE_string(benchmark_min_time, kDefaultMinTimeStr); + +// Minimum number of seconds a benchmark should be run before results should be +// taken into account. This e.g can be necessary for benchmarks of code which +// needs to fill some form of cache before performance is of interest. +// Note: results gathered within this period are discarded and not used for +// reported result. +BM_DEFINE_double(benchmark_min_warmup_time, 0.0); + +// The number of runs of each benchmark. If greater than 1, the mean and +// standard deviation of the runs will be reported. +BM_DEFINE_int32(benchmark_repetitions, 1); + +// If set, enable random interleaving of repetitions of all benchmarks. +// See http://github.com/google/benchmark/issues/1051 for details. +BM_DEFINE_bool(benchmark_enable_random_interleaving, false); + +// Report the result of each benchmark repetitions. When 'true' is specified +// only the mean, standard deviation, and other statistics are reported for +// repeated benchmarks. Affects all reporters. +BM_DEFINE_bool(benchmark_report_aggregates_only, false); + +// Display the result of each benchmark repetitions. When 'true' is specified +// only the mean, standard deviation, and other statistics are displayed for +// repeated benchmarks. Unlike benchmark_report_aggregates_only, only affects +// the display reporter, but *NOT* file reporter, which will still contain +// all the output. +BM_DEFINE_bool(benchmark_display_aggregates_only, false); + +// The format to use for console output. +// Valid values are 'console', 'json', or 'csv'. +BM_DEFINE_string(benchmark_format, "console"); + +// The format to use for file output. +// Valid values are 'console', 'json', or 'csv'. +BM_DEFINE_string(benchmark_out_format, "json"); + +// The file to write additional output to. +BM_DEFINE_string(benchmark_out, ""); + +// Whether to use colors in the output. Valid values: +// 'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use colors if +// the output is being sent to a terminal and the TERM environment variable is +// set to a terminal type that supports colors. +BM_DEFINE_string(benchmark_color, "auto"); + +// Whether to use tabular format when printing user counters to the console. +// Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to false. +BM_DEFINE_bool(benchmark_counters_tabular, false); + +// List of additional perf counters to collect, in libpfm format. For more +// information about libpfm: https://man7.org/linux/man-pages/man3/libpfm.3.html +BM_DEFINE_string(benchmark_perf_counters, ""); + +// Extra context to include in the output formatted as comma-separated key-value +// pairs. Kept internal as it's only used for parsing from env/command line. +BM_DEFINE_kvpairs(benchmark_context, {}); + +// Set the default time unit to use for reports +// Valid values are 'ns', 'us', 'ms' or 's' +BM_DEFINE_string(benchmark_time_unit, ""); + +// The level of verbose logging to output +BM_DEFINE_int32(v, 0); + +namespace internal { + +std::map* global_context = nullptr; + +BENCHMARK_EXPORT std::map*& GetGlobalContext() { + return global_context; +} + +// FIXME: wouldn't LTO mess this up? +void UseCharPointer(char const volatile*) {} + +} // namespace internal + +State::State(std::string name, IterationCount max_iters, + const std::vector& ranges, int thread_i, int n_threads, + internal::ThreadTimer* timer, internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement) + : total_iterations_(0), + batch_leftover_(0), + max_iterations(max_iters), + started_(false), + finished_(false), + skipped_(internal::NotSkipped), + range_(ranges), + complexity_n_(0), + name_(std::move(name)), + thread_index_(thread_i), + threads_(n_threads), + timer_(timer), + manager_(manager), + perf_counters_measurement_(perf_counters_measurement) { + BM_CHECK(max_iterations != 0) << "At least one iteration must be run"; + BM_CHECK_LT(thread_index_, threads_) + << "thread_index must be less than threads"; + + // Note: The use of offsetof below is technically undefined until C++17 + // because State is not a standard layout type. However, all compilers + // currently provide well-defined behavior as an extension (which is + // demonstrated since constexpr evaluation must diagnose all undefined + // behavior). However, GCC and Clang also warn about this use of offsetof, + // which must be suppressed. +#if defined(__INTEL_COMPILER) +#pragma warning push +#pragma warning(disable : 1875) +#elif defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Winvalid-offsetof" +#endif +#if defined(__NVCC__) +#pragma nv_diagnostic push +#pragma nv_diag_suppress 1427 +#endif +#if defined(__NVCOMPILER) +#pragma diagnostic push +#pragma diag_suppress offset_in_non_POD_nonstandard +#endif + // Offset tests to ensure commonly accessed data is on the first cache line. + const int cache_line_size = 64; + static_assert( + offsetof(State, skipped_) <= (cache_line_size - sizeof(skipped_)), ""); +#if defined(__INTEL_COMPILER) +#pragma warning pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif +#if defined(__NVCC__) +#pragma nv_diagnostic pop +#endif +#if defined(__NVCOMPILER) +#pragma diagnostic pop +#endif +} + +void State::PauseTiming() { + // Add in time accumulated so far + BM_CHECK(started_ && !finished_ && !skipped()); + timer_->StopTimer(); + if (perf_counters_measurement_) { + std::vector> measurements; + if (!perf_counters_measurement_->Stop(measurements)) { + BM_CHECK(false) << "Perf counters read the value failed."; + } + for (const auto& name_and_measurement : measurements) { + auto name = name_and_measurement.first; + auto measurement = name_and_measurement.second; + BM_CHECK_EQ(std::fpclassify((double)counters[name]), FP_ZERO); + counters[name] = Counter(measurement, Counter::kAvgIterations); + } + } +} + +void State::ResumeTiming() { + BM_CHECK(started_ && !finished_ && !skipped()); + timer_->StartTimer(); + if (perf_counters_measurement_) { + perf_counters_measurement_->Start(); + } +} + +void State::SkipWithMessage(const std::string& msg) { + skipped_ = internal::SkippedWithMessage; + { + MutexLock l(manager_->GetBenchmarkMutex()); + if (internal::NotSkipped == manager_->results.skipped_) { + manager_->results.skip_message_ = msg; + manager_->results.skipped_ = skipped_; + } + } + total_iterations_ = 0; + if (timer_->running()) timer_->StopTimer(); +} + +void State::SkipWithError(const std::string& msg) { + skipped_ = internal::SkippedWithError; + { + MutexLock l(manager_->GetBenchmarkMutex()); + if (internal::NotSkipped == manager_->results.skipped_) { + manager_->results.skip_message_ = msg; + manager_->results.skipped_ = skipped_; + } + } + total_iterations_ = 0; + if (timer_->running()) timer_->StopTimer(); +} + +void State::SetIterationTime(double seconds) { + timer_->SetIterationTime(seconds); +} + +void State::SetLabel(const std::string& label) { + MutexLock l(manager_->GetBenchmarkMutex()); + manager_->results.report_label_ = label; +} + +void State::StartKeepRunning() { + BM_CHECK(!started_ && !finished_); + started_ = true; + total_iterations_ = skipped() ? 0 : max_iterations; + manager_->StartStopBarrier(); + if (!skipped()) ResumeTiming(); +} + +void State::FinishKeepRunning() { + BM_CHECK(started_ && (!finished_ || skipped())); + if (!skipped()) { + PauseTiming(); + } + // Total iterations has now wrapped around past 0. Fix this. + total_iterations_ = 0; + finished_ = true; + manager_->StartStopBarrier(); +} + +namespace internal { +namespace { + +// Flushes streams after invoking reporter methods that write to them. This +// ensures users get timely updates even when streams are not line-buffered. +void FlushStreams(BenchmarkReporter* reporter) { + if (!reporter) return; + std::flush(reporter->GetOutputStream()); + std::flush(reporter->GetErrorStream()); +} + +// Reports in both display and file reporters. +void Report(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter, const RunResults& run_results) { + auto report_one = [](BenchmarkReporter* reporter, bool aggregates_only, + const RunResults& results) { + assert(reporter); + // If there are no aggregates, do output non-aggregates. + aggregates_only &= !results.aggregates_only.empty(); + if (!aggregates_only) reporter->ReportRuns(results.non_aggregates); + if (!results.aggregates_only.empty()) + reporter->ReportRuns(results.aggregates_only); + }; + + report_one(display_reporter, run_results.display_report_aggregates_only, + run_results); + if (file_reporter) + report_one(file_reporter, run_results.file_report_aggregates_only, + run_results); + + FlushStreams(display_reporter); + FlushStreams(file_reporter); +} + +void RunBenchmarks(const std::vector& benchmarks, + BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter) { + // Note the file_reporter can be null. + BM_CHECK(display_reporter != nullptr); + + // Determine the width of the name field using a minimum width of 10. + bool might_have_aggregates = FLAGS_benchmark_repetitions > 1; + size_t name_field_width = 10; + size_t stat_field_width = 0; + for (const BenchmarkInstance& benchmark : benchmarks) { + name_field_width = + std::max(name_field_width, benchmark.name().str().size()); + might_have_aggregates |= benchmark.repetitions() > 1; + + for (const auto& Stat : benchmark.statistics()) + stat_field_width = std::max(stat_field_width, Stat.name_.size()); + } + if (might_have_aggregates) name_field_width += 1 + stat_field_width; + + // Print header here + BenchmarkReporter::Context context; + context.name_field_width = name_field_width; + + // Keep track of running times of all instances of each benchmark family. + std::map + per_family_reports; + + if (display_reporter->ReportContext(context) && + (!file_reporter || file_reporter->ReportContext(context))) { + FlushStreams(display_reporter); + FlushStreams(file_reporter); + + size_t num_repetitions_total = 0; + + // This perfcounters object needs to be created before the runners vector + // below so it outlasts their lifetime. + PerfCountersMeasurement perfcounters( + StrSplit(FLAGS_benchmark_perf_counters, ',')); + + // Vector of benchmarks to run + std::vector runners; + runners.reserve(benchmarks.size()); + + // Count the number of benchmarks with threads to warn the user in case + // performance counters are used. + int benchmarks_with_threads = 0; + + // Loop through all benchmarks + for (const BenchmarkInstance& benchmark : benchmarks) { + BenchmarkReporter::PerFamilyRunReports* reports_for_family = nullptr; + if (benchmark.complexity() != oNone) + reports_for_family = &per_family_reports[benchmark.family_index()]; + benchmarks_with_threads += (benchmark.threads() > 0); + runners.emplace_back(benchmark, &perfcounters, reports_for_family); + int num_repeats_of_this_instance = runners.back().GetNumRepeats(); + num_repetitions_total += num_repeats_of_this_instance; + if (reports_for_family) + reports_for_family->num_runs_total += num_repeats_of_this_instance; + } + assert(runners.size() == benchmarks.size() && "Unexpected runner count."); + + // The use of performance counters with threads would be unintuitive for + // the average user so we need to warn them about this case + if ((benchmarks_with_threads > 0) && (perfcounters.num_counters() > 0)) { + GetErrorLogInstance() + << "***WARNING*** There are " << benchmarks_with_threads + << " benchmarks with threads and " << perfcounters.num_counters() + << " performance counters were requested. Beware counters will " + "reflect the combined usage across all " + "threads.\n"; + } + + std::vector repetition_indices; + repetition_indices.reserve(num_repetitions_total); + for (size_t runner_index = 0, num_runners = runners.size(); + runner_index != num_runners; ++runner_index) { + const internal::BenchmarkRunner& runner = runners[runner_index]; + std::fill_n(std::back_inserter(repetition_indices), + runner.GetNumRepeats(), runner_index); + } + assert(repetition_indices.size() == num_repetitions_total && + "Unexpected number of repetition indexes."); + + if (FLAGS_benchmark_enable_random_interleaving) { + std::random_device rd; + std::mt19937 g(rd()); + std::shuffle(repetition_indices.begin(), repetition_indices.end(), g); + } + + for (size_t repetition_index : repetition_indices) { + internal::BenchmarkRunner& runner = runners[repetition_index]; + runner.DoOneRepetition(); + if (runner.HasRepeatsRemaining()) continue; + // FIXME: report each repetition separately, not all of them in bulk. + + display_reporter->ReportRunsConfig( + runner.GetMinTime(), runner.HasExplicitIters(), runner.GetIters()); + if (file_reporter) + file_reporter->ReportRunsConfig( + runner.GetMinTime(), runner.HasExplicitIters(), runner.GetIters()); + + RunResults run_results = runner.GetResults(); + + // Maybe calculate complexity report + if (const auto* reports_for_family = runner.GetReportsForFamily()) { + if (reports_for_family->num_runs_done == + reports_for_family->num_runs_total) { + auto additional_run_stats = ComputeBigO(reports_for_family->Runs); + run_results.aggregates_only.insert(run_results.aggregates_only.end(), + additional_run_stats.begin(), + additional_run_stats.end()); + per_family_reports.erase( + static_cast(reports_for_family->Runs.front().family_index)); + } + } + + Report(display_reporter, file_reporter, run_results); + } + } + display_reporter->Finalize(); + if (file_reporter) file_reporter->Finalize(); + FlushStreams(display_reporter); + FlushStreams(file_reporter); +} + +// Disable deprecated warnings temporarily because we need to reference +// CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations +BENCHMARK_DISABLE_DEPRECATED_WARNING + +std::unique_ptr CreateReporter( + std::string const& name, ConsoleReporter::OutputOptions output_opts) { + typedef std::unique_ptr PtrType; + if (name == "console") { + return PtrType(new ConsoleReporter(output_opts)); + } + if (name == "json") { + return PtrType(new JSONReporter()); + } + if (name == "csv") { + return PtrType(new CSVReporter()); + } + std::cerr << "Unexpected format: '" << name << "'\n"; + std::exit(1); +} + +BENCHMARK_RESTORE_DEPRECATED_WARNING + +} // end namespace + +bool IsZero(double n) { + return std::abs(n) < std::numeric_limits::epsilon(); +} + +ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) { + int output_opts = ConsoleReporter::OO_Defaults; + auto is_benchmark_color = [force_no_color]() -> bool { + if (force_no_color) { + return false; + } + if (FLAGS_benchmark_color == "auto") { + return IsColorTerminal(); + } + return IsTruthyFlagValue(FLAGS_benchmark_color); + }; + if (is_benchmark_color()) { + output_opts |= ConsoleReporter::OO_Color; + } else { + output_opts &= ~ConsoleReporter::OO_Color; + } + if (FLAGS_benchmark_counters_tabular) { + output_opts |= ConsoleReporter::OO_Tabular; + } else { + output_opts &= ~ConsoleReporter::OO_Tabular; + } + return static_cast(output_opts); +} + +} // end namespace internal + +BenchmarkReporter* CreateDefaultDisplayReporter() { + static auto default_display_reporter = + internal::CreateReporter(FLAGS_benchmark_format, + internal::GetOutputOptions()) + .release(); + return default_display_reporter; +} + +size_t RunSpecifiedBenchmarks() { + return RunSpecifiedBenchmarks(nullptr, nullptr, FLAGS_benchmark_filter); +} + +size_t RunSpecifiedBenchmarks(std::string spec) { + return RunSpecifiedBenchmarks(nullptr, nullptr, std::move(spec)); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) { + return RunSpecifiedBenchmarks(display_reporter, nullptr, + FLAGS_benchmark_filter); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + std::string spec) { + return RunSpecifiedBenchmarks(display_reporter, nullptr, std::move(spec)); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter) { + return RunSpecifiedBenchmarks(display_reporter, file_reporter, + FLAGS_benchmark_filter); +} + +size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, + BenchmarkReporter* file_reporter, + std::string spec) { + if (spec.empty() || spec == "all") + spec = "."; // Regexp that matches all benchmarks + + // Setup the reporters + std::ofstream output_file; + std::unique_ptr default_display_reporter; + std::unique_ptr default_file_reporter; + if (!display_reporter) { + default_display_reporter.reset(CreateDefaultDisplayReporter()); + display_reporter = default_display_reporter.get(); + } + auto& Out = display_reporter->GetOutputStream(); + auto& Err = display_reporter->GetErrorStream(); + + std::string const& fname = FLAGS_benchmark_out; + if (fname.empty() && file_reporter) { + Err << "A custom file reporter was provided but " + "--benchmark_out= was not specified." + << std::endl; + std::exit(1); + } + if (!fname.empty()) { + output_file.open(fname); + if (!output_file.is_open()) { + Err << "invalid file name: '" << fname << "'" << std::endl; + std::exit(1); + } + if (!file_reporter) { + default_file_reporter = internal::CreateReporter( + FLAGS_benchmark_out_format, ConsoleReporter::OO_None); + file_reporter = default_file_reporter.get(); + } + file_reporter->SetOutputStream(&output_file); + file_reporter->SetErrorStream(&output_file); + } + + std::vector benchmarks; + if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0; + + if (benchmarks.empty()) { + Err << "Failed to match any benchmarks against regex: " << spec << "\n"; + return 0; + } + + if (FLAGS_benchmark_list_tests) { + for (auto const& benchmark : benchmarks) + Out << benchmark.name().str() << "\n"; + } else { + internal::RunBenchmarks(benchmarks, display_reporter, file_reporter); + } + + return benchmarks.size(); +} + +namespace { +// stores the time unit benchmarks use by default +TimeUnit default_time_unit = kNanosecond; +} // namespace + +TimeUnit GetDefaultTimeUnit() { return default_time_unit; } + +void SetDefaultTimeUnit(TimeUnit unit) { default_time_unit = unit; } + +std::string GetBenchmarkFilter() { return FLAGS_benchmark_filter; } + +void SetBenchmarkFilter(std::string value) { + FLAGS_benchmark_filter = std::move(value); +} + +int32_t GetBenchmarkVerbosity() { return FLAGS_v; } + +void RegisterMemoryManager(MemoryManager* manager) { + internal::memory_manager = manager; +} + +void AddCustomContext(const std::string& key, const std::string& value) { + if (internal::global_context == nullptr) { + internal::global_context = new std::map(); + } + if (!internal::global_context->emplace(key, value).second) { + std::cerr << "Failed to add custom context \"" << key << "\" as it already " + << "exists with value \"" << value << "\"\n"; + } +} + +namespace internal { + +void (*HelperPrintf)(); + +void PrintUsageAndExit() { + HelperPrintf(); + exit(0); +} + +void SetDefaultTimeUnitFromFlag(const std::string& time_unit_flag) { + if (time_unit_flag == "s") { + return SetDefaultTimeUnit(kSecond); + } + if (time_unit_flag == "ms") { + return SetDefaultTimeUnit(kMillisecond); + } + if (time_unit_flag == "us") { + return SetDefaultTimeUnit(kMicrosecond); + } + if (time_unit_flag == "ns") { + return SetDefaultTimeUnit(kNanosecond); + } + if (!time_unit_flag.empty()) { + PrintUsageAndExit(); + } +} + +void ParseCommandLineFlags(int* argc, char** argv) { + using namespace benchmark; + BenchmarkReporter::Context::executable_name = + (argc && *argc > 0) ? argv[0] : "unknown"; + for (int i = 1; argc && i < *argc; ++i) { + if (ParseBoolFlag(argv[i], "benchmark_list_tests", + &FLAGS_benchmark_list_tests) || + ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) || + ParseStringFlag(argv[i], "benchmark_min_time", + &FLAGS_benchmark_min_time) || + ParseDoubleFlag(argv[i], "benchmark_min_warmup_time", + &FLAGS_benchmark_min_warmup_time) || + ParseInt32Flag(argv[i], "benchmark_repetitions", + &FLAGS_benchmark_repetitions) || + ParseBoolFlag(argv[i], "benchmark_enable_random_interleaving", + &FLAGS_benchmark_enable_random_interleaving) || + ParseBoolFlag(argv[i], "benchmark_report_aggregates_only", + &FLAGS_benchmark_report_aggregates_only) || + ParseBoolFlag(argv[i], "benchmark_display_aggregates_only", + &FLAGS_benchmark_display_aggregates_only) || + ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) || + ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) || + ParseStringFlag(argv[i], "benchmark_out_format", + &FLAGS_benchmark_out_format) || + ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) || + ParseBoolFlag(argv[i], "benchmark_counters_tabular", + &FLAGS_benchmark_counters_tabular) || + ParseStringFlag(argv[i], "benchmark_perf_counters", + &FLAGS_benchmark_perf_counters) || + ParseKeyValueFlag(argv[i], "benchmark_context", + &FLAGS_benchmark_context) || + ParseStringFlag(argv[i], "benchmark_time_unit", + &FLAGS_benchmark_time_unit) || + ParseInt32Flag(argv[i], "v", &FLAGS_v)) { + for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1]; + + --(*argc); + --i; + } else if (IsFlag(argv[i], "help")) { + PrintUsageAndExit(); + } + } + for (auto const* flag : + {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format}) { + if (*flag != "console" && *flag != "json" && *flag != "csv") { + PrintUsageAndExit(); + } + } + SetDefaultTimeUnitFromFlag(FLAGS_benchmark_time_unit); + if (FLAGS_benchmark_color.empty()) { + PrintUsageAndExit(); + } + for (const auto& kv : FLAGS_benchmark_context) { + AddCustomContext(kv.first, kv.second); + } +} + +int InitializeStreams() { + static std::ios_base::Init init; + return 0; +} + +} // end namespace internal + +void PrintDefaultHelp() { + fprintf(stdout, + "benchmark" + " [--benchmark_list_tests={true|false}]\n" + " [--benchmark_filter=]\n" + " [--benchmark_min_time=`x` OR `s` ]\n" + " [--benchmark_min_warmup_time=]\n" + " [--benchmark_repetitions=]\n" + " [--benchmark_enable_random_interleaving={true|false}]\n" + " [--benchmark_report_aggregates_only={true|false}]\n" + " [--benchmark_display_aggregates_only={true|false}]\n" + " [--benchmark_format=]\n" + " [--benchmark_out=]\n" + " [--benchmark_out_format=]\n" + " [--benchmark_color={auto|true|false}]\n" + " [--benchmark_counters_tabular={true|false}]\n" +#if defined HAVE_LIBPFM + " [--benchmark_perf_counters=,...]\n" +#endif + " [--benchmark_context==,...]\n" + " [--benchmark_time_unit={ns|us|ms|s}]\n" + " [--v=]\n"); +} + +void Initialize(int* argc, char** argv, void (*HelperPrintf)()) { + internal::HelperPrintf = HelperPrintf; + internal::ParseCommandLineFlags(argc, argv); + internal::LogLevel() = FLAGS_v; +} + +void Shutdown() { delete internal::global_context; } + +bool ReportUnrecognizedArguments(int argc, char** argv) { + for (int i = 1; i < argc; ++i) { + fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], + argv[i]); + } + return argc > 1; +} + +} // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/src/benchmark_api_internal.cc b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_api_internal.cc new file mode 100644 index 000000000..286f98653 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_api_internal.cc @@ -0,0 +1,118 @@ +#include "benchmark_api_internal.h" + +#include + +#include "string_util.h" + +namespace benchmark { +namespace internal { + +BenchmarkInstance::BenchmarkInstance(Benchmark* benchmark, int family_idx, + int per_family_instance_idx, + const std::vector& args, + int thread_count) + : benchmark_(*benchmark), + family_index_(family_idx), + per_family_instance_index_(per_family_instance_idx), + aggregation_report_mode_(benchmark_.aggregation_report_mode_), + args_(args), + time_unit_(benchmark_.GetTimeUnit()), + measure_process_cpu_time_(benchmark_.measure_process_cpu_time_), + use_real_time_(benchmark_.use_real_time_), + use_manual_time_(benchmark_.use_manual_time_), + complexity_(benchmark_.complexity_), + complexity_lambda_(benchmark_.complexity_lambda_), + statistics_(benchmark_.statistics_), + repetitions_(benchmark_.repetitions_), + min_time_(benchmark_.min_time_), + min_warmup_time_(benchmark_.min_warmup_time_), + iterations_(benchmark_.iterations_), + threads_(thread_count) { + name_.function_name = benchmark_.name_; + + size_t arg_i = 0; + for (const auto& arg : args) { + if (!name_.args.empty()) { + name_.args += '/'; + } + + if (arg_i < benchmark->arg_names_.size()) { + const auto& arg_name = benchmark_.arg_names_[arg_i]; + if (!arg_name.empty()) { + name_.args += StrFormat("%s:", arg_name.c_str()); + } + } + + name_.args += StrFormat("%" PRId64, arg); + ++arg_i; + } + + if (!IsZero(benchmark->min_time_)) { + name_.min_time = StrFormat("min_time:%0.3f", benchmark_.min_time_); + } + + if (!IsZero(benchmark->min_warmup_time_)) { + name_.min_warmup_time = + StrFormat("min_warmup_time:%0.3f", benchmark_.min_warmup_time_); + } + + if (benchmark_.iterations_ != 0) { + name_.iterations = StrFormat( + "iterations:%lu", static_cast(benchmark_.iterations_)); + } + + if (benchmark_.repetitions_ != 0) { + name_.repetitions = StrFormat("repeats:%d", benchmark_.repetitions_); + } + + if (benchmark_.measure_process_cpu_time_) { + name_.time_type = "process_time"; + } + + if (benchmark_.use_manual_time_) { + if (!name_.time_type.empty()) { + name_.time_type += '/'; + } + name_.time_type += "manual_time"; + } else if (benchmark_.use_real_time_) { + if (!name_.time_type.empty()) { + name_.time_type += '/'; + } + name_.time_type += "real_time"; + } + + if (!benchmark_.thread_counts_.empty()) { + name_.threads = StrFormat("threads:%d", threads_); + } + + setup_ = benchmark_.setup_; + teardown_ = benchmark_.teardown_; +} + +State BenchmarkInstance::Run( + IterationCount iters, int thread_id, internal::ThreadTimer* timer, + internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement) const { + State st(name_.function_name, iters, args_, thread_id, threads_, timer, + manager, perf_counters_measurement); + benchmark_.Run(st); + return st; +} + +void BenchmarkInstance::Setup() const { + if (setup_) { + State st(name_.function_name, /*iters*/ 1, args_, /*thread_id*/ 0, threads_, + nullptr, nullptr, nullptr); + setup_(st); + } +} + +void BenchmarkInstance::Teardown() const { + if (teardown_) { + State st(name_.function_name, /*iters*/ 1, args_, /*thread_id*/ 0, threads_, + nullptr, nullptr, nullptr); + teardown_(st); + } +} +} // namespace internal +} // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/src/benchmark_api_internal.h b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_api_internal.h new file mode 100644 index 000000000..94f516531 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_api_internal.h @@ -0,0 +1,87 @@ +#ifndef BENCHMARK_API_INTERNAL_H +#define BENCHMARK_API_INTERNAL_H + +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "commandlineflags.h" + +namespace benchmark { +namespace internal { + +// Information kept per benchmark we may want to run +class BenchmarkInstance { + public: + BenchmarkInstance(Benchmark* benchmark, int family_index, + int per_family_instance_index, + const std::vector& args, int threads); + + const BenchmarkName& name() const { return name_; } + int family_index() const { return family_index_; } + int per_family_instance_index() const { return per_family_instance_index_; } + AggregationReportMode aggregation_report_mode() const { + return aggregation_report_mode_; + } + TimeUnit time_unit() const { return time_unit_; } + bool measure_process_cpu_time() const { return measure_process_cpu_time_; } + bool use_real_time() const { return use_real_time_; } + bool use_manual_time() const { return use_manual_time_; } + BigO complexity() const { return complexity_; } + BigOFunc* complexity_lambda() const { return complexity_lambda_; } + const std::vector& statistics() const { return statistics_; } + int repetitions() const { return repetitions_; } + double min_time() const { return min_time_; } + double min_warmup_time() const { return min_warmup_time_; } + IterationCount iterations() const { return iterations_; } + int threads() const { return threads_; } + void Setup() const; + void Teardown() const; + + State Run(IterationCount iters, int thread_id, internal::ThreadTimer* timer, + internal::ThreadManager* manager, + internal::PerfCountersMeasurement* perf_counters_measurement) const; + + private: + BenchmarkName name_; + Benchmark& benchmark_; + const int family_index_; + const int per_family_instance_index_; + AggregationReportMode aggregation_report_mode_; + const std::vector& args_; + TimeUnit time_unit_; + bool measure_process_cpu_time_; + bool use_real_time_; + bool use_manual_time_; + BigO complexity_; + BigOFunc* complexity_lambda_; + UserCounters counters_; + const std::vector& statistics_; + int repetitions_; + double min_time_; + double min_warmup_time_; + IterationCount iterations_; + int threads_; // Number of concurrent threads to us + + typedef void (*callback_function)(const benchmark::State&); + callback_function setup_ = nullptr; + callback_function teardown_ = nullptr; +}; + +bool FindBenchmarksInternal(const std::string& re, + std::vector* benchmarks, + std::ostream* Err); + +bool IsZero(double n); + +BENCHMARK_EXPORT +ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color = false); + +} // end namespace internal +} // end namespace benchmark + +#endif // BENCHMARK_API_INTERNAL_H diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_main.cc b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_main.cc similarity index 94% rename from thirdparty_builtin/benchmark-1.5.0/src/benchmark_main.cc rename to thirdparty_builtin/benchmark-1.8.0/src/benchmark_main.cc index b3b247831..cd61cd2ad 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_main.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_main.cc @@ -14,4 +14,5 @@ #include "benchmark/benchmark.h" +BENCHMARK_EXPORT int main(int, char**); BENCHMARK_MAIN(); diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_name.cc b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_name.cc similarity index 91% rename from thirdparty_builtin/benchmark-1.5.0/src/benchmark_name.cc rename to thirdparty_builtin/benchmark-1.8.0/src/benchmark_name.cc index 2a17ebce2..01676bbc8 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_name.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_name.cc @@ -51,8 +51,9 @@ std::string join(char delimiter, const Ts&... ts) { } } // namespace +BENCHMARK_EXPORT std::string BenchmarkName::str() const { - return join('/', function_name, args, min_time, iterations, repetitions, - time_type, threads); + return join('/', function_name, args, min_time, min_warmup_time, iterations, + repetitions, time_type, threads); } } // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_register.cc b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_register.cc similarity index 67% rename from thirdparty_builtin/benchmark-1.5.0/src/benchmark_register.cc rename to thirdparty_builtin/benchmark-1.8.0/src/benchmark_register.cc index 6696c382b..e447c9a2d 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_register.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_register.cc @@ -15,7 +15,7 @@ #include "benchmark_register.h" #ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) #include #endif #include @@ -24,6 +24,7 @@ #include #include +#include #include #include #include @@ -31,12 +32,10 @@ #include #include #include +#include #include #include -#define __STDC_FORMAT_MACROS -#include - #include "benchmark/benchmark.h" #include "benchmark_api_internal.h" #include "check.h" @@ -54,10 +53,13 @@ namespace benchmark { namespace { // For non-dense Range, intermediate values are powers of kRangeMultiplier. -static const int kRangeMultiplier = 8; +static constexpr int kRangeMultiplier = 8; + // The size of a benchmark family determines is the number of inputs to repeat // the benchmark on. If this is "large" then warn the user during configuration. -static const size_t kMaxFamilySize = 100; +static constexpr size_t kMaxFamilySize = 100; + +static constexpr char kDisabledPrefix[] = "DISABLED_"; } // end namespace namespace internal { @@ -112,15 +114,15 @@ void BenchmarkFamilies::ClearBenchmarks() { bool BenchmarkFamilies::FindBenchmarks( std::string spec, std::vector* benchmarks, std::ostream* ErrStream) { - CHECK(ErrStream); + BM_CHECK(ErrStream); auto& Err = *ErrStream; // Make regular expression out of command-line flag std::string error_msg; Regex re; - bool isNegativeFilter = false; + bool is_negative_filter = false; if (spec[0] == '-') { spec.replace(0, 1, ""); - isNegativeFilter = true; + is_negative_filter = true; } if (!re.Init(spec, &error_msg)) { Err << "Could not compile benchmark re: " << error_msg << std::endl; @@ -130,8 +132,13 @@ bool BenchmarkFamilies::FindBenchmarks( // Special list of thread counts to use when none are specified const std::vector one_thread = {1}; + int next_family_index = 0; + MutexLock l(mutex_); for (std::unique_ptr& family : families_) { + int family_index = next_family_index; + int per_family_instance_index = 0; + // Family was deleted or benchmark doesn't match if (!family) continue; @@ -150,85 +157,27 @@ bool BenchmarkFamilies::FindBenchmarks( << " will be repeated at least " << family_size << " times.\n"; } // reserve in the special case the regex ".", since we know the final - // family size. - if (spec == ".") benchmarks->reserve(family_size); + // family size. this doesn't take into account any disabled benchmarks + // so worst case we reserve more than we need. + if (spec == ".") benchmarks->reserve(benchmarks->size() + family_size); for (auto const& args : family->args_) { for (int num_threads : *thread_counts) { - BenchmarkInstance instance; - instance.name.function_name = family->name_; - instance.benchmark = family.get(); - instance.aggregation_report_mode = family->aggregation_report_mode_; - instance.arg = args; - instance.time_unit = family->time_unit_; - instance.range_multiplier = family->range_multiplier_; - instance.min_time = family->min_time_; - instance.iterations = family->iterations_; - instance.repetitions = family->repetitions_; - instance.measure_process_cpu_time = family->measure_process_cpu_time_; - instance.use_real_time = family->use_real_time_; - instance.use_manual_time = family->use_manual_time_; - instance.complexity = family->complexity_; - instance.complexity_lambda = family->complexity_lambda_; - instance.statistics = &family->statistics_; - instance.threads = num_threads; - - // Add arguments to instance name - size_t arg_i = 0; - for (auto const& arg : args) { - if (!instance.name.args.empty()) { - instance.name.args += '/'; - } - - if (arg_i < family->arg_names_.size()) { - const auto& arg_name = family->arg_names_[arg_i]; - if (!arg_name.empty()) { - instance.name.args += StrFormat("%s:", arg_name.c_str()); - } - } - - instance.name.args += StrFormat("%" PRId64, arg); - ++arg_i; - } - - if (!IsZero(family->min_time_)) - instance.name.min_time = - StrFormat("min_time:%0.3f", family->min_time_); - if (family->iterations_ != 0) { - instance.name.iterations = - StrFormat("iterations:%lu", - static_cast(family->iterations_)); - } - if (family->repetitions_ != 0) - instance.name.repetitions = - StrFormat("repeats:%d", family->repetitions_); - - if (family->measure_process_cpu_time_) { - instance.name.time_type = "process_time"; - } - - if (family->use_manual_time_) { - if (!instance.name.time_type.empty()) { - instance.name.time_type += '/'; - } - instance.name.time_type += "manual_time"; - } else if (family->use_real_time_) { - if (!instance.name.time_type.empty()) { - instance.name.time_type += '/'; - } - instance.name.time_type += "real_time"; - } + BenchmarkInstance instance(family.get(), family_index, + per_family_instance_index, args, + num_threads); + + const auto full_name = instance.name().str(); + if (full_name.rfind(kDisabledPrefix, 0) != 0 && + ((re.Match(full_name) && !is_negative_filter) || + (!re.Match(full_name) && is_negative_filter))) { + benchmarks->push_back(std::move(instance)); - // Add the number of threads used to the name - if (!family->thread_counts_.empty()) { - instance.name.threads = StrFormat("threads:%d", instance.threads); - } + ++per_family_instance_index; - const auto full_name = instance.name.str(); - if ((re.Match(full_name) && !isNegativeFilter) || - (!re.Match(full_name) && isNegativeFilter)) { - instance.last_benchmark_instance = (&args == &family->args_.back()); - benchmarks->push_back(std::move(instance)); + // Only bump the next family index once we've estabilished that + // at least one instance of this family will be run. + if (next_family_index == family_index) ++next_family_index; } } } @@ -255,39 +204,50 @@ bool FindBenchmarksInternal(const std::string& re, // Benchmark //=============================================================================// -Benchmark::Benchmark(const char* name) +Benchmark::Benchmark(const std::string& name) : name_(name), aggregation_report_mode_(ARM_Unspecified), - time_unit_(kNanosecond), + time_unit_(GetDefaultTimeUnit()), + use_default_time_unit_(true), range_multiplier_(kRangeMultiplier), min_time_(0), + min_warmup_time_(0), iterations_(0), repetitions_(0), measure_process_cpu_time_(false), use_real_time_(false), use_manual_time_(false), complexity_(oNone), - complexity_lambda_(nullptr) { + complexity_lambda_(nullptr), + setup_(nullptr), + teardown_(nullptr) { ComputeStatistics("mean", StatisticsMean); ComputeStatistics("median", StatisticsMedian); ComputeStatistics("stddev", StatisticsStdDev); + ComputeStatistics("cv", StatisticsCV, kPercentage); } Benchmark::~Benchmark() {} +Benchmark* Benchmark::Name(const std::string& name) { + SetName(name); + return this; +} + Benchmark* Benchmark::Arg(int64_t x) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); args_.push_back({x}); return this; } Benchmark* Benchmark::Unit(TimeUnit unit) { time_unit_ = unit; + use_default_time_unit_ = false; return this; } Benchmark* Benchmark::Range(int64_t start, int64_t limit) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); std::vector arglist; AddRange(&arglist, start, limit, range_multiplier_); @@ -299,53 +259,61 @@ Benchmark* Benchmark::Range(int64_t start, int64_t limit) { Benchmark* Benchmark::Ranges( const std::vector>& ranges) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(ranges.size())); + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(ranges.size())); std::vector> arglists(ranges.size()); - std::size_t total = 1; for (std::size_t i = 0; i < ranges.size(); i++) { AddRange(&arglists[i], ranges[i].first, ranges[i].second, range_multiplier_); - total *= arglists[i].size(); } - std::vector ctr(arglists.size(), 0); + ArgsProduct(arglists); - for (std::size_t i = 0; i < total; i++) { - std::vector tmp; - tmp.reserve(arglists.size()); - - for (std::size_t j = 0; j < arglists.size(); j++) { - tmp.push_back(arglists[j].at(ctr[j])); - } + return this; +} - args_.push_back(std::move(tmp)); +Benchmark* Benchmark::ArgsProduct( + const std::vector>& arglists) { + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(arglists.size())); - for (std::size_t j = 0; j < arglists.size(); j++) { - if (ctr[j] + 1 < arglists[j].size()) { - ++ctr[j]; - break; - } - ctr[j] = 0; + std::vector indices(arglists.size()); + const std::size_t total = std::accumulate( + std::begin(arglists), std::end(arglists), std::size_t{1}, + [](const std::size_t res, const std::vector& arglist) { + return res * arglist.size(); + }); + std::vector args; + args.reserve(arglists.size()); + for (std::size_t i = 0; i < total; i++) { + for (std::size_t arg = 0; arg < arglists.size(); arg++) { + args.push_back(arglists[arg][indices[arg]]); } + args_.push_back(args); + args.clear(); + + std::size_t arg = 0; + do { + indices[arg] = (indices[arg] + 1) % arglists[arg].size(); + } while (indices[arg++] == 0 && arg < arglists.size()); } + return this; } Benchmark* Benchmark::ArgName(const std::string& name) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); arg_names_ = {name}; return this; } Benchmark* Benchmark::ArgNames(const std::vector& names) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(names.size())); + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(names.size())); arg_names_ = names; return this; } Benchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - CHECK_LE(start, limit); + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); + BM_CHECK_LE(start, limit); for (int64_t arg = start; arg <= limit; arg += step) { args_.push_back({arg}); } @@ -353,7 +321,7 @@ Benchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) { } Benchmark* Benchmark::Args(const std::vector& args) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(args.size())); + BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(args.size())); args_.push_back(args); return this; } @@ -363,28 +331,48 @@ Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) { return this; } +Benchmark* Benchmark::Setup(void (*setup)(const benchmark::State&)) { + BM_CHECK(setup != nullptr); + setup_ = setup; + return this; +} + +Benchmark* Benchmark::Teardown(void (*teardown)(const benchmark::State&)) { + BM_CHECK(teardown != nullptr); + teardown_ = teardown; + return this; +} + Benchmark* Benchmark::RangeMultiplier(int multiplier) { - CHECK(multiplier > 1); + BM_CHECK(multiplier > 1); range_multiplier_ = multiplier; return this; } Benchmark* Benchmark::MinTime(double t) { - CHECK(t > 0.0); - CHECK(iterations_ == 0); + BM_CHECK(t > 0.0); + BM_CHECK(iterations_ == 0); min_time_ = t; return this; } +Benchmark* Benchmark::MinWarmUpTime(double t) { + BM_CHECK(t >= 0.0); + BM_CHECK(iterations_ == 0); + min_warmup_time_ = t; + return this; +} + Benchmark* Benchmark::Iterations(IterationCount n) { - CHECK(n > 0); - CHECK(IsZero(min_time_)); + BM_CHECK(n > 0); + BM_CHECK(IsZero(min_time_)); + BM_CHECK(IsZero(min_warmup_time_)); iterations_ = n; return this; } Benchmark* Benchmark::Repetitions(int n) { - CHECK(n > 0); + BM_CHECK(n > 0); repetitions_ = n; return this; } @@ -417,14 +405,14 @@ Benchmark* Benchmark::MeasureProcessCPUTime() { } Benchmark* Benchmark::UseRealTime() { - CHECK(!use_manual_time_) + BM_CHECK(!use_manual_time_) << "Cannot set UseRealTime and UseManualTime simultaneously."; use_real_time_ = true; return this; } Benchmark* Benchmark::UseManualTime() { - CHECK(!use_real_time_) + BM_CHECK(!use_real_time_) << "Cannot set UseRealTime and UseManualTime simultaneously."; use_manual_time_ = true; return this; @@ -441,21 +429,22 @@ Benchmark* Benchmark::Complexity(BigOFunc* complexity) { return this; } -Benchmark* Benchmark::ComputeStatistics(std::string name, - StatisticsFunc* statistics) { - statistics_.emplace_back(name, statistics); +Benchmark* Benchmark::ComputeStatistics(const std::string& name, + StatisticsFunc* statistics, + StatisticUnit unit) { + statistics_.emplace_back(name, statistics, unit); return this; } Benchmark* Benchmark::Threads(int t) { - CHECK_GT(t, 0); + BM_CHECK_GT(t, 0); thread_counts_.push_back(t); return this; } Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) { - CHECK_GT(min_threads, 0); - CHECK_GE(max_threads, min_threads); + BM_CHECK_GT(min_threads, 0); + BM_CHECK_GE(max_threads, min_threads); AddRange(&thread_counts_, min_threads, max_threads, 2); return this; @@ -463,9 +452,9 @@ Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) { Benchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads, int stride) { - CHECK_GT(min_threads, 0); - CHECK_GE(max_threads, min_threads); - CHECK_GE(stride, 1); + BM_CHECK_GT(min_threads, 0); + BM_CHECK_GE(max_threads, min_threads); + BM_CHECK_GE(stride, 1); for (auto i = min_threads; i < max_threads; i += stride) { thread_counts_.push_back(i); @@ -479,7 +468,9 @@ Benchmark* Benchmark::ThreadPerCpu() { return this; } -void Benchmark::SetName(const char* name) { name_ = name; } +void Benchmark::SetName(const std::string& name) { name_ = name; } + +const char* Benchmark::GetName() const { return name_.c_str(); } int Benchmark::ArgsCnt() const { if (args_.empty()) { @@ -489,6 +480,16 @@ int Benchmark::ArgsCnt() const { return static_cast(args_.front().size()); } +const char* Benchmark::GetArgName(int arg) const { + BM_CHECK_GE(arg, 0); + BM_CHECK_LT(arg, static_cast(arg_names_.size())); + return arg_names_[arg].c_str(); +} + +TimeUnit Benchmark::GetTimeUnit() const { + return use_default_time_unit_ ? GetDefaultTimeUnit() : time_unit_; +} + //=============================================================================// // FunctionBenchmark //=============================================================================// @@ -501,4 +502,19 @@ void ClearRegisteredBenchmarks() { internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks(); } +std::vector CreateRange(int64_t lo, int64_t hi, int multi) { + std::vector args; + internal::AddRange(&args, lo, hi, multi); + return args; +} + +std::vector CreateDenseRange(int64_t start, int64_t limit, int step) { + BM_CHECK_LE(start, limit); + std::vector args; + for (int64_t arg = start; arg <= limit; arg += step) { + args.push_back(arg); + } + return args; +} + } // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_register.h b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_register.h similarity index 80% rename from thirdparty_builtin/benchmark-1.5.0/src/benchmark_register.h rename to thirdparty_builtin/benchmark-1.8.0/src/benchmark_register.h index 61377d742..53367c707 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/benchmark_register.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_register.h @@ -1,6 +1,8 @@ #ifndef BENCHMARK_REGISTER_H #define BENCHMARK_REGISTER_H +#include +#include #include #include "check.h" @@ -11,18 +13,18 @@ namespace internal { // Append the powers of 'mult' in the closed interval [lo, hi]. // Returns iterator to the start of the inserted range. template -typename std::vector::iterator -AddPowers(std::vector* dst, T lo, T hi, int mult) { - CHECK_GE(lo, 0); - CHECK_GE(hi, lo); - CHECK_GE(mult, 2); +typename std::vector::iterator AddPowers(std::vector* dst, T lo, T hi, + int mult) { + BM_CHECK_GE(lo, 0); + BM_CHECK_GE(hi, lo); + BM_CHECK_GE(mult, 2); const size_t start_offset = dst->size(); static const T kmax = std::numeric_limits::max(); // Space out the values in multiples of "mult" - for (T i = 1; i <= hi; i *= mult) { + for (T i = static_cast(1); i <= hi; i *= static_cast(mult)) { if (i >= lo) { dst->push_back(i); } @@ -31,16 +33,16 @@ AddPowers(std::vector* dst, T lo, T hi, int mult) { if (i > kmax / mult) break; } - return dst->begin() + start_offset; + return dst->begin() + static_cast(start_offset); } template void AddNegatedPowers(std::vector* dst, T lo, T hi, int mult) { // We negate lo and hi so we require that they cannot be equal to 'min'. - CHECK_GT(lo, std::numeric_limits::min()); - CHECK_GT(hi, std::numeric_limits::min()); - CHECK_GE(hi, lo); - CHECK_LE(hi, 0); + BM_CHECK_GT(lo, std::numeric_limits::min()); + BM_CHECK_GT(hi, std::numeric_limits::min()); + BM_CHECK_GE(hi, lo); + BM_CHECK_LE(hi, 0); // Add positive powers, then negate and reverse. // Casts necessary since small integers get promoted @@ -59,8 +61,8 @@ void AddRange(std::vector* dst, T lo, T hi, int mult) { static_assert(std::is_integral::value && std::is_signed::value, "Args type must be a signed integer"); - CHECK_GE(hi, lo); - CHECK_GE(mult, 2); + BM_CHECK_GE(hi, lo); + BM_CHECK_GE(mult, 2); // Add "lo" dst->push_back(lo); @@ -86,7 +88,7 @@ void AddRange(std::vector* dst, T lo, T hi, int mult) { } // Treat 0 as a special case (see discussion on #762). - if (lo <= 0 && hi >= 0) { + if (lo < 0 && hi >= 0) { dst->push_back(0); } diff --git a/thirdparty_builtin/benchmark-1.8.0/src/benchmark_runner.cc b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_runner.cc new file mode 100644 index 000000000..f7ae42439 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_runner.cc @@ -0,0 +1,497 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "benchmark_runner.h" + +#include "benchmark/benchmark.h" +#include "benchmark_api_internal.h" +#include "internal_macros.h" + +#ifndef BENCHMARK_OS_WINDOWS +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) +#include +#endif +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "check.h" +#include "colorprint.h" +#include "commandlineflags.h" +#include "complexity.h" +#include "counter.h" +#include "internal_macros.h" +#include "log.h" +#include "mutex.h" +#include "perf_counters.h" +#include "re.h" +#include "statistics.h" +#include "string_util.h" +#include "thread_manager.h" +#include "thread_timer.h" + +namespace benchmark { + +namespace internal { + +MemoryManager* memory_manager = nullptr; + +namespace { + +static constexpr IterationCount kMaxIterations = 1000000000; +const double kDefaultMinTime = + std::strtod(::benchmark::kDefaultMinTimeStr, /*p_end*/ nullptr); + +BenchmarkReporter::Run CreateRunReport( + const benchmark::internal::BenchmarkInstance& b, + const internal::ThreadManager::Result& results, + IterationCount memory_iterations, + const MemoryManager::Result* memory_result, double seconds, + int64_t repetition_index, int64_t repeats) { + // Create report about this benchmark run. + BenchmarkReporter::Run report; + + report.run_name = b.name(); + report.family_index = b.family_index(); + report.per_family_instance_index = b.per_family_instance_index(); + report.skipped = results.skipped_; + report.skip_message = results.skip_message_; + report.report_label = results.report_label_; + // This is the total iterations across all threads. + report.iterations = results.iterations; + report.time_unit = b.time_unit(); + report.threads = b.threads(); + report.repetition_index = repetition_index; + report.repetitions = repeats; + + if (!report.skipped) { + if (b.use_manual_time()) { + report.real_accumulated_time = results.manual_time_used; + } else { + report.real_accumulated_time = results.real_time_used; + } + report.cpu_accumulated_time = results.cpu_time_used; + report.complexity_n = results.complexity_n; + report.complexity = b.complexity(); + report.complexity_lambda = b.complexity_lambda(); + report.statistics = &b.statistics(); + report.counters = results.counters; + + if (memory_iterations > 0) { + assert(memory_result != nullptr); + report.memory_result = memory_result; + report.allocs_per_iter = + memory_iterations ? static_cast(memory_result->num_allocs) / + memory_iterations + : 0; + } + + internal::Finish(&report.counters, results.iterations, seconds, + b.threads()); + } + return report; +} + +// Execute one thread of benchmark b for the specified number of iterations. +// Adds the stats collected for the thread into manager->results. +void RunInThread(const BenchmarkInstance* b, IterationCount iters, + int thread_id, ThreadManager* manager, + PerfCountersMeasurement* perf_counters_measurement) { + internal::ThreadTimer timer( + b->measure_process_cpu_time() + ? internal::ThreadTimer::CreateProcessCpuTime() + : internal::ThreadTimer::Create()); + + State st = + b->Run(iters, thread_id, &timer, manager, perf_counters_measurement); + BM_CHECK(st.skipped() || st.iterations() >= st.max_iterations) + << "Benchmark returned before State::KeepRunning() returned false!"; + { + MutexLock l(manager->GetBenchmarkMutex()); + internal::ThreadManager::Result& results = manager->results; + results.iterations += st.iterations(); + results.cpu_time_used += timer.cpu_time_used(); + results.real_time_used += timer.real_time_used(); + results.manual_time_used += timer.manual_time_used(); + results.complexity_n += st.complexity_length_n(); + internal::Increment(&results.counters, st.counters); + } + manager->NotifyThreadComplete(); +} + +double ComputeMinTime(const benchmark::internal::BenchmarkInstance& b, + const BenchTimeType& iters_or_time) { + if (!IsZero(b.min_time())) return b.min_time(); + // If the flag was used to specify number of iters, then return the default + // min_time. + if (iters_or_time.tag == BenchTimeType::ITERS) return kDefaultMinTime; + + return iters_or_time.time; +} + +IterationCount ComputeIters(const benchmark::internal::BenchmarkInstance& b, + const BenchTimeType& iters_or_time) { + if (b.iterations() != 0) return b.iterations(); + + // We've already concluded that this flag is currently used to pass + // iters but do a check here again anyway. + BM_CHECK(iters_or_time.tag == BenchTimeType::ITERS); + return iters_or_time.iters; +} + +} // end namespace + +BenchTimeType ParseBenchMinTime(const std::string& value) { + BenchTimeType ret; + + if (value.empty()) { + ret.tag = BenchTimeType::TIME; + ret.time = 0.0; + return ret; + } + + if (value.back() == 'x') { + char* p_end; + // Reset errno before it's changed by strtol. + errno = 0; + IterationCount num_iters = std::strtol(value.c_str(), &p_end, 10); + + // After a valid parse, p_end should have been set to + // point to the 'x' suffix. + BM_CHECK(errno == 0 && p_end != nullptr && *p_end == 'x') + << "Malformed iters value passed to --benchmark_min_time: `" << value + << "`. Expected --benchmark_min_time=x."; + + ret.tag = BenchTimeType::ITERS; + ret.iters = num_iters; + return ret; + } + + bool has_suffix = value.back() == 's'; + if (!has_suffix) { + BM_VLOG(0) << "Value passed to --benchmark_min_time should have a suffix. " + "Eg., `30s` for 30-seconds."; + } + + char* p_end; + // Reset errno before it's changed by strtod. + errno = 0; + double min_time = std::strtod(value.c_str(), &p_end); + + // After a successful parse, p_end should point to the suffix 's', + // or the end of the string if the suffix was omitted. + BM_CHECK(errno == 0 && p_end != nullptr && + ((has_suffix && *p_end == 's') || *p_end == '\0')) + << "Malformed seconds value passed to --benchmark_min_time: `" << value + << "`. Expected --benchmark_min_time=x."; + + ret.tag = BenchTimeType::TIME; + ret.time = min_time; + + return ret; +} + +BenchmarkRunner::BenchmarkRunner( + const benchmark::internal::BenchmarkInstance& b_, + PerfCountersMeasurement* pcm_, + BenchmarkReporter::PerFamilyRunReports* reports_for_family_) + : b(b_), + reports_for_family(reports_for_family_), + parsed_benchtime_flag(ParseBenchMinTime(FLAGS_benchmark_min_time)), + min_time(ComputeMinTime(b_, parsed_benchtime_flag)), + min_warmup_time((!IsZero(b.min_time()) && b.min_warmup_time() > 0.0) + ? b.min_warmup_time() + : FLAGS_benchmark_min_warmup_time), + warmup_done(!(min_warmup_time > 0.0)), + repeats(b.repetitions() != 0 ? b.repetitions() + : FLAGS_benchmark_repetitions), + has_explicit_iteration_count(b.iterations() != 0 || + parsed_benchtime_flag.tag == + BenchTimeType::ITERS), + pool(b.threads() - 1), + iters(has_explicit_iteration_count + ? ComputeIters(b_, parsed_benchtime_flag) + : 1), + perf_counters_measurement_ptr(pcm_) { + run_results.display_report_aggregates_only = + (FLAGS_benchmark_report_aggregates_only || + FLAGS_benchmark_display_aggregates_only); + run_results.file_report_aggregates_only = + FLAGS_benchmark_report_aggregates_only; + if (b.aggregation_report_mode() != internal::ARM_Unspecified) { + run_results.display_report_aggregates_only = + (b.aggregation_report_mode() & + internal::ARM_DisplayReportAggregatesOnly); + run_results.file_report_aggregates_only = + (b.aggregation_report_mode() & internal::ARM_FileReportAggregatesOnly); + BM_CHECK(FLAGS_benchmark_perf_counters.empty() || + (perf_counters_measurement_ptr->num_counters() == 0)) + << "Perf counters were requested but could not be set up."; + } +} + +BenchmarkRunner::IterationResults BenchmarkRunner::DoNIterations() { + BM_VLOG(2) << "Running " << b.name().str() << " for " << iters << "\n"; + + std::unique_ptr manager; + manager.reset(new internal::ThreadManager(b.threads())); + + // Run all but one thread in separate threads + for (std::size_t ti = 0; ti < pool.size(); ++ti) { + pool[ti] = std::thread(&RunInThread, &b, iters, static_cast(ti + 1), + manager.get(), perf_counters_measurement_ptr); + } + // And run one thread here directly. + // (If we were asked to run just one thread, we don't create new threads.) + // Yes, we need to do this here *after* we start the separate threads. + RunInThread(&b, iters, 0, manager.get(), perf_counters_measurement_ptr); + + // The main thread has finished. Now let's wait for the other threads. + manager->WaitForAllThreads(); + for (std::thread& thread : pool) thread.join(); + + IterationResults i; + // Acquire the measurements/counters from the manager, UNDER THE LOCK! + { + MutexLock l(manager->GetBenchmarkMutex()); + i.results = manager->results; + } + + // And get rid of the manager. + manager.reset(); + + // Adjust real/manual time stats since they were reported per thread. + i.results.real_time_used /= b.threads(); + i.results.manual_time_used /= b.threads(); + // If we were measuring whole-process CPU usage, adjust the CPU time too. + if (b.measure_process_cpu_time()) i.results.cpu_time_used /= b.threads(); + + BM_VLOG(2) << "Ran in " << i.results.cpu_time_used << "/" + << i.results.real_time_used << "\n"; + + // By using KeepRunningBatch a benchmark can iterate more times than + // requested, so take the iteration count from i.results. + i.iters = i.results.iterations / b.threads(); + + // Base decisions off of real time if requested by this benchmark. + i.seconds = i.results.cpu_time_used; + if (b.use_manual_time()) { + i.seconds = i.results.manual_time_used; + } else if (b.use_real_time()) { + i.seconds = i.results.real_time_used; + } + + return i; +} + +IterationCount BenchmarkRunner::PredictNumItersNeeded( + const IterationResults& i) const { + // See how much iterations should be increased by. + // Note: Avoid division by zero with max(seconds, 1ns). + double multiplier = GetMinTimeToApply() * 1.4 / std::max(i.seconds, 1e-9); + // If our last run was at least 10% of FLAGS_benchmark_min_time then we + // use the multiplier directly. + // Otherwise we use at most 10 times expansion. + // NOTE: When the last run was at least 10% of the min time the max + // expansion should be 14x. + const bool is_significant = (i.seconds / GetMinTimeToApply()) > 0.1; + multiplier = is_significant ? multiplier : 10.0; + + // So what seems to be the sufficiently-large iteration count? Round up. + const IterationCount max_next_iters = static_cast( + std::lround(std::max(multiplier * static_cast(i.iters), + static_cast(i.iters) + 1.0))); + // But we do have *some* limits though.. + const IterationCount next_iters = std::min(max_next_iters, kMaxIterations); + + BM_VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n"; + return next_iters; // round up before conversion to integer. +} + +bool BenchmarkRunner::ShouldReportIterationResults( + const IterationResults& i) const { + // Determine if this run should be reported; + // Either it has run for a sufficient amount of time + // or because an error was reported. + return i.results.skipped_ || + i.iters >= kMaxIterations || // Too many iterations already. + i.seconds >= + GetMinTimeToApply() || // The elapsed time is large enough. + // CPU time is specified but the elapsed real time greatly exceeds + // the minimum time. + // Note that user provided timers are except from this test. + ((i.results.real_time_used >= 5 * GetMinTimeToApply()) && + !b.use_manual_time()); +} + +double BenchmarkRunner::GetMinTimeToApply() const { + // In order to re-use functionality to run and measure benchmarks for running + // a warmup phase of the benchmark, we need a way of telling whether to apply + // min_time or min_warmup_time. This function will figure out if we are in the + // warmup phase and therefore need to apply min_warmup_time or if we already + // in the benchmarking phase and min_time needs to be applied. + return warmup_done ? min_time : min_warmup_time; +} + +void BenchmarkRunner::FinishWarmUp(const IterationCount& i) { + warmup_done = true; + iters = i; +} + +void BenchmarkRunner::RunWarmUp() { + // Use the same mechanisms for warming up the benchmark as used for actually + // running and measuring the benchmark. + IterationResults i_warmup; + // Dont use the iterations determined in the warmup phase for the actual + // measured benchmark phase. While this may be a good starting point for the + // benchmark and it would therefore get rid of the need to figure out how many + // iterations are needed if min_time is set again, this may also be a complete + // wrong guess since the warmup loops might be considerably slower (e.g + // because of caching effects). + const IterationCount i_backup = iters; + + for (;;) { + b.Setup(); + i_warmup = DoNIterations(); + b.Teardown(); + + const bool finish = ShouldReportIterationResults(i_warmup); + + if (finish) { + FinishWarmUp(i_backup); + break; + } + + // Although we are running "only" a warmup phase where running enough + // iterations at once without measuring time isn't as important as it is for + // the benchmarking phase, we still do it the same way as otherwise it is + // very confusing for the user to know how to choose a proper value for + // min_warmup_time if a different approach on running it is used. + iters = PredictNumItersNeeded(i_warmup); + assert(iters > i_warmup.iters && + "if we did more iterations than we want to do the next time, " + "then we should have accepted the current iteration run."); + } +} + +void BenchmarkRunner::DoOneRepetition() { + assert(HasRepeatsRemaining() && "Already done all repetitions?"); + + const bool is_the_first_repetition = num_repetitions_done == 0; + + // In case a warmup phase is requested by the benchmark, run it now. + // After running the warmup phase the BenchmarkRunner should be in a state as + // this warmup never happened except the fact that warmup_done is set. Every + // other manipulation of the BenchmarkRunner instance would be a bug! Please + // fix it. + if (!warmup_done) RunWarmUp(); + + IterationResults i; + // We *may* be gradually increasing the length (iteration count) + // of the benchmark until we decide the results are significant. + // And once we do, we report those last results and exit. + // Please do note that the if there are repetitions, the iteration count + // is *only* calculated for the *first* repetition, and other repetitions + // simply use that precomputed iteration count. + for (;;) { + b.Setup(); + i = DoNIterations(); + b.Teardown(); + + // Do we consider the results to be significant? + // If we are doing repetitions, and the first repetition was already done, + // it has calculated the correct iteration time, so we have run that very + // iteration count just now. No need to calculate anything. Just report. + // Else, the normal rules apply. + const bool results_are_significant = !is_the_first_repetition || + has_explicit_iteration_count || + ShouldReportIterationResults(i); + + if (results_are_significant) break; // Good, let's report them! + + // Nope, bad iteration. Let's re-estimate the hopefully-sufficient + // iteration count, and run the benchmark again... + + iters = PredictNumItersNeeded(i); + assert(iters > i.iters && + "if we did more iterations than we want to do the next time, " + "then we should have accepted the current iteration run."); + } + + // Oh, one last thing, we need to also produce the 'memory measurements'.. + MemoryManager::Result* memory_result = nullptr; + IterationCount memory_iterations = 0; + if (memory_manager != nullptr) { + // TODO(vyng): Consider making BenchmarkReporter::Run::memory_result an + // optional so we don't have to own the Result here. + // Can't do it now due to cxx03. + memory_results.push_back(MemoryManager::Result()); + memory_result = &memory_results.back(); + // Only run a few iterations to reduce the impact of one-time + // allocations in benchmarks that are not properly managed. + memory_iterations = std::min(16, iters); + memory_manager->Start(); + std::unique_ptr manager; + manager.reset(new internal::ThreadManager(1)); + b.Setup(); + RunInThread(&b, memory_iterations, 0, manager.get(), + perf_counters_measurement_ptr); + manager->WaitForAllThreads(); + manager.reset(); + b.Teardown(); + memory_manager->Stop(*memory_result); + } + + // Ok, now actually report. + BenchmarkReporter::Run report = + CreateRunReport(b, i.results, memory_iterations, memory_result, i.seconds, + num_repetitions_done, repeats); + + if (reports_for_family) { + ++reports_for_family->num_runs_done; + if (!report.skipped) reports_for_family->Runs.push_back(report); + } + + run_results.non_aggregates.push_back(report); + + ++num_repetitions_done; +} + +RunResults&& BenchmarkRunner::GetResults() { + assert(!HasRepeatsRemaining() && "Did not run all repetitions yet?"); + + // Calculate additional statistics over the repetitions of this instance. + run_results.aggregates_only = ComputeStats(run_results.non_aggregates); + + return std::move(run_results); +} + +} // end namespace internal + +} // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/src/benchmark_runner.h b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_runner.h new file mode 100644 index 000000000..db2fa0439 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/benchmark_runner.h @@ -0,0 +1,131 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef BENCHMARK_RUNNER_H_ +#define BENCHMARK_RUNNER_H_ + +#include +#include + +#include "benchmark_api_internal.h" +#include "internal_macros.h" +#include "perf_counters.h" +#include "thread_manager.h" + +namespace benchmark { + +BM_DECLARE_string(benchmark_min_time); +BM_DECLARE_double(benchmark_min_warmup_time); +BM_DECLARE_int32(benchmark_repetitions); +BM_DECLARE_bool(benchmark_report_aggregates_only); +BM_DECLARE_bool(benchmark_display_aggregates_only); +BM_DECLARE_string(benchmark_perf_counters); + +namespace internal { + +extern MemoryManager* memory_manager; + +struct RunResults { + std::vector non_aggregates; + std::vector aggregates_only; + + bool display_report_aggregates_only = false; + bool file_report_aggregates_only = false; +}; + +struct BENCHMARK_EXPORT BenchTimeType { + enum { ITERS, TIME } tag; + union { + IterationCount iters; + double time; + }; +}; + +BENCHMARK_EXPORT +BenchTimeType ParseBenchMinTime(const std::string& value); + +class BenchmarkRunner { + public: + BenchmarkRunner(const benchmark::internal::BenchmarkInstance& b_, + benchmark::internal::PerfCountersMeasurement* pmc_, + BenchmarkReporter::PerFamilyRunReports* reports_for_family); + + int GetNumRepeats() const { return repeats; } + + bool HasRepeatsRemaining() const { + return GetNumRepeats() != num_repetitions_done; + } + + void DoOneRepetition(); + + RunResults&& GetResults(); + + BenchmarkReporter::PerFamilyRunReports* GetReportsForFamily() const { + return reports_for_family; + } + + double GetMinTime() const { return min_time; } + + bool HasExplicitIters() const { return has_explicit_iteration_count; } + + IterationCount GetIters() const { return iters; } + + private: + RunResults run_results; + + const benchmark::internal::BenchmarkInstance& b; + BenchmarkReporter::PerFamilyRunReports* reports_for_family; + + BenchTimeType parsed_benchtime_flag; + const double min_time; + const double min_warmup_time; + bool warmup_done; + const int repeats; + const bool has_explicit_iteration_count; + + int num_repetitions_done = 0; + + std::vector pool; + + std::vector memory_results; + + IterationCount iters; // preserved between repetitions! + // So only the first repetition has to find/calculate it, + // the other repetitions will just use that precomputed iteration count. + + PerfCountersMeasurement* const perf_counters_measurement_ptr = nullptr; + + struct IterationResults { + internal::ThreadManager::Result results; + IterationCount iters; + double seconds; + }; + IterationResults DoNIterations(); + + IterationCount PredictNumItersNeeded(const IterationResults& i) const; + + bool ShouldReportIterationResults(const IterationResults& i) const; + + double GetMinTimeToApply() const; + + void FinishWarmUp(const IterationCount& i); + + void RunWarmUp(); +}; + +} // namespace internal + +} // end namespace benchmark + +#endif // BENCHMARK_RUNNER_H_ diff --git a/thirdparty_builtin/benchmark-1.8.0/src/check.cc b/thirdparty_builtin/benchmark-1.8.0/src/check.cc new file mode 100644 index 000000000..5f7526e08 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/check.cc @@ -0,0 +1,11 @@ +#include "check.h" + +namespace benchmark { +namespace internal { + +static AbortHandlerT* handler = &std::abort; + +BENCHMARK_EXPORT AbortHandlerT*& GetAbortHandler() { return handler; } + +} // namespace internal +} // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/src/check.h b/thirdparty_builtin/benchmark-1.8.0/src/check.h new file mode 100644 index 000000000..c1cd5e85e --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/check.h @@ -0,0 +1,106 @@ +#ifndef CHECK_H_ +#define CHECK_H_ + +#include +#include +#include + +#include "benchmark/export.h" +#include "internal_macros.h" +#include "log.h" + +#if defined(__GNUC__) || defined(__clang__) +#define BENCHMARK_NOEXCEPT noexcept +#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) +#elif defined(_MSC_VER) && !defined(__clang__) +#if _MSC_VER >= 1900 +#define BENCHMARK_NOEXCEPT noexcept +#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) +#else +#define BENCHMARK_NOEXCEPT +#define BENCHMARK_NOEXCEPT_OP(x) +#endif +#define __func__ __FUNCTION__ +#else +#define BENCHMARK_NOEXCEPT +#define BENCHMARK_NOEXCEPT_OP(x) +#endif + +namespace benchmark { +namespace internal { + +typedef void(AbortHandlerT)(); + +BENCHMARK_EXPORT +AbortHandlerT*& GetAbortHandler(); + +BENCHMARK_NORETURN inline void CallAbortHandler() { + GetAbortHandler()(); + std::abort(); // fallback to enforce noreturn +} + +// CheckHandler is the class constructed by failing BM_CHECK macros. +// CheckHandler will log information about the failures and abort when it is +// destructed. +class CheckHandler { + public: + CheckHandler(const char* check, const char* file, const char* func, int line) + : log_(GetErrorLogInstance()) { + log_ << file << ":" << line << ": " << func << ": Check `" << check + << "' failed. "; + } + + LogType& GetLog() { return log_; } + +#if defined(COMPILER_MSVC) +#pragma warning(push) +#pragma warning(disable : 4722) +#endif + BENCHMARK_NORETURN ~CheckHandler() BENCHMARK_NOEXCEPT_OP(false) { + log_ << std::endl; + CallAbortHandler(); + } +#if defined(COMPILER_MSVC) +#pragma warning(pop) +#endif + + CheckHandler& operator=(const CheckHandler&) = delete; + CheckHandler(const CheckHandler&) = delete; + CheckHandler() = delete; + + private: + LogType& log_; +}; + +} // end namespace internal +} // end namespace benchmark + +// The BM_CHECK macro returns a std::ostream object that can have extra +// information written to it. +#ifndef NDEBUG +#define BM_CHECK(b) \ + (b ? ::benchmark::internal::GetNullLogInstance() \ + : ::benchmark::internal::CheckHandler(#b, __FILE__, __func__, __LINE__) \ + .GetLog()) +#else +#define BM_CHECK(b) ::benchmark::internal::GetNullLogInstance() +#endif + +// clang-format off +// preserve whitespacing between operators for alignment +#define BM_CHECK_EQ(a, b) BM_CHECK((a) == (b)) +#define BM_CHECK_NE(a, b) BM_CHECK((a) != (b)) +#define BM_CHECK_GE(a, b) BM_CHECK((a) >= (b)) +#define BM_CHECK_LE(a, b) BM_CHECK((a) <= (b)) +#define BM_CHECK_GT(a, b) BM_CHECK((a) > (b)) +#define BM_CHECK_LT(a, b) BM_CHECK((a) < (b)) + +#define BM_CHECK_FLOAT_EQ(a, b, eps) BM_CHECK(std::fabs((a) - (b)) < (eps)) +#define BM_CHECK_FLOAT_NE(a, b, eps) BM_CHECK(std::fabs((a) - (b)) >= (eps)) +#define BM_CHECK_FLOAT_GE(a, b, eps) BM_CHECK((a) - (b) > -(eps)) +#define BM_CHECK_FLOAT_LE(a, b, eps) BM_CHECK((b) - (a) > -(eps)) +#define BM_CHECK_FLOAT_GT(a, b, eps) BM_CHECK((a) - (b) > (eps)) +#define BM_CHECK_FLOAT_LT(a, b, eps) BM_CHECK((b) - (a) > (eps)) +//clang-format on + +#endif // CHECK_H_ diff --git a/thirdparty_builtin/benchmark-1.5.0/src/colorprint.cc b/thirdparty_builtin/benchmark-1.8.0/src/colorprint.cc similarity index 90% rename from thirdparty_builtin/benchmark-1.5.0/src/colorprint.cc rename to thirdparty_builtin/benchmark-1.8.0/src/colorprint.cc index fff6a9881..9a653c500 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/colorprint.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/colorprint.cc @@ -25,8 +25,8 @@ #include "internal_macros.h" #ifdef BENCHMARK_OS_WINDOWS -#include #include +#include #else #include #endif // BENCHMARK_OS_WINDOWS @@ -94,20 +94,20 @@ std::string FormatString(const char* msg, va_list args) { va_end(args_cp); // currently there is no error handling for failure, so this is hack. - CHECK(ret >= 0); + BM_CHECK(ret >= 0); - if (ret == 0) // handle empty expansion + if (ret == 0) { // handle empty expansion return {}; - else if (static_cast(ret) < size) + } + if (static_cast(ret) < size) { return local_buff; - else { - // we did not provide a long enough buffer on our first attempt. - size = (size_t)ret + 1; // + 1 for the null byte - std::unique_ptr buff(new char[size]); - ret = vsnprintf(buff.get(), size, msg, args); - CHECK(ret > 0 && ((size_t)ret) < size); - return buff.get(); } + // we did not provide a long enough buffer on our first attempt. + size = static_cast(ret) + 1; // + 1 for the null byte + std::unique_ptr buff(new char[size]); + ret = vsnprintf(buff.get(), size, msg, args); + BM_CHECK(ret > 0 && (static_cast(ret)) < size); + return buff.get(); } std::string FormatString(const char* msg, ...) { @@ -163,7 +163,7 @@ bool IsColorTerminal() { #else // On non-Windows platforms, we rely on the TERM variable. This list of // supported TERM values is copied from Google Test: - // . + // . const char* const SUPPORTED_TERM_VALUES[] = { "xterm", "xterm-color", "xterm-256color", "screen", "screen-256color", "tmux", diff --git a/thirdparty_builtin/benchmark-1.5.0/src/colorprint.h b/thirdparty_builtin/benchmark-1.8.0/src/colorprint.h similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/src/colorprint.h rename to thirdparty_builtin/benchmark-1.8.0/src/colorprint.h diff --git a/thirdparty_builtin/benchmark-1.5.0/src/commandlineflags.cc b/thirdparty_builtin/benchmark-1.8.0/src/commandlineflags.cc similarity index 64% rename from thirdparty_builtin/benchmark-1.5.0/src/commandlineflags.cc rename to thirdparty_builtin/benchmark-1.8.0/src/commandlineflags.cc index 6bd65c5ae..dcb414959 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/commandlineflags.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/commandlineflags.cc @@ -14,11 +14,16 @@ #include "commandlineflags.h" +#include #include #include #include #include #include +#include +#include + +#include "../src/string_util.h" namespace benchmark { namespace { @@ -77,6 +82,30 @@ bool ParseDouble(const std::string& src_text, const char* str, double* value) { return true; } +// Parses 'str' into KV pairs. If successful, writes the result to *value and +// returns true; otherwise leaves *value unchanged and returns false. +bool ParseKvPairs(const std::string& src_text, const char* str, + std::map* value) { + std::map kvs; + for (const auto& kvpair : StrSplit(str, ',')) { + const auto kv = StrSplit(kvpair, '='); + if (kv.size() != 2) { + std::cerr << src_text << " is expected to be a comma-separated list of " + << "= strings, but actually has value \"" << str + << "\".\n"; + return false; + } + if (!kvs.emplace(kv[0], kv[1]).second) { + std::cerr << src_text << " is expected to contain unique keys but key \"" + << kv[0] << "\" was repeated.\n"; + return false; + } + } + + *value = kvs; + return true; +} + // Returns the name of the environment variable corresponding to the // given flag. For example, FlagToEnvVar("foo") will return // "BENCHMARK_FOO" in the open-source version. @@ -87,49 +116,64 @@ static std::string FlagToEnvVar(const char* flag) { for (size_t i = 0; i != flag_str.length(); ++i) env_var += static_cast(::toupper(flag_str.c_str()[i])); - return "BENCHMARK_" + env_var; + return env_var; } } // namespace -// Reads and returns the Boolean environment variable corresponding to -// the given flag; if it's not set, returns default_value. -// -// The value is considered true iff it's not "0". -bool BoolFromEnv(const char* flag, bool default_value) { +BENCHMARK_EXPORT +bool BoolFromEnv(const char* flag, bool default_val) { const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = getenv(env_var.c_str()); - return string_value == nullptr ? default_value - : strcmp(string_value, "0") != 0; + const char* const value_str = getenv(env_var.c_str()); + return value_str == nullptr ? default_val : IsTruthyFlagValue(value_str); } -// Reads and returns a 32-bit integer stored in the environment -// variable corresponding to the given flag; if it isn't set or -// doesn't represent a valid 32-bit integer, returns default_value. -int32_t Int32FromEnv(const char* flag, int32_t default_value) { +BENCHMARK_EXPORT +int32_t Int32FromEnv(const char* flag, int32_t default_val) { const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = getenv(env_var.c_str()); - if (string_value == nullptr) { - // The environment variable is not set. - return default_value; + const char* const value_str = getenv(env_var.c_str()); + int32_t value = default_val; + if (value_str == nullptr || + !ParseInt32(std::string("Environment variable ") + env_var, value_str, + &value)) { + return default_val; } + return value; +} - int32_t result = default_value; - if (!ParseInt32(std::string("Environment variable ") + env_var, string_value, - &result)) { - std::cout << "The default value " << default_value << " is used.\n"; - return default_value; +BENCHMARK_EXPORT +double DoubleFromEnv(const char* flag, double default_val) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value_str = getenv(env_var.c_str()); + double value = default_val; + if (value_str == nullptr || + !ParseDouble(std::string("Environment variable ") + env_var, value_str, + &value)) { + return default_val; } - - return result; + return value; } -// Reads and returns the string environment variable corresponding to -// the given flag; if it's not set, returns default_value. -const char* StringFromEnv(const char* flag, const char* default_value) { +BENCHMARK_EXPORT +const char* StringFromEnv(const char* flag, const char* default_val) { const std::string env_var = FlagToEnvVar(flag); const char* const value = getenv(env_var.c_str()); - return value == nullptr ? default_value : value; + return value == nullptr ? default_val : value; +} + +BENCHMARK_EXPORT +std::map KvPairsFromEnv( + const char* flag, std::map default_val) { + const std::string env_var = FlagToEnvVar(flag); + const char* const value_str = getenv(env_var.c_str()); + + if (value_str == nullptr) return default_val; + + std::map value; + if (!ParseKvPairs("Environment variable " + env_var, value_str, &value)) { + return default_val; + } + return value; } // Parses a string as a command line flag. The string should have @@ -162,6 +206,7 @@ const char* ParseFlagValue(const char* str, const char* flag, return flag_end + 1; } +BENCHMARK_EXPORT bool ParseBoolFlag(const char* str, const char* flag, bool* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, true); @@ -174,6 +219,7 @@ bool ParseBoolFlag(const char* str, const char* flag, bool* value) { return true; } +BENCHMARK_EXPORT bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); @@ -186,6 +232,7 @@ bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { value); } +BENCHMARK_EXPORT bool ParseDoubleFlag(const char* str, const char* flag, double* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); @@ -198,6 +245,7 @@ bool ParseDoubleFlag(const char* str, const char* flag, double* value) { value); } +BENCHMARK_EXPORT bool ParseStringFlag(const char* str, const char* flag, std::string* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); @@ -209,14 +257,42 @@ bool ParseStringFlag(const char* str, const char* flag, std::string* value) { return true; } +BENCHMARK_EXPORT +bool ParseKeyValueFlag(const char* str, const char* flag, + std::map* value) { + const char* const value_str = ParseFlagValue(str, flag, false); + + if (value_str == nullptr) return false; + + for (const auto& kvpair : StrSplit(value_str, ',')) { + const auto kv = StrSplit(kvpair, '='); + if (kv.size() != 2) return false; + value->emplace(kv[0], kv[1]); + } + + return true; +} + +BENCHMARK_EXPORT bool IsFlag(const char* str, const char* flag) { return (ParseFlagValue(str, flag, true) != nullptr); } +BENCHMARK_EXPORT bool IsTruthyFlagValue(const std::string& value) { - if (value.empty()) return true; - char ch = value[0]; - return isalnum(ch) && - !(ch == '0' || ch == 'f' || ch == 'F' || ch == 'n' || ch == 'N'); + if (value.size() == 1) { + char v = value[0]; + return isalnum(v) && + !(v == '0' || v == 'f' || v == 'F' || v == 'n' || v == 'N'); + } + if (!value.empty()) { + std::string value_lower(value); + std::transform(value_lower.begin(), value_lower.end(), value_lower.begin(), + [](char c) { return static_cast(::tolower(c)); }); + return !(value_lower == "false" || value_lower == "no" || + value_lower == "off"); + } + return true; } + } // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/src/commandlineflags.h b/thirdparty_builtin/benchmark-1.8.0/src/commandlineflags.h new file mode 100644 index 000000000..788262897 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/commandlineflags.h @@ -0,0 +1,133 @@ +#ifndef BENCHMARK_COMMANDLINEFLAGS_H_ +#define BENCHMARK_COMMANDLINEFLAGS_H_ + +#include +#include +#include + +#include "benchmark/export.h" + +// Macro for referencing flags. +#define FLAG(name) FLAGS_##name + +// Macros for declaring flags. +#define BM_DECLARE_bool(name) BENCHMARK_EXPORT extern bool FLAG(name) +#define BM_DECLARE_int32(name) BENCHMARK_EXPORT extern int32_t FLAG(name) +#define BM_DECLARE_double(name) BENCHMARK_EXPORT extern double FLAG(name) +#define BM_DECLARE_string(name) BENCHMARK_EXPORT extern std::string FLAG(name) +#define BM_DECLARE_kvpairs(name) \ + BENCHMARK_EXPORT extern std::map FLAG(name) + +// Macros for defining flags. +#define BM_DEFINE_bool(name, default_val) \ + BENCHMARK_EXPORT bool FLAG(name) = benchmark::BoolFromEnv(#name, default_val) +#define BM_DEFINE_int32(name, default_val) \ + BENCHMARK_EXPORT int32_t FLAG(name) = \ + benchmark::Int32FromEnv(#name, default_val) +#define BM_DEFINE_double(name, default_val) \ + BENCHMARK_EXPORT double FLAG(name) = \ + benchmark::DoubleFromEnv(#name, default_val) +#define BM_DEFINE_string(name, default_val) \ + BENCHMARK_EXPORT std::string FLAG(name) = \ + benchmark::StringFromEnv(#name, default_val) +#define BM_DEFINE_kvpairs(name, default_val) \ + BENCHMARK_EXPORT std::map FLAG(name) = \ + benchmark::KvPairsFromEnv(#name, default_val) + +namespace benchmark { + +// Parses a bool from the environment variable corresponding to the given flag. +// +// If the variable exists, returns IsTruthyFlagValue() value; if not, +// returns the given default value. +BENCHMARK_EXPORT +bool BoolFromEnv(const char* flag, bool default_val); + +// Parses an Int32 from the environment variable corresponding to the given +// flag. +// +// If the variable exists, returns ParseInt32() value; if not, returns +// the given default value. +BENCHMARK_EXPORT +int32_t Int32FromEnv(const char* flag, int32_t default_val); + +// Parses an Double from the environment variable corresponding to the given +// flag. +// +// If the variable exists, returns ParseDouble(); if not, returns +// the given default value. +BENCHMARK_EXPORT +double DoubleFromEnv(const char* flag, double default_val); + +// Parses a string from the environment variable corresponding to the given +// flag. +// +// If variable exists, returns its value; if not, returns +// the given default value. +BENCHMARK_EXPORT +const char* StringFromEnv(const char* flag, const char* default_val); + +// Parses a set of kvpairs from the environment variable corresponding to the +// given flag. +// +// If variable exists, returns its value; if not, returns +// the given default value. +BENCHMARK_EXPORT +std::map KvPairsFromEnv( + const char* flag, std::map default_val); + +// Parses a string for a bool flag, in the form of either +// "--flag=value" or "--flag". +// +// In the former case, the value is taken as true if it passes IsTruthyValue(). +// +// In the latter case, the value is taken as true. +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseBoolFlag(const char* str, const char* flag, bool* value); + +// Parses a string for an Int32 flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseInt32Flag(const char* str, const char* flag, int32_t* value); + +// Parses a string for a Double flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseDoubleFlag(const char* str, const char* flag, double* value); + +// Parses a string for a string flag, in the form of "--flag=value". +// +// On success, stores the value of the flag in *value, and returns +// true. On failure, returns false without changing *value. +BENCHMARK_EXPORT +bool ParseStringFlag(const char* str, const char* flag, std::string* value); + +// Parses a string for a kvpairs flag in the form "--flag=key=value,key=value" +// +// On success, stores the value of the flag in *value and returns true. On +// failure returns false, though *value may have been mutated. +BENCHMARK_EXPORT +bool ParseKeyValueFlag(const char* str, const char* flag, + std::map* value); + +// Returns true if the string matches the flag. +BENCHMARK_EXPORT +bool IsFlag(const char* str, const char* flag); + +// Returns true unless value starts with one of: '0', 'f', 'F', 'n' or 'N', or +// some non-alphanumeric character. Also returns false if the value matches +// one of 'no', 'false', 'off' (case-insensitive). As a special case, also +// returns true if value is the empty string. +BENCHMARK_EXPORT +bool IsTruthyFlagValue(const std::string& value); + +} // end namespace benchmark + +#endif // BENCHMARK_COMMANDLINEFLAGS_H_ diff --git a/thirdparty_builtin/benchmark-1.5.0/src/complexity.cc b/thirdparty_builtin/benchmark-1.8.0/src/complexity.cc similarity index 92% rename from thirdparty_builtin/benchmark-1.5.0/src/complexity.cc rename to thirdparty_builtin/benchmark-1.8.0/src/complexity.cc index aeed67f0c..825c57394 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/complexity.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/complexity.cc @@ -15,12 +15,13 @@ // Source project : https://github.com/ismaelJimenez/cpp.leastsq // Adapted to be used with google benchmark -#include "benchmark/benchmark.h" +#include "complexity.h" #include #include + +#include "benchmark/benchmark.h" #include "check.h" -#include "complexity.h" namespace benchmark { @@ -82,7 +83,6 @@ std::string GetBigOString(BigO complexity) { LeastSq MinimalLeastSq(const std::vector& n, const std::vector& time, BigOFunc* fitting_curve) { - double sigma_gn = 0.0; double sigma_gn_squared = 0.0; double sigma_time = 0.0; double sigma_time_gn = 0.0; @@ -90,7 +90,6 @@ LeastSq MinimalLeastSq(const std::vector& n, // Calculate least square fitting parameter for (size_t i = 0; i < n.size(); ++i) { double gn_i = fitting_curve(n[i]); - sigma_gn += gn_i; sigma_gn_squared += gn_i * gn_i; sigma_time += time[i]; sigma_time_gn += time[i] * gn_i; @@ -125,10 +124,10 @@ LeastSq MinimalLeastSq(const std::vector& n, // fitting curve. LeastSq MinimalLeastSq(const std::vector& n, const std::vector& time, const BigO complexity) { - CHECK_EQ(n.size(), time.size()); - CHECK_GE(n.size(), 2); // Do not compute fitting curve is less than two - // benchmark runs are given - CHECK_NE(complexity, oNone); + BM_CHECK_EQ(n.size(), time.size()); + BM_CHECK_GE(n.size(), 2); // Do not compute fitting curve is less than two + // benchmark runs are given + BM_CHECK_NE(complexity, oNone); LeastSq best_fit; @@ -169,7 +168,8 @@ std::vector ComputeBigO( // Populate the accumulators. for (const Run& run : reports) { - CHECK_GT(run.complexity_n, 0) << "Did you forget to call SetComplexityN?"; + BM_CHECK_GT(run.complexity_n, 0) + << "Did you forget to call SetComplexityN?"; n.push_back(run.complexity_n); real_time.push_back(run.real_accumulated_time / run.iterations); cpu_time.push_back(run.cpu_accumulated_time / run.iterations); @@ -193,11 +193,14 @@ std::vector ComputeBigO( // Get the data from the accumulator to BenchmarkReporter::Run's. Run big_o; big_o.run_name = run_name; + big_o.family_index = reports[0].family_index; + big_o.per_family_instance_index = reports[0].per_family_instance_index; big_o.run_type = BenchmarkReporter::Run::RT_Aggregate; big_o.repetitions = reports[0].repetitions; big_o.repetition_index = Run::no_repetition_index; big_o.threads = reports[0].threads; big_o.aggregate_name = "BigO"; + big_o.aggregate_unit = StatisticUnit::kTime; big_o.report_label = reports[0].report_label; big_o.iterations = 0; big_o.real_accumulated_time = result_real.coef; @@ -215,8 +218,11 @@ std::vector ComputeBigO( // Only add label to mean/stddev if it is same for all runs Run rms; rms.run_name = run_name; + rms.family_index = reports[0].family_index; + rms.per_family_instance_index = reports[0].per_family_instance_index; rms.run_type = BenchmarkReporter::Run::RT_Aggregate; rms.aggregate_name = "RMS"; + rms.aggregate_unit = StatisticUnit::kPercentage; rms.report_label = big_o.report_label; rms.iterations = 0; rms.repetition_index = Run::no_repetition_index; diff --git a/thirdparty_builtin/benchmark-1.5.0/src/complexity.h b/thirdparty_builtin/benchmark-1.8.0/src/complexity.h similarity index 96% rename from thirdparty_builtin/benchmark-1.5.0/src/complexity.h rename to thirdparty_builtin/benchmark-1.8.0/src/complexity.h index df29b48d2..0a0679b48 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/complexity.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/complexity.h @@ -31,7 +31,7 @@ std::vector ComputeBigO( const std::vector& reports); // This data structure will contain the result returned by MinimalLeastSq -// - coef : Estimated coeficient for the high-order term as +// - coef : Estimated coefficient for the high-order term as // interpolated from data. // - rms : Normalized Root Mean Squared Error. // - complexity : Scalability form (e.g. oN, oNLogN). In case a scalability diff --git a/thirdparty_builtin/benchmark-1.5.0/src/console_reporter.cc b/thirdparty_builtin/benchmark-1.8.0/src/console_reporter.cc similarity index 66% rename from thirdparty_builtin/benchmark-1.5.0/src/console_reporter.cc rename to thirdparty_builtin/benchmark-1.8.0/src/console_reporter.cc index cc8ae276f..10e05e133 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/console_reporter.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/console_reporter.cc @@ -12,27 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "benchmark/benchmark.h" -#include "complexity.h" -#include "counter.h" - #include #include #include +#include #include #include #include #include +#include "benchmark/benchmark.h" #include "check.h" #include "colorprint.h" #include "commandlineflags.h" +#include "complexity.h" +#include "counter.h" #include "internal_macros.h" #include "string_util.h" #include "timers.h" namespace benchmark { +BENCHMARK_EXPORT bool ConsoleReporter::ReportContext(const Context& context) { name_field_width_ = context.name_field_width; printed_header_ = false; @@ -45,19 +46,21 @@ bool ConsoleReporter::ReportContext(const Context& context) { GetErrorStream() << "Color printing is only supported for stdout on windows." " Disabling color printing\n"; - output_options_ = static_cast< OutputOptions >(output_options_ & ~OO_Color); + output_options_ = static_cast(output_options_ & ~OO_Color); } #endif return true; } +BENCHMARK_EXPORT void ConsoleReporter::PrintHeader(const Run& run) { - std::string str = FormatString("%-*s %13s %15s %12s", static_cast(name_field_width_), - "Benchmark", "Time", "CPU", "Iterations"); - if(!run.counters.empty()) { - if(output_options_ & OO_Tabular) { - for(auto const& c : run.counters) { + std::string str = + FormatString("%-*s %13s %15s %12s", static_cast(name_field_width_), + "Benchmark", "Time", "CPU", "Iterations"); + if (!run.counters.empty()) { + if (output_options_ & OO_Tabular) { + for (auto const& c : run.counters) { str += FormatString(" %10s", c.first.c_str()); } } else { @@ -68,6 +71,7 @@ void ConsoleReporter::PrintHeader(const Run& run) { GetOutputStream() << line << "\n" << str << "\n" << line << "\n"; } +BENCHMARK_EXPORT void ConsoleReporter::ReportRuns(const std::vector& reports) { for (const auto& run : reports) { // print the header: @@ -97,8 +101,10 @@ static void IgnoreColorPrint(std::ostream& out, LogColor, const char* fmt, va_end(args); } - static std::string FormatTime(double time) { + // For the time columns of the console printer 13 digits are reserved. One of + // them is a space and max two of them are the time unit (e.g ns). That puts + // us at 10 digits usable for the number. // Align decimal places... if (time < 1.0) { return FormatString("%10.3f", time); @@ -109,22 +115,33 @@ static std::string FormatTime(double time) { if (time < 100.0) { return FormatString("%10.1f", time); } + // Assuming the time is at max 9.9999e+99 and we have 10 digits for the + // number, we get 10-1(.)-1(e)-1(sign)-2(exponent) = 5 digits to print. + if (time > 9999999999 /*max 10 digit number*/) { + return FormatString("%1.4e", time); + } return FormatString("%10.0f", time); } +BENCHMARK_EXPORT void ConsoleReporter::PrintRunData(const Run& result) { typedef void(PrinterFn)(std::ostream&, LogColor, const char*, ...); auto& Out = GetOutputStream(); - PrinterFn* printer = (output_options_ & OO_Color) ? - (PrinterFn*)ColorPrintf : IgnoreColorPrint; + PrinterFn* printer = (output_options_ & OO_Color) + ? static_cast(ColorPrintf) + : IgnoreColorPrint; auto name_color = (result.report_big_o || result.report_rms) ? COLOR_BLUE : COLOR_GREEN; printer(Out, name_color, "%-*s ", name_field_width_, result.benchmark_name().c_str()); - if (result.error_occurred) { + if (internal::SkippedWithError == result.skipped) { printer(Out, COLOR_RED, "ERROR OCCURRED: \'%s\'", - result.error_message.c_str()); + result.skip_message.c_str()); + printer(Out, COLOR_DEFAULT, "\n"); + return; + } else if (internal::SkippedWithMessage == result.skipped) { + printer(Out, COLOR_WHITE, "SKIPPED: \'%s\'", result.skip_message.c_str()); printer(Out, COLOR_DEFAULT, "\n"); return; } @@ -134,18 +151,23 @@ void ConsoleReporter::PrintRunData(const Run& result) { const std::string real_time_str = FormatTime(real_time); const std::string cpu_time_str = FormatTime(cpu_time); - if (result.report_big_o) { std::string big_o = GetBigOString(result.complexity); - printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", real_time, big_o.c_str(), - cpu_time, big_o.c_str()); + printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", real_time, + big_o.c_str(), cpu_time, big_o.c_str()); } else if (result.report_rms) { printer(Out, COLOR_YELLOW, "%10.0f %-4s %10.0f %-4s ", real_time * 100, "%", cpu_time * 100, "%"); - } else { + } else if (result.run_type != Run::RT_Aggregate || + result.aggregate_unit == StatisticUnit::kTime) { const char* timeLabel = GetTimeUnitString(result.time_unit); - printer(Out, COLOR_YELLOW, "%s %-4s %s %-4s ", real_time_str.c_str(), timeLabel, - cpu_time_str.c_str(), timeLabel); + printer(Out, COLOR_YELLOW, "%s %-4s %s %-4s ", real_time_str.c_str(), + timeLabel, cpu_time_str.c_str(), timeLabel); + } else { + assert(result.aggregate_unit == StatisticUnit::kPercentage); + printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", + (100. * result.real_accumulated_time), "%", + (100. * result.cpu_accumulated_time), "%"); } if (!result.report_big_o && !result.report_rms) { @@ -153,19 +175,24 @@ void ConsoleReporter::PrintRunData(const Run& result) { } for (auto& c : result.counters) { - const std::size_t cNameLen = std::max(std::string::size_type(10), - c.first.length()); - auto const& s = HumanReadableNumber(c.second.value, c.second.oneK); - if (output_options_ & OO_Tabular) { - if (c.second.flags & Counter::kIsRate) { - printer(Out, COLOR_DEFAULT, " %*s/s", cNameLen - 2, s.c_str()); - } else { - printer(Out, COLOR_DEFAULT, " %*s", cNameLen, s.c_str()); - } + const std::size_t cNameLen = + std::max(std::string::size_type(10), c.first.length()); + std::string s; + const char* unit = ""; + if (result.run_type == Run::RT_Aggregate && + result.aggregate_unit == StatisticUnit::kPercentage) { + s = StrFormat("%.2f", 100. * c.second.value); + unit = "%"; } else { - const char* unit = (c.second.flags & Counter::kIsRate) ? "/s" : ""; - printer(Out, COLOR_DEFAULT, " %s=%s%s", c.first.c_str(), s.c_str(), + s = HumanReadableNumber(c.second.value, c.second.oneK); + if (c.second.flags & Counter::kIsRate) + unit = (c.second.flags & Counter::kInvert) ? "s" : "/s"; + } + if (output_options_ & OO_Tabular) { + printer(Out, COLOR_DEFAULT, " %*s%s", cNameLen - strlen(unit), s.c_str(), unit); + } else { + printer(Out, COLOR_DEFAULT, " %s=%s%s", c.first.c_str(), s.c_str(), unit); } } diff --git a/thirdparty_builtin/benchmark-1.5.0/src/counter.cc b/thirdparty_builtin/benchmark-1.8.0/src/counter.cc similarity index 95% rename from thirdparty_builtin/benchmark-1.5.0/src/counter.cc rename to thirdparty_builtin/benchmark-1.8.0/src/counter.cc index c248ea110..cf5b78ee3 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/counter.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/counter.cc @@ -32,6 +32,10 @@ double Finish(Counter const& c, IterationCount iterations, double cpu_time, if (c.flags & Counter::kAvgIterations) { v /= iterations; } + + if (c.flags & Counter::kInvert) { // Invert is *always* last. + v = 1.0 / v; + } return v; } diff --git a/thirdparty_builtin/benchmark-1.5.0/src/counter.h b/thirdparty_builtin/benchmark-1.8.0/src/counter.h similarity index 91% rename from thirdparty_builtin/benchmark-1.5.0/src/counter.h rename to thirdparty_builtin/benchmark-1.8.0/src/counter.h index 1ad46d494..1f5a58e31 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/counter.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/counter.h @@ -12,6 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +#ifndef BENCHMARK_COUNTER_H_ +#define BENCHMARK_COUNTER_H_ + #include "benchmark/benchmark.h" namespace benchmark { @@ -25,3 +28,5 @@ bool SameNames(UserCounters const& l, UserCounters const& r); } // end namespace internal } // end namespace benchmark + +#endif // BENCHMARK_COUNTER_H_ diff --git a/thirdparty_builtin/benchmark-1.5.0/src/csv_reporter.cc b/thirdparty_builtin/benchmark-1.8.0/src/csv_reporter.cc similarity index 90% rename from thirdparty_builtin/benchmark-1.5.0/src/csv_reporter.cc rename to thirdparty_builtin/benchmark-1.8.0/src/csv_reporter.cc index af2c18fc8..7b56da107 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/csv_reporter.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/csv_reporter.cc @@ -12,9 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "benchmark/benchmark.h" -#include "complexity.h" - #include #include #include @@ -22,7 +19,9 @@ #include #include +#include "benchmark/benchmark.h" #include "check.h" +#include "complexity.h" #include "string_util.h" #include "timers.h" @@ -37,23 +36,29 @@ std::vector elements = { "error_occurred", "error_message"}; } // namespace -std::string CsvEscape(const std::string & s) { +std::string CsvEscape(const std::string& s) { std::string tmp; tmp.reserve(s.size() + 2); for (char c : s) { switch (c) { - case '"' : tmp += "\"\""; break; - default : tmp += c; break; + case '"': + tmp += "\"\""; + break; + default: + tmp += c; + break; } } return '"' + tmp + '"'; } +BENCHMARK_EXPORT bool CSVReporter::ReportContext(const Context& context) { PrintBasicContext(&GetErrorStream(), context); return true; } +BENCHMARK_EXPORT void CSVReporter::ReportRuns(const std::vector& reports) { std::ostream& Out = GetOutputStream(); @@ -85,7 +90,8 @@ void CSVReporter::ReportRuns(const std::vector& reports) { for (const auto& cnt : run.counters) { if (cnt.first == "bytes_per_second" || cnt.first == "items_per_second") continue; - CHECK(user_counter_names_.find(cnt.first) != user_counter_names_.end()) + BM_CHECK(user_counter_names_.find(cnt.first) != + user_counter_names_.end()) << "All counters must be present in each run. " << "Counter named \"" << cnt.first << "\" was not in a run after being added to the header"; @@ -99,13 +105,14 @@ void CSVReporter::ReportRuns(const std::vector& reports) { } } +BENCHMARK_EXPORT void CSVReporter::PrintRunData(const Run& run) { std::ostream& Out = GetOutputStream(); Out << CsvEscape(run.benchmark_name()) << ","; - if (run.error_occurred) { + if (run.skipped) { Out << std::string(elements.size() - 3, ','); - Out << "true,"; - Out << CsvEscape(run.error_message) << "\n"; + Out << std::boolalpha << (internal::SkippedWithError == run.skipped) << ","; + Out << CsvEscape(run.skip_message) << "\n"; return; } diff --git a/thirdparty_builtin/benchmark-1.5.0/src/cycleclock.h b/thirdparty_builtin/benchmark-1.8.0/src/cycleclock.h similarity index 75% rename from thirdparty_builtin/benchmark-1.5.0/src/cycleclock.h rename to thirdparty_builtin/benchmark-1.8.0/src/cycleclock.h index f5e37b011..ae1ef2d2d 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/cycleclock.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/cycleclock.h @@ -36,7 +36,8 @@ // declarations of some other intrinsics, breaking compilation. // Therefore, we simply declare __rdtsc ourselves. See also // http://connect.microsoft.com/VisualStudio/feedback/details/262047 -#if defined(COMPILER_MSVC) && !defined(_M_IX86) +#if defined(COMPILER_MSVC) && !defined(_M_IX86) && !defined(_M_ARM64) && \ + !defined(_M_ARM64EC) extern "C" uint64_t __rdtsc(); #pragma intrinsic(__rdtsc) #endif @@ -84,13 +85,21 @@ inline BENCHMARK_ALWAYS_INLINE int64_t Now() { return (high << 32) | low; #elif defined(__powerpc__) || defined(__ppc__) // This returns a time-base, which is not always precisely a cycle-count. - int64_t tbl, tbu0, tbu1; - asm("mftbu %0" : "=r"(tbu0)); - asm("mftb %0" : "=r"(tbl)); - asm("mftbu %0" : "=r"(tbu1)); - tbl &= -static_cast(tbu0 == tbu1); - // high 32 bits in tbu1; low 32 bits in tbl (tbu0 is garbage) - return (tbu1 << 32) | tbl; +#if defined(__powerpc64__) || defined(__ppc64__) + int64_t tb; + asm volatile("mfspr %0, 268" : "=r"(tb)); + return tb; +#else + uint32_t tbl, tbu0, tbu1; + asm volatile( + "mftbu %0\n" + "mftb %1\n" + "mftbu %2" + : "=r"(tbu0), "=r"(tbl), "=r"(tbu1)); + tbl &= -static_cast(tbu0 == tbu1); + // high 32 bits in tbu1; low 32 bits in tbl (tbu0 is no longer needed) + return (static_cast(tbu1) << 32) | tbl; +#endif #elif defined(__sparc__) int64_t tick; asm(".byte 0x83, 0x41, 0x00, 0x00"); @@ -106,6 +115,12 @@ inline BENCHMARK_ALWAYS_INLINE int64_t Now() { // when I know it will work. Otherwise, I'll use __rdtsc and hope // the code is being compiled with a non-ancient compiler. _asm rdtsc +#elif defined(COMPILER_MSVC) && (defined(_M_ARM64) || defined(_M_ARM64EC)) + // See // https://docs.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics + // and https://reviews.llvm.org/D53115 + int64_t virtual_timer_value; + virtual_timer_value = _ReadStatusReg(ARM64_CNTVCT); + return virtual_timer_value; #elif defined(COMPILER_MSVC) return __rdtsc(); #elif defined(BENCHMARK_OS_NACL) @@ -118,7 +133,7 @@ inline BENCHMARK_ALWAYS_INLINE int64_t Now() { // Native Client does not provide any API to access cycle counter. // Use clock_gettime(CLOCK_MONOTONIC, ...) instead of gettimeofday - // because is provides nanosecond resolution (which is noticable at + // because is provides nanosecond resolution (which is noticeable at // least for PNaCl modules running on x86 Mac & Linux). // Initialize to always return 0 if clock_gettime fails. struct timespec ts = {0, 0}; @@ -153,17 +168,55 @@ inline BENCHMARK_ALWAYS_INLINE int64_t Now() { struct timeval tv; gettimeofday(&tv, nullptr); return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; -#elif defined(__mips__) +#elif defined(__mips__) || defined(__m68k__) // mips apparently only allows rdtsc for superusers, so we fall // back to gettimeofday. It's possible clock_gettime would be better. struct timeval tv; gettimeofday(&tv, nullptr); return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +#elif defined(__loongarch__) || defined(__csky__) + struct timeval tv; + gettimeofday(&tv, nullptr); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; #elif defined(__s390__) // Covers both s390 and s390x. // Return the CPU clock. uint64_t tsc; +#if defined(BENCHMARK_OS_ZOS) && defined(COMPILER_IBMXL) + // z/OS XL compiler HLASM syntax. + asm(" stck %0" : "=m"(tsc) : : "cc"); +#else asm("stck %0" : "=Q"(tsc) : : "cc"); +#endif return tsc; +#elif defined(__riscv) // RISC-V + // Use RDCYCLE (and RDCYCLEH on riscv32) +#if __riscv_xlen == 32 + uint32_t cycles_lo, cycles_hi0, cycles_hi1; + // This asm also includes the PowerPC overflow handling strategy, as above. + // Implemented in assembly because Clang insisted on branching. + asm volatile( + "rdcycleh %0\n" + "rdcycle %1\n" + "rdcycleh %2\n" + "sub %0, %0, %2\n" + "seqz %0, %0\n" + "sub %0, zero, %0\n" + "and %1, %1, %0\n" + : "=r"(cycles_hi0), "=r"(cycles_lo), "=r"(cycles_hi1)); + return (static_cast(cycles_hi1) << 32) | cycles_lo; +#else + uint64_t cycles; + asm volatile("rdcycle %0" : "=r"(cycles)); + return cycles; +#endif +#elif defined(__e2k__) || defined(__elbrus__) + struct timeval tv; + gettimeofday(&tv, nullptr); + return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; +#elif defined(__hexagon__) + uint64_t pcycle; + asm volatile("%0 = C15:14" : "=r"(pcycle)); + return static_cast(pcycle); #else // The soft failover to a generic implementation is automatic only for ARM. // For other platforms the developer is expected to make an attempt to create diff --git a/thirdparty_builtin/benchmark-1.5.0/src/internal_macros.h b/thirdparty_builtin/benchmark-1.8.0/src/internal_macros.h similarity index 74% rename from thirdparty_builtin/benchmark-1.5.0/src/internal_macros.h rename to thirdparty_builtin/benchmark-1.8.0/src/internal_macros.h index 6adf00d05..8dd7d0c65 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/internal_macros.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/internal_macros.h @@ -1,8 +1,6 @@ #ifndef BENCHMARK_INTERNAL_MACROS_H_ #define BENCHMARK_INTERNAL_MACROS_H_ -#include "benchmark/benchmark.h" - /* Needed to detect STL */ #include @@ -13,7 +11,11 @@ #endif #if defined(__clang__) - #if !defined(COMPILER_CLANG) + #if defined(__ibmxl__) + #if !defined(COMPILER_IBMXL) + #define COMPILER_IBMXL + #endif + #elif !defined(COMPILER_CLANG) #define COMPILER_CLANG #endif #elif defined(_MSC_VER) @@ -40,6 +42,19 @@ #define BENCHMARK_OS_CYGWIN 1 #elif defined(_WIN32) #define BENCHMARK_OS_WINDOWS 1 + // WINAPI_FAMILY_PARTITION is defined in winapifamily.h. + // We include windows.h which implicitly includes winapifamily.h for compatibility. + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include + #if defined(WINAPI_FAMILY_PARTITION) + #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) + #define BENCHMARK_OS_WINDOWS_WIN32 1 + #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) + #define BENCHMARK_OS_WINDOWS_RT 1 + #endif + #endif #if defined(__MINGW32__) #define BENCHMARK_OS_MINGW 1 #endif @@ -58,6 +73,8 @@ #define BENCHMARK_OS_NETBSD 1 #elif defined(__OpenBSD__) #define BENCHMARK_OS_OPENBSD 1 +#elif defined(__DragonFly__) + #define BENCHMARK_OS_DRAGONFLY 1 #elif defined(__linux__) #define BENCHMARK_OS_LINUX 1 #elif defined(__native_client__) @@ -72,6 +89,10 @@ #define BENCHMARK_OS_SOLARIS 1 #elif defined(__QNX__) #define BENCHMARK_OS_QNX 1 +#elif defined(__MVS__) +#define BENCHMARK_OS_ZOS 1 +#elif defined(__hexagon__) +#define BENCHMARK_OS_QURT 1 #endif #if defined(__ANDROID__) && defined(__GLIBCXX__) diff --git a/thirdparty_builtin/benchmark-1.5.0/src/json_reporter.cc b/thirdparty_builtin/benchmark-1.8.0/src/json_reporter.cc similarity index 65% rename from thirdparty_builtin/benchmark-1.5.0/src/json_reporter.cc rename to thirdparty_builtin/benchmark-1.8.0/src/json_reporter.cc index 11db2b99d..6559dfd5e 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/json_reporter.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/json_reporter.cc @@ -12,9 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "benchmark/benchmark.h" -#include "complexity.h" - #include #include #include @@ -25,41 +22,61 @@ #include #include +#include "benchmark/benchmark.h" +#include "complexity.h" #include "string_util.h" #include "timers.h" namespace benchmark { - namespace { -std::string StrEscape(const std::string & s) { +std::string StrEscape(const std::string& s) { std::string tmp; tmp.reserve(s.size()); for (char c : s) { switch (c) { - case '\b': tmp += "\\b"; break; - case '\f': tmp += "\\f"; break; - case '\n': tmp += "\\n"; break; - case '\r': tmp += "\\r"; break; - case '\t': tmp += "\\t"; break; - case '\\': tmp += "\\\\"; break; - case '"' : tmp += "\\\""; break; - default : tmp += c; break; + case '\b': + tmp += "\\b"; + break; + case '\f': + tmp += "\\f"; + break; + case '\n': + tmp += "\\n"; + break; + case '\r': + tmp += "\\r"; + break; + case '\t': + tmp += "\\t"; + break; + case '\\': + tmp += "\\\\"; + break; + case '"': + tmp += "\\\""; + break; + default: + tmp += c; + break; } } return tmp; } std::string FormatKV(std::string const& key, std::string const& value) { - return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), StrEscape(value).c_str()); + return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), + StrEscape(value).c_str()); } std::string FormatKV(std::string const& key, const char* value) { - return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), StrEscape(value).c_str()); + return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), + StrEscape(value).c_str()); } std::string FormatKV(std::string const& key, bool value) { - return StrFormat("\"%s\": %s", StrEscape(key).c_str(), value ? "true" : "false"); + return StrFormat("\"%s\": %s", StrEscape(key).c_str(), + value ? "true" : "false"); } std::string FormatKV(std::string const& key, int64_t value) { @@ -68,12 +85,6 @@ std::string FormatKV(std::string const& key, int64_t value) { return ss.str(); } -std::string FormatKV(std::string const& key, IterationCount value) { - std::stringstream ss; - ss << '"' << StrEscape(key) << "\": " << value; - return ss.str(); -} - std::string FormatKV(std::string const& key, double value) { std::stringstream ss; ss << '"' << StrEscape(key) << "\": "; @@ -92,7 +103,7 @@ std::string FormatKV(std::string const& key, double value) { return ss.str(); } -int64_t RoundDouble(double v) { return static_cast(v + 0.5); } +int64_t RoundDouble(double v) { return std::lround(v); } } // end namespace @@ -122,8 +133,12 @@ bool JSONReporter::ReportContext(const Context& context) { << FormatKV("mhz_per_cpu", RoundDouble(info.cycles_per_second / 1000000.0)) << ",\n"; - out << indent << FormatKV("cpu_scaling_enabled", info.scaling_enabled) - << ",\n"; + if (CPUInfo::Scaling::UNKNOWN != info.scaling) { + out << indent + << FormatKV("cpu_scaling_enabled", + info.scaling == CPUInfo::Scaling::ENABLED ? true : false) + << ",\n"; + } out << indent << "\"caches\": [\n"; indent = std::string(6, ' '); @@ -134,8 +149,8 @@ bool JSONReporter::ReportContext(const Context& context) { out << cache_indent << FormatKV("type", CI.type) << ",\n"; out << cache_indent << FormatKV("level", static_cast(CI.level)) << ",\n"; - out << cache_indent - << FormatKV("size", static_cast(CI.size) * 1000u) << ",\n"; + out << cache_indent << FormatKV("size", static_cast(CI.size)) + << ",\n"; out << cache_indent << FormatKV("num_sharing", static_cast(CI.num_sharing)) << "\n"; @@ -157,7 +172,19 @@ bool JSONReporter::ReportContext(const Context& context) { #else const char build_type[] = "debug"; #endif - out << indent << FormatKV("library_build_type", build_type) << "\n"; + out << indent << FormatKV("library_build_type", build_type); + + std::map* global_context = + internal::GetGlobalContext(); + + if (global_context != nullptr) { + for (const auto& kv : *global_context) { + out << ",\n"; + out << indent << FormatKV(kv.first, kv.second); + } + } + out << "\n"; + // Close context block and open the list of benchmarks. out << inner_indent << "},\n"; out << inner_indent << "\"benchmarks\": [\n"; @@ -195,6 +222,10 @@ void JSONReporter::PrintRunData(Run const& run) { std::string indent(6, ' '); std::ostream& out = GetOutputStream(); out << indent << FormatKV("name", run.benchmark_name()) << ",\n"; + out << indent << FormatKV("family_index", run.family_index) << ",\n"; + out << indent + << FormatKV("per_family_instance_index", run.per_family_instance_index) + << ",\n"; out << indent << FormatKV("run_name", run.run_name.str()) << ",\n"; out << indent << FormatKV("run_type", [&run]() -> const char* { switch (run.run_type) { @@ -213,15 +244,36 @@ void JSONReporter::PrintRunData(Run const& run) { out << indent << FormatKV("threads", run.threads) << ",\n"; if (run.run_type == BenchmarkReporter::Run::RT_Aggregate) { out << indent << FormatKV("aggregate_name", run.aggregate_name) << ",\n"; + out << indent << FormatKV("aggregate_unit", [&run]() -> const char* { + switch (run.aggregate_unit) { + case StatisticUnit::kTime: + return "time"; + case StatisticUnit::kPercentage: + return "percentage"; + } + BENCHMARK_UNREACHABLE(); + }()) << ",\n"; } - if (run.error_occurred) { - out << indent << FormatKV("error_occurred", run.error_occurred) << ",\n"; - out << indent << FormatKV("error_message", run.error_message) << ",\n"; + if (internal::SkippedWithError == run.skipped) { + out << indent << FormatKV("error_occurred", true) << ",\n"; + out << indent << FormatKV("error_message", run.skip_message) << ",\n"; + } else if (internal::SkippedWithMessage == run.skipped) { + out << indent << FormatKV("skipped", true) << ",\n"; + out << indent << FormatKV("skip_message", run.skip_message) << ",\n"; } if (!run.report_big_o && !run.report_rms) { out << indent << FormatKV("iterations", run.iterations) << ",\n"; - out << indent << FormatKV("real_time", run.GetAdjustedRealTime()) << ",\n"; - out << indent << FormatKV("cpu_time", run.GetAdjustedCPUTime()); + if (run.run_type != Run::RT_Aggregate || + run.aggregate_unit == StatisticUnit::kTime) { + out << indent << FormatKV("real_time", run.GetAdjustedRealTime()) + << ",\n"; + out << indent << FormatKV("cpu_time", run.GetAdjustedCPUTime()); + } else { + assert(run.aggregate_unit == StatisticUnit::kPercentage); + out << indent << FormatKV("real_time", run.real_accumulated_time) + << ",\n"; + out << indent << FormatKV("cpu_time", run.cpu_accumulated_time); + } out << ",\n" << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); } else if (run.report_big_o) { @@ -239,9 +291,21 @@ void JSONReporter::PrintRunData(Run const& run) { out << ",\n" << indent << FormatKV(c.first, c.second); } - if (run.has_memory_result) { + if (run.memory_result) { + const MemoryManager::Result memory_result = *run.memory_result; out << ",\n" << indent << FormatKV("allocs_per_iter", run.allocs_per_iter); - out << ",\n" << indent << FormatKV("max_bytes_used", run.max_bytes_used); + out << ",\n" + << indent << FormatKV("max_bytes_used", memory_result.max_bytes_used); + + auto report_if_present = [&out, &indent](const std::string& label, + int64_t val) { + if (val != MemoryManager::TombstoneValue) + out << ",\n" << indent << FormatKV(label, val); + }; + + report_if_present("total_allocated_bytes", + memory_result.total_allocated_bytes); + report_if_present("net_heap_growth", memory_result.net_heap_growth); } if (!run.report_label.empty()) { @@ -250,4 +314,7 @@ void JSONReporter::PrintRunData(Run const& run) { out << '\n'; } +const int64_t MemoryManager::TombstoneValue = + std::numeric_limits::max(); + } // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/log.h b/thirdparty_builtin/benchmark-1.8.0/src/log.h similarity index 63% rename from thirdparty_builtin/benchmark-1.5.0/src/log.h rename to thirdparty_builtin/benchmark-1.8.0/src/log.h index 47d0c35c0..45701667a 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/log.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/log.h @@ -4,7 +4,12 @@ #include #include -#include "benchmark/benchmark.h" +// NOTE: this is also defined in benchmark.h but we're trying to avoid a +// dependency. +// The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer. +#if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) +#define BENCHMARK_HAS_CXX11 +#endif namespace benchmark { namespace internal { @@ -23,7 +28,16 @@ class LogType { private: LogType(std::ostream* out) : out_(out) {} std::ostream* out_; - BENCHMARK_DISALLOW_COPY_AND_ASSIGN(LogType); + + // NOTE: we could use BENCHMARK_DISALLOW_COPY_AND_ASSIGN but we shouldn't have + // a dependency on benchmark.h from here. +#ifndef BENCHMARK_HAS_CXX11 + LogType(const LogType&); + LogType& operator=(const LogType&); +#else + LogType(const LogType&) = delete; + LogType& operator=(const LogType&) = delete; +#endif }; template @@ -47,13 +61,13 @@ inline int& LogLevel() { } inline LogType& GetNullLogInstance() { - static LogType log(nullptr); - return log; + static LogType null_log((std::ostream*)nullptr); + return null_log; } inline LogType& GetErrorLogInstance() { - static LogType log(&std::clog); - return log; + static LogType error_log(&std::clog); + return error_log; } inline LogType& GetLogInstanceForLevel(int level) { @@ -67,7 +81,7 @@ inline LogType& GetLogInstanceForLevel(int level) { } // end namespace benchmark // clang-format off -#define VLOG(x) \ +#define BM_VLOG(x) \ (::benchmark::internal::GetLogInstanceForLevel(x) << "-- LOG(" << x << "):" \ " ") // clang-format on diff --git a/thirdparty_builtin/benchmark-1.5.0/src/mutex.h b/thirdparty_builtin/benchmark-1.8.0/src/mutex.h similarity index 66% rename from thirdparty_builtin/benchmark-1.5.0/src/mutex.h rename to thirdparty_builtin/benchmark-1.8.0/src/mutex.h index 5f461d05a..bec78d9e5 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/mutex.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/mutex.h @@ -9,60 +9,60 @@ // Enable thread safety attributes only with clang. // The attributes can be safely erased when compiling with other compilers. #if defined(HAVE_THREAD_SAFETY_ATTRIBUTES) -#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) +#define THREAD_ANNOTATION_ATTRIBUTE_(x) __attribute__((x)) #else -#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op +#define THREAD_ANNOTATION_ATTRIBUTE_(x) // no-op #endif -#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) +#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(capability(x)) -#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) +#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE_(scoped_lockable) -#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) +#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(guarded_by(x)) -#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) +#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(pt_guarded_by(x)) #define ACQUIRED_BEFORE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(acquired_before(__VA_ARGS__)) #define ACQUIRED_AFTER(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(acquired_after(__VA_ARGS__)) #define REQUIRES(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(requires_capability(__VA_ARGS__)) #define REQUIRES_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(requires_shared_capability(__VA_ARGS__)) #define ACQUIRE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(acquire_capability(__VA_ARGS__)) #define ACQUIRE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(acquire_shared_capability(__VA_ARGS__)) #define RELEASE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(release_capability(__VA_ARGS__)) #define RELEASE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(release_shared_capability(__VA_ARGS__)) #define TRY_ACQUIRE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_capability(__VA_ARGS__)) #define TRY_ACQUIRE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) + THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_shared_capability(__VA_ARGS__)) -#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) +#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE_(locks_excluded(__VA_ARGS__)) -#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) +#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(assert_capability(x)) #define ASSERT_SHARED_CAPABILITY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) + THREAD_ANNOTATION_ATTRIBUTE_(assert_shared_capability(x)) -#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) +#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(lock_returned(x)) #define NO_THREAD_SAFETY_ANALYSIS \ - THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) + THREAD_ANNOTATION_ATTRIBUTE_(no_thread_safety_analysis) namespace benchmark { @@ -71,7 +71,7 @@ typedef std::condition_variable Condition; // NOTE: Wrappers for std::mutex and std::unique_lock are provided so that // we can annotate them with thread safety attributes and use the // -Wthread-safety warning with clang. The standard library types cannot be -// used directly because they do not provided the required annotations. +// used directly because they do not provide the required annotations. class CAPABILITY("mutex") Mutex { public: Mutex() {} @@ -130,7 +130,7 @@ class Barrier { // entered the barrier. Returns iff this is the last thread to // enter the barrier. bool createBarrier(MutexLock& ml) REQUIRES(lock_) { - CHECK_LT(entered_, running_threads_); + BM_CHECK_LT(entered_, running_threads_); entered_++; if (entered_ < running_threads_) { // Wait for all threads to enter diff --git a/thirdparty_builtin/benchmark-1.8.0/src/perf_counters.cc b/thirdparty_builtin/benchmark-1.8.0/src/perf_counters.cc new file mode 100644 index 000000000..3980ea053 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/perf_counters.cc @@ -0,0 +1,269 @@ +// Copyright 2021 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "perf_counters.h" + +#include +#include +#include + +#if defined HAVE_LIBPFM +#include "perfmon/pfmlib.h" +#include "perfmon/pfmlib_perf_event.h" +#endif + +namespace benchmark { +namespace internal { + +constexpr size_t PerfCounterValues::kMaxCounters; + +#if defined HAVE_LIBPFM + +size_t PerfCounterValues::Read(const std::vector& leaders) { + // Create a pointer for multiple reads + const size_t bufsize = values_.size() * sizeof(values_[0]); + char* ptr = reinterpret_cast(values_.data()); + size_t size = bufsize; + for (int lead : leaders) { + auto read_bytes = ::read(lead, ptr, size); + if (read_bytes >= ssize_t(sizeof(uint64_t))) { + // Actual data bytes are all bytes minus initial padding + std::size_t data_bytes = read_bytes - sizeof(uint64_t); + // This should be very cheap since it's in hot cache + std::memmove(ptr, ptr + sizeof(uint64_t), data_bytes); + // Increment our counters + ptr += data_bytes; + size -= data_bytes; + } else { + int err = errno; + GetErrorLogInstance() << "Error reading lead " << lead << " errno:" << err + << " " << ::strerror(err) << "\n"; + return 0; + } + } + return (bufsize - size) / sizeof(uint64_t); +} + +const bool PerfCounters::kSupported = true; + +bool PerfCounters::Initialize() { return pfm_initialize() == PFM_SUCCESS; } + +bool PerfCounters::IsCounterSupported(const std::string& name) { + perf_event_attr_t attr; + std::memset(&attr, 0, sizeof(attr)); + pfm_perf_encode_arg_t arg; + std::memset(&arg, 0, sizeof(arg)); + arg.attr = &attr; + const int mode = PFM_PLM3; // user mode only + int ret = pfm_get_os_event_encoding(name.c_str(), mode, PFM_OS_PERF_EVENT_EXT, + &arg); + return (ret == PFM_SUCCESS); +} + +PerfCounters PerfCounters::Create( + const std::vector& counter_names) { + // Valid counters will populate these arrays but we start empty + std::vector valid_names; + std::vector counter_ids; + std::vector leader_ids; + + // Resize to the maximum possible + valid_names.reserve(counter_names.size()); + counter_ids.reserve(counter_names.size()); + + const int kCounterMode = PFM_PLM3; // user mode only + + // Group leads will be assigned on demand. The idea is that once we cannot + // create a counter descriptor, the reason is that this group has maxed out + // so we set the group_id again to -1 and retry - giving the algorithm a + // chance to create a new group leader to hold the next set of counters. + int group_id = -1; + + // Loop through all performance counters + for (size_t i = 0; i < counter_names.size(); ++i) { + // we are about to push into the valid names vector + // check if we did not reach the maximum + if (valid_names.size() == PerfCounterValues::kMaxCounters) { + // Log a message if we maxed out and stop adding + GetErrorLogInstance() + << counter_names.size() << " counters were requested. The maximum is " + << PerfCounterValues::kMaxCounters << " and " << valid_names.size() + << " were already added. All remaining counters will be ignored\n"; + // stop the loop and return what we have already + break; + } + + // Check if this name is empty + const auto& name = counter_names[i]; + if (name.empty()) { + GetErrorLogInstance() + << "A performance counter name was the empty string\n"; + continue; + } + + // Here first means first in group, ie the group leader + const bool is_first = (group_id < 0); + + // This struct will be populated by libpfm from the counter string + // and then fed into the syscall perf_event_open + struct perf_event_attr attr {}; + attr.size = sizeof(attr); + + // This is the input struct to libpfm. + pfm_perf_encode_arg_t arg{}; + arg.attr = &attr; + const int pfm_get = pfm_get_os_event_encoding(name.c_str(), kCounterMode, + PFM_OS_PERF_EVENT, &arg); + if (pfm_get != PFM_SUCCESS) { + GetErrorLogInstance() + << "Unknown performance counter name: " << name << "\n"; + continue; + } + + // We then proceed to populate the remaining fields in our attribute struct + // Note: the man page for perf_event_create suggests inherit = true and + // read_format = PERF_FORMAT_GROUP don't work together, but that's not the + // case. + attr.disabled = is_first; + attr.inherit = true; + attr.pinned = is_first; + attr.exclude_kernel = true; + attr.exclude_user = false; + attr.exclude_hv = true; + + // Read all counters in a group in one read. + attr.read_format = PERF_FORMAT_GROUP; + + int id = -1; + while (id < 0) { + static constexpr size_t kNrOfSyscallRetries = 5; + // Retry syscall as it was interrupted often (b/64774091). + for (size_t num_retries = 0; num_retries < kNrOfSyscallRetries; + ++num_retries) { + id = perf_event_open(&attr, 0, -1, group_id, 0); + if (id >= 0 || errno != EINTR) { + break; + } + } + if (id < 0) { + // If the file descriptor is negative we might have reached a limit + // in the current group. Set the group_id to -1 and retry + if (group_id >= 0) { + // Create a new group + group_id = -1; + } else { + // At this point we have already retried to set a new group id and + // failed. We then give up. + break; + } + } + } + + // We failed to get a new file descriptor. We might have reached a hard + // hardware limit that cannot be resolved even with group multiplexing + if (id < 0) { + GetErrorLogInstance() << "***WARNING** Failed to get a file descriptor " + "for performance counter " + << name << ". Ignoring\n"; + + // We give up on this counter but try to keep going + // as the others would be fine + continue; + } + if (group_id < 0) { + // This is a leader, store and assign it to the current file descriptor + leader_ids.push_back(id); + group_id = id; + } + // This is a valid counter, add it to our descriptor's list + counter_ids.push_back(id); + valid_names.push_back(name); + } + + // Loop through all group leaders activating them + // There is another option of starting ALL counters in a process but + // that would be far reaching an intrusion. If the user is using PMCs + // by themselves then this would have a side effect on them. It is + // friendlier to loop through all groups individually. + for (int lead : leader_ids) { + if (ioctl(lead, PERF_EVENT_IOC_ENABLE) != 0) { + // This should never happen but if it does, we give up on the + // entire batch as recovery would be a mess. + GetErrorLogInstance() << "***WARNING*** Failed to start counters. " + "Claring out all counters.\n"; + + // Close all peformance counters + for (int id : counter_ids) { + ::close(id); + } + + // Return an empty object so our internal state is still good and + // the process can continue normally without impact + return NoCounters(); + } + } + + return PerfCounters(std::move(valid_names), std::move(counter_ids), + std::move(leader_ids)); +} + +void PerfCounters::CloseCounters() const { + if (counter_ids_.empty()) { + return; + } + for (int lead : leader_ids_) { + ioctl(lead, PERF_EVENT_IOC_DISABLE); + } + for (int fd : counter_ids_) { + close(fd); + } +} +#else // defined HAVE_LIBPFM +size_t PerfCounterValues::Read(const std::vector&) { return 0; } + +const bool PerfCounters::kSupported = false; + +bool PerfCounters::Initialize() { return false; } + +bool PerfCounters::IsCounterSupported(const std::string&) { return false; } + +PerfCounters PerfCounters::Create( + const std::vector& counter_names) { + if (!counter_names.empty()) { + GetErrorLogInstance() << "Performance counters not supported."; + } + return NoCounters(); +} + +void PerfCounters::CloseCounters() const {} +#endif // defined HAVE_LIBPFM + +PerfCountersMeasurement::PerfCountersMeasurement( + const std::vector& counter_names) + : start_values_(counter_names.size()), end_values_(counter_names.size()) { + counters_ = PerfCounters::Create(counter_names); +} + +PerfCounters& PerfCounters::operator=(PerfCounters&& other) noexcept { + if (this != &other) { + CloseCounters(); + + counter_ids_ = std::move(other.counter_ids_); + leader_ids_ = std::move(other.leader_ids_); + counter_names_ = std::move(other.counter_names_); + } + return *this; +} +} // namespace internal +} // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/src/perf_counters.h b/thirdparty_builtin/benchmark-1.8.0/src/perf_counters.h new file mode 100644 index 000000000..152a6f256 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/src/perf_counters.h @@ -0,0 +1,202 @@ +// Copyright 2021 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef BENCHMARK_PERF_COUNTERS_H +#define BENCHMARK_PERF_COUNTERS_H + +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" +#include "check.h" +#include "log.h" +#include "mutex.h" + +#ifndef BENCHMARK_OS_WINDOWS +#include +#endif + +#if defined(_MSC_VER) +#pragma warning(push) +// C4251: needs to have dll-interface to be used by clients of class +#pragma warning(disable : 4251) +#endif + +namespace benchmark { +namespace internal { + +// Typically, we can only read a small number of counters. There is also a +// padding preceding counter values, when reading multiple counters with one +// syscall (which is desirable). PerfCounterValues abstracts these details. +// The implementation ensures the storage is inlined, and allows 0-based +// indexing into the counter values. +// The object is used in conjunction with a PerfCounters object, by passing it +// to Snapshot(). The Read() method relocates individual reads, discarding +// the initial padding from each group leader in the values buffer such that +// all user accesses through the [] operator are correct. +class BENCHMARK_EXPORT PerfCounterValues { + public: + explicit PerfCounterValues(size_t nr_counters) : nr_counters_(nr_counters) { + BM_CHECK_LE(nr_counters_, kMaxCounters); + } + + // We are reading correctly now so the values don't need to skip padding + uint64_t operator[](size_t pos) const { return values_[pos]; } + + // Increased the maximum to 32 only since the buffer + // is std::array<> backed + static constexpr size_t kMaxCounters = 32; + + private: + friend class PerfCounters; + // Get the byte buffer in which perf counters can be captured. + // This is used by PerfCounters::Read + std::pair get_data_buffer() { + return {reinterpret_cast(values_.data()), + sizeof(uint64_t) * (kPadding + nr_counters_)}; + } + + // This reading is complex and as the goal of this class is to + // abstract away the intrincacies of the reading process, this is + // a better place for it + size_t Read(const std::vector& leaders); + + // Move the padding to 2 due to the reading algorithm (1st padding plus a + // current read padding) + static constexpr size_t kPadding = 2; + std::array values_; + const size_t nr_counters_; +}; + +// Collect PMU counters. The object, once constructed, is ready to be used by +// calling read(). PMU counter collection is enabled from the time create() is +// called, to obtain the object, until the object's destructor is called. +class BENCHMARK_EXPORT PerfCounters final { + public: + // True iff this platform supports performance counters. + static const bool kSupported; + + // Returns an empty object + static PerfCounters NoCounters() { return PerfCounters(); } + + ~PerfCounters() { CloseCounters(); } + PerfCounters() = default; + PerfCounters(PerfCounters&&) = default; + PerfCounters(const PerfCounters&) = delete; + PerfCounters& operator=(PerfCounters&&) noexcept; + PerfCounters& operator=(const PerfCounters&) = delete; + + // Platform-specific implementations may choose to do some library + // initialization here. + static bool Initialize(); + + // Check if the given counter is supported, if the app wants to + // check before passing + static bool IsCounterSupported(const std::string& name); + + // Return a PerfCounters object ready to read the counters with the names + // specified. The values are user-mode only. The counter name format is + // implementation and OS specific. + // In case of failure, this method will in the worst case return an + // empty object whose state will still be valid. + static PerfCounters Create(const std::vector& counter_names); + + // Take a snapshot of the current value of the counters into the provided + // valid PerfCounterValues storage. The values are populated such that: + // names()[i]'s value is (*values)[i] + BENCHMARK_ALWAYS_INLINE bool Snapshot(PerfCounterValues* values) const { +#ifndef BENCHMARK_OS_WINDOWS + assert(values != nullptr); + return values->Read(leader_ids_) == counter_ids_.size(); +#else + (void)values; + return false; +#endif + } + + const std::vector& names() const { return counter_names_; } + size_t num_counters() const { return counter_names_.size(); } + + private: + PerfCounters(const std::vector& counter_names, + std::vector&& counter_ids, std::vector&& leader_ids) + : counter_ids_(std::move(counter_ids)), + leader_ids_(std::move(leader_ids)), + counter_names_(counter_names) {} + + void CloseCounters() const; + + std::vector counter_ids_; + std::vector leader_ids_; + std::vector counter_names_; +}; + +// Typical usage of the above primitives. +class BENCHMARK_EXPORT PerfCountersMeasurement final { + public: + PerfCountersMeasurement(const std::vector& counter_names); + + size_t num_counters() const { return counters_.num_counters(); } + + std::vector names() const { return counters_.names(); } + + BENCHMARK_ALWAYS_INLINE bool Start() { + if (num_counters() == 0) return true; + // Tell the compiler to not move instructions above/below where we take + // the snapshot. + ClobberMemory(); + valid_read_ &= counters_.Snapshot(&start_values_); + ClobberMemory(); + + return valid_read_; + } + + BENCHMARK_ALWAYS_INLINE bool Stop( + std::vector>& measurements) { + if (num_counters() == 0) return true; + // Tell the compiler to not move instructions above/below where we take + // the snapshot. + ClobberMemory(); + valid_read_ &= counters_.Snapshot(&end_values_); + ClobberMemory(); + + for (size_t i = 0; i < counters_.names().size(); ++i) { + double measurement = static_cast(end_values_[i]) - + static_cast(start_values_[i]); + measurements.push_back({counters_.names()[i], measurement}); + } + + return valid_read_; + } + + private: + PerfCounters counters_; + bool valid_read_ = true; + PerfCounterValues start_values_; + PerfCounterValues end_values_; +}; + +BENCHMARK_UNUSED static bool perf_init_anchor = PerfCounters::Initialize(); + +} // namespace internal +} // namespace benchmark + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +#endif // BENCHMARK_PERF_COUNTERS_H diff --git a/thirdparty_builtin/benchmark-1.5.0/src/re.h b/thirdparty_builtin/benchmark-1.8.0/src/re.h similarity index 99% rename from thirdparty_builtin/benchmark-1.5.0/src/re.h rename to thirdparty_builtin/benchmark-1.8.0/src/re.h index fbe25037b..630046782 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/re.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/re.h @@ -126,7 +126,7 @@ inline bool Regex::Init(const std::string& spec, std::string* error) { // regerror returns the number of bytes necessary to null terminate // the string, so we move that when assigning to error. - CHECK_NE(needed, 0); + BM_CHECK_NE(needed, 0); error->assign(errbuf, needed - 1); delete[] errbuf; diff --git a/thirdparty_builtin/benchmark-1.5.0/src/reporter.cc b/thirdparty_builtin/benchmark-1.8.0/src/reporter.cc similarity index 85% rename from thirdparty_builtin/benchmark-1.5.0/src/reporter.cc rename to thirdparty_builtin/benchmark-1.8.0/src/reporter.cc index 4d3e477d4..076bc31a2 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/reporter.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/reporter.cc @@ -12,17 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "benchmark/benchmark.h" -#include "timers.h" - #include - #include +#include +#include #include #include +#include "benchmark/benchmark.h" #include "check.h" #include "string_util.h" +#include "timers.h" namespace benchmark { @@ -33,10 +33,14 @@ BenchmarkReporter::~BenchmarkReporter() {} void BenchmarkReporter::PrintBasicContext(std::ostream *out, Context const &context) { - CHECK(out) << "cannot be null"; + BM_CHECK(out) << "cannot be null"; auto &Out = *out; +#ifndef BENCHMARK_OS_QURT + // Date/time information is not available on QuRT. + // Attempting to get it via this call cause the binary to crash. Out << LocalDateTimeString() << "\n"; +#endif if (context.executable_name) Out << "Running " << context.executable_name << "\n"; @@ -49,7 +53,7 @@ void BenchmarkReporter::PrintBasicContext(std::ostream *out, Out << "CPU Caches:\n"; for (auto &CInfo : info.caches) { Out << " L" << CInfo.level << " " << CInfo.type << " " - << (CInfo.size / 1000) << "K"; + << (CInfo.size / 1024) << " KiB"; if (CInfo.num_sharing != 0) Out << " (x" << (info.num_cpus / CInfo.num_sharing) << ")"; Out << "\n"; @@ -64,7 +68,16 @@ void BenchmarkReporter::PrintBasicContext(std::ostream *out, Out << "\n"; } - if (info.scaling_enabled) { + std::map *global_context = + internal::GetGlobalContext(); + + if (global_context != nullptr) { + for (const auto &kv : *global_context) { + Out << kv.first << ": " << kv.second << "\n"; + } + } + + if (CPUInfo::Scaling::ENABLED == info.scaling) { Out << "***WARNING*** CPU scaling is enabled, the benchmark " "real time measurements may be noisy and will incur extra " "overhead.\n"; diff --git a/thirdparty_builtin/benchmark-1.5.0/src/statistics.cc b/thirdparty_builtin/benchmark-1.8.0/src/statistics.cc similarity index 79% rename from thirdparty_builtin/benchmark-1.5.0/src/statistics.cc rename to thirdparty_builtin/benchmark-1.8.0/src/statistics.cc index bd5a3d659..c4b54b271 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/statistics.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/statistics.cc @@ -13,15 +13,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "benchmark/benchmark.h" +#include "statistics.h" #include #include #include #include #include + +#include "benchmark/benchmark.h" #include "check.h" -#include "statistics.h" namespace benchmark { @@ -74,14 +75,22 @@ double StatisticsStdDev(const std::vector& v) { return Sqrt(v.size() / (v.size() - 1.0) * (avg_squares - Sqr(mean))); } +double StatisticsCV(const std::vector& v) { + if (v.size() < 2) return 0.0; + + const auto stddev = StatisticsStdDev(v); + const auto mean = StatisticsMean(v); + + return stddev / mean; +} + std::vector ComputeStats( const std::vector& reports) { typedef BenchmarkReporter::Run Run; std::vector results; - auto error_count = - std::count_if(reports.begin(), reports.end(), - [](Run const& run) { return run.error_occurred; }); + auto error_count = std::count_if(reports.begin(), reports.end(), + [](Run const& run) { return run.skipped; }); if (reports.size() - error_count < 2) { // We don't report aggregated data if there was a single run. @@ -108,26 +117,28 @@ std::vector ComputeStats( for (auto const& cnt : r.counters) { auto it = counter_stats.find(cnt.first); if (it == counter_stats.end()) { - counter_stats.insert({cnt.first, {cnt.second, std::vector{}}}); - it = counter_stats.find(cnt.first); + it = counter_stats + .emplace(cnt.first, + CounterStat{cnt.second, std::vector{}}) + .first; it->second.s.reserve(reports.size()); } else { - CHECK_EQ(counter_stats[cnt.first].c.flags, cnt.second.flags); + BM_CHECK_EQ(it->second.c.flags, cnt.second.flags); } } } // Populate the accumulators. for (Run const& run : reports) { - CHECK_EQ(reports[0].benchmark_name(), run.benchmark_name()); - CHECK_EQ(run_iterations, run.iterations); - if (run.error_occurred) continue; + BM_CHECK_EQ(reports[0].benchmark_name(), run.benchmark_name()); + BM_CHECK_EQ(run_iterations, run.iterations); + if (run.skipped) continue; real_accumulated_time_stat.emplace_back(run.real_accumulated_time); cpu_accumulated_time_stat.emplace_back(run.cpu_accumulated_time); // user counters for (auto const& cnt : run.counters) { auto it = counter_stats.find(cnt.first); - CHECK_NE(it, counter_stats.end()); + BM_CHECK_NE(it, counter_stats.end()); it->second.s.emplace_back(cnt.second); } } @@ -148,11 +159,14 @@ std::vector ComputeStats( // Get the data from the accumulator to BenchmarkReporter::Run's. Run data; data.run_name = reports[0].run_name; + data.family_index = reports[0].family_index; + data.per_family_instance_index = reports[0].per_family_instance_index; data.run_type = BenchmarkReporter::Run::RT_Aggregate; data.threads = reports[0].threads; data.repetitions = reports[0].repetitions; data.repetition_index = Run::no_repetition_index; data.aggregate_name = Stat.name_; + data.aggregate_unit = Stat.unit_; data.report_label = report_label; // It is incorrect to say that an aggregate is computed over @@ -165,13 +179,15 @@ std::vector ComputeStats( data.real_accumulated_time = Stat.compute_(real_accumulated_time_stat); data.cpu_accumulated_time = Stat.compute_(cpu_accumulated_time_stat); - // We will divide these times by data.iterations when reporting, but the - // data.iterations is not nessesairly the scale of these measurements, - // because in each repetition, these timers are sum over all the iterations. - // And if we want to say that the stats are over N repetitions and not - // M iterations, we need to multiply these by (N/M). - data.real_accumulated_time *= iteration_rescale_factor; - data.cpu_accumulated_time *= iteration_rescale_factor; + if (data.aggregate_unit == StatisticUnit::kTime) { + // We will divide these times by data.iterations when reporting, but the + // data.iterations is not necessarily the scale of these measurements, + // because in each repetition, these timers are sum over all the iters. + // And if we want to say that the stats are over N repetitions and not + // M iterations, we need to multiply these by (N/M). + data.real_accumulated_time *= iteration_rescale_factor; + data.cpu_accumulated_time *= iteration_rescale_factor; + } data.time_unit = reports[0].time_unit; diff --git a/thirdparty_builtin/benchmark-1.5.0/src/statistics.h b/thirdparty_builtin/benchmark-1.8.0/src/statistics.h similarity index 75% rename from thirdparty_builtin/benchmark-1.5.0/src/statistics.h rename to thirdparty_builtin/benchmark-1.8.0/src/statistics.h index 7eccc8553..6e5560e8f 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/statistics.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/statistics.h @@ -22,15 +22,22 @@ namespace benchmark { -// Return a vector containing the mean, median and standard devation information -// (and any user-specified info) for the specified list of reports. If 'reports' -// contains less than two non-errored runs an empty vector is returned +// Return a vector containing the mean, median and standard deviation +// information (and any user-specified info) for the specified list of reports. +// If 'reports' contains less than two non-errored runs an empty vector is +// returned +BENCHMARK_EXPORT std::vector ComputeStats( const std::vector& reports); +BENCHMARK_EXPORT double StatisticsMean(const std::vector& v); +BENCHMARK_EXPORT double StatisticsMedian(const std::vector& v); +BENCHMARK_EXPORT double StatisticsStdDev(const std::vector& v); +BENCHMARK_EXPORT +double StatisticsCV(const std::vector& v); } // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/string_util.cc b/thirdparty_builtin/benchmark-1.8.0/src/string_util.cc similarity index 83% rename from thirdparty_builtin/benchmark-1.5.0/src/string_util.cc rename to thirdparty_builtin/benchmark-1.8.0/src/string_util.cc index 39b01a171..5e2d24a3c 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/string_util.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/string_util.cc @@ -1,6 +1,9 @@ #include "string_util.h" #include +#ifdef BENCHMARK_STL_ANDROID_GNUSTL +#include +#endif #include #include #include @@ -91,10 +94,10 @@ std::string ExponentToPrefix(int64_t exponent, bool iec) { const char* array = (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); - if (iec) + if (iec) { return array[index] + std::string("i"); - else - return std::string(1, array[index]); + } + return std::string(1, array[index]); } std::string ToBinaryStringFullySpecified(double value, double threshold, @@ -130,25 +133,25 @@ std::string StrFormatImp(const char* msg, va_list args) { // TODO(ericwf): use std::array for first attempt to avoid one memory // allocation guess what the size might be std::array local_buff; - std::size_t size = local_buff.size(); + // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation // in the android-ndk - auto ret = vsnprintf(local_buff.data(), size, msg, args_cp); + auto ret = vsnprintf(local_buff.data(), local_buff.size(), msg, args_cp); va_end(args_cp); // handle empty expansion if (ret == 0) return std::string{}; - if (static_cast(ret) < size) + if (static_cast(ret) < local_buff.size()) return std::string(local_buff.data()); // we did not provide a long enough buffer on our first attempt. // add 1 to size to account for null-byte in size cast to prevent overflow - size = static_cast(ret) + 1; + std::size_t size = static_cast(ret) + 1; auto buff_ptr = std::unique_ptr(new char[size]); // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation // in the android-ndk - ret = vsnprintf(buff_ptr.get(), size, msg, args); + vsnprintf(buff_ptr.get(), size, msg, args); return std::string(buff_ptr.get()); } @@ -160,6 +163,19 @@ std::string StrFormat(const char* format, ...) { return tmp; } +std::vector StrSplit(const std::string& str, char delim) { + if (str.empty()) return {}; + std::vector ret; + size_t first = 0; + size_t next = str.find(delim); + for (; next != std::string::npos; + first = next + 1, next = str.find(delim, first)) { + ret.push_back(str.substr(first, next - first)); + } + ret.push_back(str.substr(first)); + return ret; +} + #ifdef BENCHMARK_STL_ANDROID_GNUSTL /* * GNU STL in Android NDK lacks support for some C++11 functions, including @@ -182,11 +198,10 @@ unsigned long stoul(const std::string& str, size_t* pos, int base) { /* Check for errors and return */ if (strtoulErrno == ERANGE) { - throw std::out_of_range( - "stoul failed: " + str + " is outside of range of unsigned long"); + throw std::out_of_range("stoul failed: " + str + + " is outside of range of unsigned long"); } else if (strEnd == strStart || strtoulErrno != 0) { - throw std::invalid_argument( - "stoul failed: " + str + " is not an integer"); + throw std::invalid_argument("stoul failed: " + str + " is not an integer"); } if (pos != nullptr) { *pos = static_cast(strEnd - strStart); @@ -209,11 +224,10 @@ int stoi(const std::string& str, size_t* pos, int base) { /* Check for errors and return */ if (strtolErrno == ERANGE || long(int(result)) != result) { - throw std::out_of_range( - "stoul failed: " + str + " is outside of range of int"); + throw std::out_of_range("stoul failed: " + str + + " is outside of range of int"); } else if (strEnd == strStart || strtolErrno != 0) { - throw std::invalid_argument( - "stoul failed: " + str + " is not an integer"); + throw std::invalid_argument("stoul failed: " + str + " is not an integer"); } if (pos != nullptr) { *pos = static_cast(strEnd - strStart); @@ -236,11 +250,10 @@ double stod(const std::string& str, size_t* pos) { /* Check for errors and return */ if (strtodErrno == ERANGE) { - throw std::out_of_range( - "stoul failed: " + str + " is outside of range of int"); + throw std::out_of_range("stoul failed: " + str + + " is outside of range of int"); } else if (strEnd == strStart || strtodErrno != 0) { - throw std::invalid_argument( - "stoul failed: " + str + " is not an integer"); + throw std::invalid_argument("stoul failed: " + str + " is not an integer"); } if (pos != nullptr) { *pos = static_cast(strEnd - strStart); diff --git a/thirdparty_builtin/benchmark-1.5.0/src/string_util.h b/thirdparty_builtin/benchmark-1.8.0/src/string_util.h similarity index 76% rename from thirdparty_builtin/benchmark-1.5.0/src/string_util.h rename to thirdparty_builtin/benchmark-1.8.0/src/string_util.h index 09d7b4bd2..37bdd2e98 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/string_util.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/string_util.h @@ -4,6 +4,10 @@ #include #include #include +#include + +#include "benchmark/export.h" +#include "check.h" #include "internal_macros.h" namespace benchmark { @@ -12,6 +16,7 @@ void AppendHumanReadable(int n, std::string* str); std::string HumanReadableNumber(double n, double one_k = 1024.0); +BENCHMARK_EXPORT #if defined(__MINGW32__) __attribute__((format(__MINGW_PRINTF_FORMAT, 1, 2))) #elif defined(__GNUC__) @@ -37,6 +42,11 @@ inline std::string StrCat(Args&&... args) { return ss.str(); } +BENCHMARK_EXPORT +std::vector StrSplit(const std::string& str, char delim); + +// Disable lint checking for this block since it re-implements C functions. +// NOLINTBEGIN #ifdef BENCHMARK_STL_ANDROID_GNUSTL /* * GNU STL in Android NDK lacks support for some C++11 functions, including @@ -45,14 +55,15 @@ inline std::string StrCat(Args&&... args) { * namespace, not std:: namespace. */ unsigned long stoul(const std::string& str, size_t* pos = nullptr, - int base = 10); + int base = 10); int stoi(const std::string& str, size_t* pos = nullptr, int base = 10); double stod(const std::string& str, size_t* pos = nullptr); #else -using std::stoul; -using std::stoi; -using std::stod; +using std::stod; // NOLINT(misc-unused-using-decls) +using std::stoi; // NOLINT(misc-unused-using-decls) +using std::stoul; // NOLINT(misc-unused-using-decls) #endif +// NOLINTEND } // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/sysinfo.cc b/thirdparty_builtin/benchmark-1.8.0/src/sysinfo.cc similarity index 54% rename from thirdparty_builtin/benchmark-1.5.0/src/sysinfo.cc rename to thirdparty_builtin/benchmark-1.8.0/src/sysinfo.cc index 28126470b..4578cb0fa 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/sysinfo.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/sysinfo.cc @@ -19,27 +19,36 @@ #undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA #include #include + #include #else #include -#ifndef BENCHMARK_OS_FUCHSIA +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) #include #endif #include #include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD #include #if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX || \ - defined BENCHMARK_OS_NETBSD || defined BENCHMARK_OS_OPENBSD + defined BENCHMARK_OS_NETBSD || defined BENCHMARK_OS_OPENBSD || \ + defined BENCHMARK_OS_DRAGONFLY #define BENCHMARK_HAS_SYSCTL #include #endif #endif #if defined(BENCHMARK_OS_SOLARIS) #include +#include #endif #if defined(BENCHMARK_OS_QNX) #include #endif +#if defined(BENCHMARK_OS_QURT) +#include +#endif +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) +#include +#endif #include #include @@ -54,16 +63,19 @@ #include #include #include +#include #include +#include #include -#include +#include +#include "benchmark/benchmark.h" #include "check.h" #include "cycleclock.h" #include "internal_macros.h" #include "log.h" -#include "sleep.h" #include "string_util.h" +#include "timers.h" namespace benchmark { namespace { @@ -88,67 +100,59 @@ BENCHMARK_NORETURN void PrintErrorAndDie(Args&&... args) { /// `sysctl` with the result type it's to be interpreted as. struct ValueUnion { union DataT { - uint32_t uint32_value; - uint64_t uint64_value; + int32_t int32_value; + int64_t int64_value; // For correct aliasing of union members from bytes. char bytes[8]; }; using DataPtr = std::unique_ptr; // The size of the data union member + its trailing array size. - size_t Size; - DataPtr Buff; + std::size_t size; + DataPtr buff; public: - ValueUnion() : Size(0), Buff(nullptr, &std::free) {} + ValueUnion() : size(0), buff(nullptr, &std::free) {} - explicit ValueUnion(size_t BuffSize) - : Size(sizeof(DataT) + BuffSize), - Buff(::new (std::malloc(Size)) DataT(), &std::free) {} + explicit ValueUnion(std::size_t buff_size) + : size(sizeof(DataT) + buff_size), + buff(::new (std::malloc(size)) DataT(), &std::free) {} ValueUnion(ValueUnion&& other) = default; - explicit operator bool() const { return bool(Buff); } + explicit operator bool() const { return bool(buff); } - char* data() const { return Buff->bytes; } + char* data() const { return buff->bytes; } std::string GetAsString() const { return std::string(data()); } int64_t GetAsInteger() const { - if (Size == sizeof(Buff->uint32_value)) - return static_cast(Buff->uint32_value); - else if (Size == sizeof(Buff->uint64_value)) - return static_cast(Buff->uint64_value); - BENCHMARK_UNREACHABLE(); - } - - uint64_t GetAsUnsigned() const { - if (Size == sizeof(Buff->uint32_value)) - return Buff->uint32_value; - else if (Size == sizeof(Buff->uint64_value)) - return Buff->uint64_value; + if (size == sizeof(buff->int32_value)) + return buff->int32_value; + else if (size == sizeof(buff->int64_value)) + return buff->int64_value; BENCHMARK_UNREACHABLE(); } template std::array GetAsArray() { - const int ArrSize = sizeof(T) * N; - CHECK_LE(ArrSize, Size); - std::array Arr; - std::memcpy(Arr.data(), data(), ArrSize); - return Arr; + const int arr_size = sizeof(T) * N; + BM_CHECK_LE(arr_size, size); + std::array arr; + std::memcpy(arr.data(), data(), arr_size); + return arr; } }; -ValueUnion GetSysctlImp(std::string const& Name) { +ValueUnion GetSysctlImp(std::string const& name) { #if defined BENCHMARK_OS_OPENBSD int mib[2]; mib[0] = CTL_HW; - if ((Name == "hw.ncpu") || (Name == "hw.cpuspeed")){ + if ((name == "hw.ncpu") || (name == "hw.cpuspeed")) { ValueUnion buff(sizeof(int)); - if (Name == "hw.ncpu") { + if (name == "hw.ncpu") { mib[1] = HW_NCPU; } else { mib[1] = HW_CPUSPEED; @@ -161,41 +165,41 @@ ValueUnion GetSysctlImp(std::string const& Name) { } return ValueUnion(); #else - size_t CurBuffSize = 0; - if (sysctlbyname(Name.c_str(), nullptr, &CurBuffSize, nullptr, 0) == -1) + std::size_t cur_buff_size = 0; + if (sysctlbyname(name.c_str(), nullptr, &cur_buff_size, nullptr, 0) == -1) return ValueUnion(); - ValueUnion buff(CurBuffSize); - if (sysctlbyname(Name.c_str(), buff.data(), &buff.Size, nullptr, 0) == 0) + ValueUnion buff(cur_buff_size); + if (sysctlbyname(name.c_str(), buff.data(), &buff.size, nullptr, 0) == 0) return buff; return ValueUnion(); #endif } BENCHMARK_MAYBE_UNUSED -bool GetSysctl(std::string const& Name, std::string* Out) { - Out->clear(); - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - Out->assign(Buff.data()); +bool GetSysctl(std::string const& name, std::string* out) { + out->clear(); + auto buff = GetSysctlImp(name); + if (!buff) return false; + out->assign(buff.data()); return true; } template ::value>::type> -bool GetSysctl(std::string const& Name, Tp* Out) { - *Out = 0; - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - *Out = static_cast(Buff.GetAsUnsigned()); +bool GetSysctl(std::string const& name, Tp* out) { + *out = 0; + auto buff = GetSysctlImp(name); + if (!buff) return false; + *out = static_cast(buff.GetAsInteger()); return true; } template -bool GetSysctl(std::string const& Name, std::array* Out) { - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - *Out = Buff.GetAsArray(); +bool GetSysctl(std::string const& name, std::array* out) { + auto buff = GetSysctlImp(name); + if (!buff) return false; + *out = buff.GetAsArray(); return true; } #endif @@ -209,13 +213,12 @@ bool ReadFromFile(std::string const& fname, ArgT* arg) { return f.good(); } -bool CpuScalingEnabled(int num_cpus) { +CPUInfo::Scaling CpuScaling(int num_cpus) { // We don't have a valid CPU count, so don't even bother. - if (num_cpus <= 0) return false; -#ifdef BENCHMARK_OS_QNX - return false; -#endif -#ifndef BENCHMARK_OS_WINDOWS + if (num_cpus <= 0) return CPUInfo::Scaling::UNKNOWN; +#if defined(BENCHMARK_OS_QNX) + return CPUInfo::Scaling::UNKNOWN; +#elif !defined(BENCHMARK_OS_WINDOWS) // On Linux, the CPUfreq subsystem exposes CPU information as files on the // local file system. If reading the exported files fails, then we may not be // running on Linux, so we silently ignore all the read errors. @@ -223,27 +226,30 @@ bool CpuScalingEnabled(int num_cpus) { for (int cpu = 0; cpu < num_cpus; ++cpu) { std::string governor_file = StrCat("/sys/devices/system/cpu/cpu", cpu, "/cpufreq/scaling_governor"); - if (ReadFromFile(governor_file, &res) && res != "performance") return true; + if (ReadFromFile(governor_file, &res) && res != "performance") + return CPUInfo::Scaling::ENABLED; } + return CPUInfo::Scaling::DISABLED; +#else + return CPUInfo::Scaling::UNKNOWN; #endif - return false; } -int CountSetBitsInCPUMap(std::string Val) { - auto CountBits = [](std::string Part) { +int CountSetBitsInCPUMap(std::string val) { + auto CountBits = [](std::string part) { using CPUMask = std::bitset; - Part = "0x" + Part; - CPUMask Mask(benchmark::stoul(Part, nullptr, 16)); - return static_cast(Mask.count()); + part = "0x" + part; + CPUMask mask(benchmark::stoul(part, nullptr, 16)); + return static_cast(mask.count()); }; - size_t Pos; + std::size_t pos; int total = 0; - while ((Pos = Val.find(',')) != std::string::npos) { - total += CountBits(Val.substr(0, Pos)); - Val = Val.substr(Pos + 1); + while ((pos = val.find(',')) != std::string::npos) { + total += CountBits(val.substr(0, pos)); + val = val.substr(pos + 1); } - if (!Val.empty()) { - total += CountBits(Val); + if (!val.empty()) { + total += CountBits(val); } return total; } @@ -252,16 +258,16 @@ BENCHMARK_MAYBE_UNUSED std::vector GetCacheSizesFromKVFS() { std::vector res; std::string dir = "/sys/devices/system/cpu/cpu0/cache/"; - int Idx = 0; + int idx = 0; while (true) { CPUInfo::CacheInfo info; - std::string FPath = StrCat(dir, "index", Idx++, "/"); - std::ifstream f(StrCat(FPath, "size").c_str()); + std::string fpath = StrCat(dir, "index", idx++, "/"); + std::ifstream f(StrCat(fpath, "size").c_str()); if (!f.is_open()) break; std::string suffix; f >> info.size; if (f.fail()) - PrintErrorAndDie("Failed while reading file '", FPath, "size'"); + PrintErrorAndDie("Failed while reading file '", fpath, "size'"); if (f.good()) { f >> suffix; if (f.bad()) @@ -270,15 +276,15 @@ std::vector GetCacheSizesFromKVFS() { else if (f && suffix != "K") PrintErrorAndDie("Invalid cache size format: Expected bytes ", suffix); else if (suffix == "K") - info.size *= 1000; + info.size *= 1024; } - if (!ReadFromFile(StrCat(FPath, "type"), &info.type)) - PrintErrorAndDie("Failed to read from file ", FPath, "type"); - if (!ReadFromFile(StrCat(FPath, "level"), &info.level)) - PrintErrorAndDie("Failed to read from file ", FPath, "level"); + if (!ReadFromFile(StrCat(fpath, "type"), &info.type)) + PrintErrorAndDie("Failed to read from file ", fpath, "type"); + if (!ReadFromFile(StrCat(fpath, "level"), &info.level)) + PrintErrorAndDie("Failed to read from file ", fpath, "level"); std::string map_str; - if (!ReadFromFile(StrCat(FPath, "shared_cpu_map"), &map_str)) - PrintErrorAndDie("Failed to read from file ", FPath, "shared_cpu_map"); + if (!ReadFromFile(StrCat(fpath, "shared_cpu_map"), &map_str)) + PrintErrorAndDie("Failed to read from file ", fpath, "shared_cpu_map"); info.num_sharing = CountSetBitsInCPUMap(map_str); res.push_back(info); } @@ -289,26 +295,26 @@ std::vector GetCacheSizesFromKVFS() { #ifdef BENCHMARK_OS_MACOSX std::vector GetCacheSizesMacOSX() { std::vector res; - std::array CacheCounts{{0, 0, 0, 0}}; - GetSysctl("hw.cacheconfig", &CacheCounts); + std::array cache_counts{{0, 0, 0, 0}}; + GetSysctl("hw.cacheconfig", &cache_counts); struct { std::string name; std::string type; int level; - uint64_t num_sharing; - } Cases[] = {{"hw.l1dcachesize", "Data", 1, CacheCounts[1]}, - {"hw.l1icachesize", "Instruction", 1, CacheCounts[1]}, - {"hw.l2cachesize", "Unified", 2, CacheCounts[2]}, - {"hw.l3cachesize", "Unified", 3, CacheCounts[3]}}; - for (auto& C : Cases) { + int num_sharing; + } cases[] = {{"hw.l1dcachesize", "Data", 1, cache_counts[1]}, + {"hw.l1icachesize", "Instruction", 1, cache_counts[1]}, + {"hw.l2cachesize", "Unified", 2, cache_counts[2]}, + {"hw.l3cachesize", "Unified", 3, cache_counts[3]}}; + for (auto& c : cases) { int val; - if (!GetSysctl(C.name, &val)) continue; + if (!GetSysctl(c.name, &val)) continue; CPUInfo::CacheInfo info; - info.type = C.type; - info.level = C.level; + info.type = c.type; + info.level = c.level; info.size = val; - info.num_sharing = static_cast(C.num_sharing); + info.num_sharing = c.num_sharing; res.push_back(std::move(info)); } return res; @@ -333,15 +339,16 @@ std::vector GetCacheSizesWindows() { for (; it != end; ++it) { if (it->Relationship != RelationCache) continue; using BitSet = std::bitset; - BitSet B(it->ProcessorMask); + BitSet b(it->ProcessorMask); // To prevent duplicates, only consider caches where CPU 0 is specified - if (!B.test(0)) continue; - CInfo* Cache = &it->Cache; + if (!b.test(0)) continue; + const CInfo& cache = it->Cache; CPUInfo::CacheInfo C; - C.num_sharing = static_cast(B.count()); - C.level = Cache->Level; - C.size = Cache->Size; - switch (Cache->Type) { + C.num_sharing = static_cast(b.count()); + C.level = cache.Level; + C.size = cache.Size; + C.type = "Unknown"; + switch (cache.Type) { case CacheUnified: C.type = "Unified"; break; @@ -354,9 +361,6 @@ std::vector GetCacheSizesWindows() { case CacheTrace: C.type = "Trace"; break; - default: - C.type = "Unknown"; - break; } res.push_back(C); } @@ -365,27 +369,29 @@ std::vector GetCacheSizesWindows() { #elif BENCHMARK_OS_QNX std::vector GetCacheSizesQNX() { std::vector res; - struct cacheattr_entry *cache = SYSPAGE_ENTRY(cacheattr); + struct cacheattr_entry* cache = SYSPAGE_ENTRY(cacheattr); uint32_t const elsize = SYSPAGE_ELEMENT_SIZE(cacheattr); - int num = SYSPAGE_ENTRY_SIZE(cacheattr) / elsize ; - for(int i = 0; i < num; ++i ) { + int num = SYSPAGE_ENTRY_SIZE(cacheattr) / elsize; + for (int i = 0; i < num; ++i) { CPUInfo::CacheInfo info; - switch (cache->flags){ - case CACHE_FLAG_INSTR : + switch (cache->flags) { + case CACHE_FLAG_INSTR: info.type = "Instruction"; info.level = 1; break; - case CACHE_FLAG_DATA : + case CACHE_FLAG_DATA: info.type = "Data"; info.level = 1; break; - case CACHE_FLAG_UNIFIED : + case CACHE_FLAG_UNIFIED: info.type = "Unified"; info.level = 2; - case CACHE_FLAG_SHARED : + break; + case CACHE_FLAG_SHARED: info.type = "Shared"; info.level = 3; - default : + break; + default: continue; break; } @@ -405,6 +411,8 @@ std::vector GetCacheSizes() { return GetCacheSizesWindows(); #elif defined(BENCHMARK_OS_QNX) return GetCacheSizesQNX(); +#elif defined(BENCHMARK_OS_QURT) + return std::vector(); #else return GetCacheSizesFromKVFS(); #endif @@ -413,38 +421,57 @@ std::vector GetCacheSizes() { std::string GetSystemName() { #if defined(BENCHMARK_OS_WINDOWS) std::string str; - const unsigned COUNT = MAX_COMPUTERNAME_LENGTH+1; - TCHAR hostname[COUNT] = {'\0'}; + static constexpr int COUNT = MAX_COMPUTERNAME_LENGTH + 1; + TCHAR hostname[COUNT] = {'\0'}; DWORD DWCOUNT = COUNT; - if (!GetComputerName(hostname, &DWCOUNT)) - return std::string(""); + if (!GetComputerName(hostname, &DWCOUNT)) return std::string(""); #ifndef UNICODE str = std::string(hostname, DWCOUNT); #else - //Using wstring_convert, Is deprecated in C++17 - using convert_type = std::codecvt_utf8; - std::wstring_convert converter; - std::wstring wStr(hostname, DWCOUNT); - str = converter.to_bytes(wStr); + // `WideCharToMultiByte` returns `0` when conversion fails. + int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname, + DWCOUNT, NULL, 0, NULL, NULL); + str.resize(len); + WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname, DWCOUNT, &str[0], + str.size(), NULL, NULL); #endif return str; -#else // defined(BENCHMARK_OS_WINDOWS) -#ifdef BENCHMARK_HAS_SYSCTL // BSD/Mac Doesnt have HOST_NAME_MAX defined +#elif defined(BENCHMARK_OS_QURT) + std::string str = "Hexagon DSP"; + qurt_arch_version_t arch_version_struct; + if (qurt_sysenv_get_arch_version(&arch_version_struct) == QURT_EOK) { + str += " v"; + str += std::to_string(arch_version_struct.arch_version); + } + return str; +#else +#ifndef HOST_NAME_MAX +#ifdef BENCHMARK_HAS_SYSCTL // BSD/Mac doesn't have HOST_NAME_MAX defined +#define HOST_NAME_MAX 64 +#elif defined(BENCHMARK_OS_NACL) #define HOST_NAME_MAX 64 #elif defined(BENCHMARK_OS_QNX) #define HOST_NAME_MAX 154 +#elif defined(BENCHMARK_OS_RTEMS) +#define HOST_NAME_MAX 256 +#elif defined(BENCHMARK_OS_SOLARIS) +#define HOST_NAME_MAX MAXHOSTNAMELEN +#else +#pragma message("HOST_NAME_MAX not defined. using 64") +#define HOST_NAME_MAX 64 #endif +#endif // def HOST_NAME_MAX char hostname[HOST_NAME_MAX]; int retVal = gethostname(hostname, HOST_NAME_MAX); if (retVal != 0) return std::string(""); return std::string(hostname); -#endif // Catch-all POSIX block. +#endif // Catch-all POSIX block. } int GetNumCPUs() { #ifdef BENCHMARK_HAS_SYSCTL - int NumCPU = -1; - if (GetSysctl("hw.ncpu", &NumCPU)) return NumCPU; + int num_cpu = -1; + if (GetSysctl("hw.ncpu", &num_cpu)) return num_cpu; fprintf(stderr, "Err: %s\n", strerror(errno)); std::exit(EXIT_FAILURE); #elif defined(BENCHMARK_OS_WINDOWS) @@ -458,18 +485,23 @@ int GetNumCPUs() { // group #elif defined(BENCHMARK_OS_SOLARIS) // Returns -1 in case of a failure. - int NumCPU = sysconf(_SC_NPROCESSORS_ONLN); - if (NumCPU < 0) { - fprintf(stderr, - "sysconf(_SC_NPROCESSORS_ONLN) failed with error: %s\n", + long num_cpu = sysconf(_SC_NPROCESSORS_ONLN); + if (num_cpu < 0) { + fprintf(stderr, "sysconf(_SC_NPROCESSORS_ONLN) failed with error: %s\n", strerror(errno)); } - return NumCPU; + return (int)num_cpu; #elif defined(BENCHMARK_OS_QNX) return static_cast(_syspage_ptr->num_cpu); +#elif defined(BENCHMARK_OS_QURT) + qurt_sysenv_max_hthreads_t hardware_threads; + if (qurt_sysenv_get_max_hw_threads(&hardware_threads) != QURT_EOK) { + hardware_threads.max_hthreads = 1; + } + return hardware_threads.max_hthreads; #else - int NumCPUs = 0; - int MaxID = -1; + int num_cpus = 0; + int max_id = -1; std::ifstream f("/proc/cpuinfo"); if (!f.is_open()) { std::cerr << "failed to open /proc/cpuinfo\n"; @@ -479,20 +511,21 @@ int GetNumCPUs() { std::string ln; while (std::getline(f, ln)) { if (ln.empty()) continue; - size_t SplitIdx = ln.find(':'); + std::size_t split_idx = ln.find(':'); std::string value; #if defined(__s390__) // s390 has another format in /proc/cpuinfo // it needs to be parsed differently - if (SplitIdx != std::string::npos) value = ln.substr(Key.size()+1,SplitIdx-Key.size()-1); + if (split_idx != std::string::npos) + value = ln.substr(Key.size() + 1, split_idx - Key.size() - 1); #else - if (SplitIdx != std::string::npos) value = ln.substr(SplitIdx + 1); + if (split_idx != std::string::npos) value = ln.substr(split_idx + 1); #endif if (ln.size() >= Key.size() && ln.compare(0, Key.size(), Key) == 0) { - NumCPUs++; + num_cpus++; if (!value.empty()) { - int CurID = benchmark::stoi(value); - MaxID = std::max(CurID, MaxID); + const int cur_id = benchmark::stoi(value); + max_id = std::max(cur_id, max_id); } } } @@ -506,17 +539,95 @@ int GetNumCPUs() { } f.close(); - if ((MaxID + 1) != NumCPUs) { + if ((max_id + 1) != num_cpus) { fprintf(stderr, "CPU ID assignments in /proc/cpuinfo seem messed up." " This is usually caused by a bad BIOS.\n"); } - return NumCPUs; + return num_cpus; #endif BENCHMARK_UNREACHABLE(); } -double GetCPUCyclesPerSecond() { +class ThreadAffinityGuard final { + public: + ThreadAffinityGuard() : reset_affinity(SetAffinity()) { + if (!reset_affinity) + std::cerr << "***WARNING*** Failed to set thread affinity. Estimated CPU " + "frequency may be incorrect." + << std::endl; + } + + ~ThreadAffinityGuard() { + if (!reset_affinity) return; + +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) + int ret = pthread_setaffinity_np(self, sizeof(previous_affinity), + &previous_affinity); + if (ret == 0) return; +#elif defined(BENCHMARK_OS_WINDOWS_WIN32) + DWORD_PTR ret = SetThreadAffinityMask(self, previous_affinity); + if (ret != 0) return; +#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY + PrintErrorAndDie("Failed to reset thread affinity"); + } + + ThreadAffinityGuard(ThreadAffinityGuard&&) = delete; + ThreadAffinityGuard(const ThreadAffinityGuard&) = delete; + ThreadAffinityGuard& operator=(ThreadAffinityGuard&&) = delete; + ThreadAffinityGuard& operator=(const ThreadAffinityGuard&) = delete; + + private: + bool SetAffinity() { +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) + int ret; + self = pthread_self(); + ret = pthread_getaffinity_np(self, sizeof(previous_affinity), + &previous_affinity); + if (ret != 0) return false; + + cpu_set_t affinity; + memcpy(&affinity, &previous_affinity, sizeof(affinity)); + + bool is_first_cpu = true; + + for (int i = 0; i < CPU_SETSIZE; ++i) + if (CPU_ISSET(i, &affinity)) { + if (is_first_cpu) + is_first_cpu = false; + else + CPU_CLR(i, &affinity); + } + + if (is_first_cpu) return false; + + ret = pthread_setaffinity_np(self, sizeof(affinity), &affinity); + return ret == 0; +#elif defined(BENCHMARK_OS_WINDOWS_WIN32) + self = GetCurrentThread(); + DWORD_PTR mask = static_cast(1) << GetCurrentProcessorNumber(); + previous_affinity = SetThreadAffinityMask(self, mask); + return previous_affinity != 0; +#else + return false; +#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY + } + +#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY) + pthread_t self; + cpu_set_t previous_affinity; +#elif defined(BENCHMARK_OS_WINDOWS_WIN32) + HANDLE self; + DWORD_PTR previous_affinity; +#endif // def BENCHMARK_HAS_PTHREAD_AFFINITY + bool reset_affinity; +}; + +double GetCPUCyclesPerSecond(CPUInfo::Scaling scaling) { + // Currently, scaling is only used on linux path here, + // suppress diagnostics about it being unused on other paths. + (void)scaling; + #if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN long freq; @@ -527,8 +638,15 @@ double GetCPUCyclesPerSecond() { // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as // well. if (ReadFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq) - // If CPU scaling is in effect, we want to use the *maximum* frequency, - // not whatever CPU speed some random processor happens to be using now. + // If CPU scaling is disabled, use the *current* frequency. + // Note that we specifically don't want to read cpuinfo_cur_freq, + // because it is only readable by root. + || (scaling == CPUInfo::Scaling::DISABLED && + ReadFromFile("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", + &freq)) + // Otherwise, if CPU scaling may be in effect, we want to use + // the *maximum* frequency, not whatever CPU speed some random processor + // happens to be using now. || ReadFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", &freq)) { // The value is in kHz (as the file name suggests). For example, on a @@ -545,7 +663,7 @@ double GetCPUCyclesPerSecond() { return error_value; } - auto startsWithKey = [](std::string const& Value, std::string const& Key) { + auto StartsWithKey = [](std::string const& Value, std::string const& Key) { if (Key.size() > Value.size()) return false; auto Cmp = [&](char X, char Y) { return std::tolower(X) == std::tolower(Y); @@ -556,18 +674,18 @@ double GetCPUCyclesPerSecond() { std::string ln; while (std::getline(f, ln)) { if (ln.empty()) continue; - size_t SplitIdx = ln.find(':'); + std::size_t split_idx = ln.find(':'); std::string value; - if (SplitIdx != std::string::npos) value = ln.substr(SplitIdx + 1); + if (split_idx != std::string::npos) value = ln.substr(split_idx + 1); // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only // accept positive values. Some environments (virtual machines) report zero, // which would cause infinite looping in WallTime_Init. - if (startsWithKey(ln, "cpu MHz")) { + if (StartsWithKey(ln, "cpu MHz")) { if (!value.empty()) { double cycles_per_second = benchmark::stod(value) * 1000000.0; if (cycles_per_second > 0) return cycles_per_second; } - } else if (startsWithKey(ln, "bogomips")) { + } else if (StartsWithKey(ln, "bogomips")) { if (!value.empty()) { bogo_clock = benchmark::stod(value) * 1000000.0; if (bogo_clock < 0.0) bogo_clock = error_value; @@ -589,24 +707,29 @@ double GetCPUCyclesPerSecond() { if (bogo_clock >= 0.0) return bogo_clock; #elif defined BENCHMARK_HAS_SYSCTL - constexpr auto* FreqStr = + constexpr auto* freqStr = #if defined(BENCHMARK_OS_FREEBSD) || defined(BENCHMARK_OS_NETBSD) "machdep.tsc_freq"; #elif defined BENCHMARK_OS_OPENBSD "hw.cpuspeed"; +#elif defined BENCHMARK_OS_DRAGONFLY + "hw.tsc_frequency"; #else "hw.cpufrequency"; #endif unsigned long long hz = 0; #if defined BENCHMARK_OS_OPENBSD - if (GetSysctl(FreqStr, &hz)) return hz * 1000000; + if (GetSysctl(freqStr, &hz)) return hz * 1000000; #else - if (GetSysctl(FreqStr, &hz)) return hz; + if (GetSysctl(freqStr, &hz)) return hz; #endif fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n", - FreqStr, strerror(errno)); + freqStr, strerror(errno)); + fprintf(stderr, + "This does not affect benchmark measurements, only the " + "metadata output.\n"); -#elif defined BENCHMARK_OS_WINDOWS +#elif defined BENCHMARK_OS_WINDOWS_WIN32 // In NT, read MHz from the registry. If we fail to do so or we're in win9x // then make a crude estimate. DWORD data, data_size = sizeof(data); @@ -617,13 +740,14 @@ double GetCPUCyclesPerSecond() { "~MHz", nullptr, &data, &data_size))) return static_cast((int64_t)data * (int64_t)(1000 * 1000)); // was mhz -#elif defined (BENCHMARK_OS_SOLARIS) - kstat_ctl_t *kc = kstat_open(); +#elif defined(BENCHMARK_OS_SOLARIS) + kstat_ctl_t* kc = kstat_open(); if (!kc) { std::cerr << "failed to open /dev/kstat\n"; return -1; } - kstat_t *ksp = kstat_lookup(kc, (char*)"cpu_info", -1, (char*)"cpu_info0"); + kstat_t* ksp = kstat_lookup(kc, const_cast("cpu_info"), -1, + const_cast("cpu_info0")); if (!ksp) { std::cerr << "failed to lookup in /dev/kstat\n"; return -1; @@ -632,8 +756,8 @@ double GetCPUCyclesPerSecond() { std::cerr << "failed to read from /dev/kstat\n"; return -1; } - kstat_named_t *knp = - (kstat_named_t*)kstat_data_lookup(ksp, (char*)"current_clock_Hz"); + kstat_named_t* knp = (kstat_named_t*)kstat_data_lookup( + ksp, const_cast("current_clock_Hz")); if (!knp) { std::cerr << "failed to lookup data in /dev/kstat\n"; return -1; @@ -646,22 +770,55 @@ double GetCPUCyclesPerSecond() { double clock_hz = knp->value.ui64; kstat_close(kc); return clock_hz; -#elif defined (BENCHMARK_OS_QNX) +#elif defined(BENCHMARK_OS_QNX) return static_cast((int64_t)(SYSPAGE_ENTRY(cpuinfo)->speed) * (int64_t)(1000 * 1000)); +#elif defined(BENCHMARK_OS_QURT) + // QuRT doesn't provide any API to query Hexagon frequency. + return 1000000000; #endif // If we've fallen through, attempt to roughly estimate the CPU clock rate. - const int estimate_time_ms = 1000; + + // Make sure to use the same cycle counter when starting and stopping the + // cycle timer. We just pin the current thread to a cpu in the previous + // affinity set. + ThreadAffinityGuard affinity_guard; + + static constexpr double estimate_time_s = 1.0; + const double start_time = ChronoClockNow(); const auto start_ticks = cycleclock::Now(); - SleepForMilliseconds(estimate_time_ms); - return static_cast(cycleclock::Now() - start_ticks); + + // Impose load instead of calling sleep() to make sure the cycle counter + // works. + using PRNG = std::minstd_rand; + using Result = PRNG::result_type; + PRNG rng(static_cast(start_ticks)); + + Result state = 0; + + do { + static constexpr size_t batch_size = 10000; + rng.discard(batch_size); + state += rng(); + + } while (ChronoClockNow() - start_time < estimate_time_s); + + DoNotOptimize(state); + + const auto end_ticks = cycleclock::Now(); + const double end_time = ChronoClockNow(); + + return static_cast(end_ticks - start_ticks) / (end_time - start_time); + // Reset the affinity of current thread when the lifetime of affinity_guard + // ends. } std::vector GetLoadAvg() { -#if (defined BENCHMARK_OS_FREEBSD || defined(BENCHMARK_OS_LINUX) || \ - defined BENCHMARK_OS_MACOSX || defined BENCHMARK_OS_NETBSD || \ - defined BENCHMARK_OS_OPENBSD) && !defined(__ANDROID__) - constexpr int kMaxSamples = 3; +#if (defined BENCHMARK_OS_FREEBSD || defined(BENCHMARK_OS_LINUX) || \ + defined BENCHMARK_OS_MACOSX || defined BENCHMARK_OS_NETBSD || \ + defined BENCHMARK_OS_OPENBSD || defined BENCHMARK_OS_DRAGONFLY) && \ + !defined(__ANDROID__) + static constexpr int kMaxSamples = 3; std::vector res(kMaxSamples, 0.0); const int nelem = getloadavg(res.data(), kMaxSamples); if (nelem < 1) { @@ -684,12 +841,11 @@ const CPUInfo& CPUInfo::Get() { CPUInfo::CPUInfo() : num_cpus(GetNumCPUs()), - cycles_per_second(GetCPUCyclesPerSecond()), + scaling(CpuScaling(num_cpus)), + cycles_per_second(GetCPUCyclesPerSecond(scaling)), caches(GetCacheSizes()), - scaling_enabled(CpuScalingEnabled(num_cpus)), load_avg(GetLoadAvg()) {} - const SystemInfo& SystemInfo::Get() { static const SystemInfo* info = new SystemInfo(); return *info; diff --git a/thirdparty_builtin/benchmark-1.5.0/src/thread_manager.h b/thirdparty_builtin/benchmark-1.8.0/src/thread_manager.h similarity index 91% rename from thirdparty_builtin/benchmark-1.5.0/src/thread_manager.h rename to thirdparty_builtin/benchmark-1.8.0/src/thread_manager.h index 1720281f0..819b3c44d 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/thread_manager.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/thread_manager.h @@ -11,7 +11,7 @@ namespace internal { class ThreadManager { public: - ThreadManager(int num_threads) + explicit ThreadManager(int num_threads) : alive_threads_(num_threads), start_stop_barrier_(num_threads) {} Mutex& GetBenchmarkMutex() const RETURN_CAPABILITY(benchmark_mutex_) { @@ -36,7 +36,6 @@ class ThreadManager { [this]() { return alive_threads_ == 0; }); } - public: struct Result { IterationCount iterations = 0; double real_time_used = 0; @@ -44,8 +43,8 @@ class ThreadManager { double manual_time_used = 0; int64_t complexity_n = 0; std::string report_label_; - std::string error_message_; - bool has_error_ = false; + std::string skip_message_; + internal::Skipped skipped_ = internal::NotSkipped; UserCounters counters; }; GUARDED_BY(GetBenchmarkMutex()) Result results; diff --git a/thirdparty_builtin/benchmark-1.5.0/src/thread_timer.h b/thirdparty_builtin/benchmark-1.8.0/src/thread_timer.h similarity index 91% rename from thirdparty_builtin/benchmark-1.5.0/src/thread_timer.h rename to thirdparty_builtin/benchmark-1.8.0/src/thread_timer.h index fbd298d3b..eb23f5956 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/thread_timer.h +++ b/thirdparty_builtin/benchmark-1.8.0/src/thread_timer.h @@ -28,7 +28,7 @@ class ThreadTimer { // Called by each thread void StopTimer() { - CHECK(running_); + BM_CHECK(running_); running_ = false; real_time_used_ += ChronoClockNow() - start_real_time_; // Floating point error can result in the subtraction producing a negative @@ -43,20 +43,20 @@ class ThreadTimer { bool running() const { return running_; } // REQUIRES: timer is not running - double real_time_used() { - CHECK(!running_); + double real_time_used() const { + BM_CHECK(!running_); return real_time_used_; } // REQUIRES: timer is not running - double cpu_time_used() { - CHECK(!running_); + double cpu_time_used() const { + BM_CHECK(!running_); return cpu_time_used_; } // REQUIRES: timer is not running - double manual_time_used() { - CHECK(!running_); + double manual_time_used() const { + BM_CHECK(!running_); return manual_time_used_; } diff --git a/thirdparty_builtin/benchmark-1.5.0/src/timers.cc b/thirdparty_builtin/benchmark-1.8.0/src/timers.cc similarity index 64% rename from thirdparty_builtin/benchmark-1.5.0/src/timers.cc rename to thirdparty_builtin/benchmark-1.8.0/src/timers.cc index 7613ff92c..b23feea8b 100644 --- a/thirdparty_builtin/benchmark-1.5.0/src/timers.cc +++ b/thirdparty_builtin/benchmark-1.8.0/src/timers.cc @@ -13,6 +13,7 @@ // limitations under the License. #include "timers.h" + #include "internal_macros.h" #ifdef BENCHMARK_OS_WINDOWS @@ -22,13 +23,14 @@ #include #else #include -#ifndef BENCHMARK_OS_FUCHSIA +#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) #include #endif #include #include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD #include -#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX +#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_DRAGONFLY || \ + defined BENCHMARK_OS_MACOSX #include #endif #if defined(BENCHMARK_OS_MACOSX) @@ -36,6 +38,9 @@ #include #include #endif +#if defined(BENCHMARK_OS_QURT) +#include +#endif #endif #ifdef BENCHMARK_OS_EMSCRIPTEN @@ -54,7 +59,6 @@ #include "check.h" #include "log.h" -#include "sleep.h" #include "string_util.h" namespace benchmark { @@ -63,6 +67,9 @@ namespace benchmark { #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" #endif +#if defined(__NVCOMPILER) +#pragma diag_suppress declared_but_not_referenced +#endif namespace { #if defined(BENCHMARK_OS_WINDOWS) @@ -77,7 +84,7 @@ double MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) { static_cast(user.QuadPart)) * 1e-7; } -#elif !defined(BENCHMARK_OS_FUCHSIA) +#elif !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT) double MakeTime(struct rusage const& ru) { return (static_cast(ru.ru_utime.tv_sec) + static_cast(ru.ru_utime.tv_usec) * 1e-6 + @@ -117,15 +124,19 @@ double ProcessCPUUsage() { &user_time)) return MakeTime(kernel_time, user_time); DiagnoseAndExit("GetProccessTimes() failed"); +#elif defined(BENCHMARK_OS_QURT) + return static_cast( + qurt_timer_timetick_to_us(qurt_timer_get_ticks())) * + 1.0e-6; #elif defined(BENCHMARK_OS_EMSCRIPTEN) // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten. // Use Emscripten-specific API. Reported CPU time would be exactly the // same as total time, but this is ok because there aren't long-latency - // syncronous system calls in Emscripten. + // synchronous system calls in Emscripten. return emscripten_get_now() * 1e-3; #elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX) - // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See - // https://github.com/google/benchmark/pull/292 + // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. + // See https://github.com/google/benchmark/pull/292 struct timespec spec; if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0) return MakeTime(spec); @@ -147,14 +158,19 @@ double ThreadCPUUsage() { GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time, &user_time); return MakeTime(kernel_time, user_time); +#elif defined(BENCHMARK_OS_QURT) + return static_cast( + qurt_timer_timetick_to_us(qurt_timer_get_ticks())) * + 1.0e-6; #elif defined(BENCHMARK_OS_MACOSX) - // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See - // https://github.com/google/benchmark/pull/292 + // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. + // See https://github.com/google/benchmark/pull/292 mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; thread_basic_info_data_t info; mach_port_t thread = pthread_mach_thread_np(pthread_self()); - if (thread_info(thread, THREAD_BASIC_INFO, (thread_info_t)&info, &count) == - KERN_SUCCESS) { + if (thread_info(thread, THREAD_BASIC_INFO, + reinterpret_cast(&info), + &count) == KERN_SUCCESS) { return MakeTime(info); } DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info"); @@ -178,40 +194,79 @@ double ThreadCPUUsage() { #endif } -namespace { - -std::string DateTimeString(bool local) { +std::string LocalDateTimeString() { + // Write the local time in RFC3339 format yyyy-mm-ddTHH:MM:SS+/-HH:MM. typedef std::chrono::system_clock Clock; std::time_t now = Clock::to_time_t(Clock::now()); - const std::size_t kStorageSize = 128; - char storage[kStorageSize]; - std::size_t written; + const std::size_t kTzOffsetLen = 6; + const std::size_t kTimestampLen = 19; + + std::size_t tz_len; + std::size_t timestamp_len; + long int offset_minutes; + char tz_offset_sign = '+'; + // tz_offset is set in one of three ways: + // * strftime with %z - This either returns empty or the ISO 8601 time. The + // maximum length an + // ISO 8601 string can be is 7 (e.g. -03:30, plus trailing zero). + // * snprintf with %c%02li:%02li - The maximum length is 41 (one for %c, up to + // 19 for %02li, + // one for :, up to 19 %02li, plus trailing zero). + // * A fixed string of "-00:00". The maximum length is 7 (-00:00, plus + // trailing zero). + // + // Thus, the maximum size this needs to be is 41. + char tz_offset[41]; + // Long enough buffer to avoid format-overflow warnings + char storage[128]; - if (local) { #if defined(BENCHMARK_OS_WINDOWS) - written = - std::strftime(storage, sizeof(storage), "%x %X", ::localtime(&now)); + std::tm* timeinfo_p = ::localtime(&now); #else - std::tm timeinfo; - ::localtime_r(&now, &timeinfo); - written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo); + std::tm timeinfo; + std::tm* timeinfo_p = &timeinfo; + ::localtime_r(&now, &timeinfo); #endif + + tz_len = std::strftime(tz_offset, sizeof(tz_offset), "%z", timeinfo_p); + + if (tz_len < kTzOffsetLen && tz_len > 1) { + // Timezone offset was written. strftime writes offset as +HHMM or -HHMM, + // RFC3339 specifies an offset as +HH:MM or -HH:MM. To convert, we parse + // the offset as an integer, then reprint it to a string. + + offset_minutes = ::strtol(tz_offset, NULL, 10); + if (offset_minutes < 0) { + offset_minutes *= -1; + tz_offset_sign = '-'; + } + + tz_len = + ::snprintf(tz_offset, sizeof(tz_offset), "%c%02li:%02li", + tz_offset_sign, offset_minutes / 100, offset_minutes % 100); + BM_CHECK(tz_len == kTzOffsetLen); + ((void)tz_len); // Prevent unused variable warning in optimized build. } else { + // Unknown offset. RFC3339 specifies that unknown local offsets should be + // written as UTC time with -00:00 timezone. #if defined(BENCHMARK_OS_WINDOWS) - written = std::strftime(storage, sizeof(storage), "%x %X", ::gmtime(&now)); + // Potential race condition if another thread calls localtime or gmtime. + timeinfo_p = ::gmtime(&now); #else - std::tm timeinfo; ::gmtime_r(&now, &timeinfo); - written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo); #endif + + strncpy(tz_offset, "-00:00", kTzOffsetLen + 1); } - CHECK(written < kStorageSize); - ((void)written); // prevent unused variable in optimized mode. - return std::string(storage); -} -} // end namespace + timestamp_len = + std::strftime(storage, sizeof(storage), "%Y-%m-%dT%H:%M:%S", timeinfo_p); + BM_CHECK(timestamp_len == kTimestampLen); + // Prevent unused variable warning in optimized build. + ((void)kTimestampLen); -std::string LocalDateTimeString() { return DateTimeString(true); } + std::strncat(storage, tz_offset, sizeof(storage) - timestamp_len - 1); + return std::string(storage); +} } // end namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/src/timers.h b/thirdparty_builtin/benchmark-1.8.0/src/timers.h similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/src/timers.h rename to thirdparty_builtin/benchmark-1.8.0/src/timers.h diff --git a/thirdparty_builtin/benchmark-1.5.0/test/AssemblyTests.cmake b/thirdparty_builtin/benchmark-1.8.0/test/AssemblyTests.cmake similarity index 63% rename from thirdparty_builtin/benchmark-1.5.0/test/AssemblyTests.cmake rename to thirdparty_builtin/benchmark-1.8.0/test/AssemblyTests.cmake index 3d078586f..c43c711fa 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/AssemblyTests.cmake +++ b/thirdparty_builtin/benchmark-1.8.0/test/AssemblyTests.cmake @@ -1,3 +1,23 @@ +set(CLANG_SUPPORTED_VERSION "5.0.0") +set(GCC_SUPPORTED_VERSION "5.5.0") + +if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_EQUAL ${CLANG_SUPPORTED_VERSION}) + message (WARNING + "Unsupported Clang version " ${CMAKE_CXX_COMPILER_VERSION} + ". Expected is " ${CLANG_SUPPORTED_VERSION} + ". Assembly tests may be broken.") + endif() +elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU") + if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_EQUAL ${GCC_SUPPORTED_VERSION}) + message (WARNING + "Unsupported GCC version " ${CMAKE_CXX_COMPILER_VERSION} + ". Expected is " ${GCC_SUPPORTED_VERSION} + ". Assembly tests may be broken.") + endif() +else() + message (WARNING "Unsupported compiler. Assembly tests may be broken.") +endif() include(split_list) @@ -23,6 +43,7 @@ string(TOUPPER "${CMAKE_CXX_COMPILER_ID}" ASM_TEST_COMPILER) macro(add_filecheck_test name) cmake_parse_arguments(ARG "" "" "CHECK_PREFIXES" ${ARGV}) add_library(${name} OBJECT ${name}.cc) + target_link_libraries(${name} PRIVATE benchmark::benchmark) set_target_properties(${name} PROPERTIES COMPILE_FLAGS "-S ${ASM_TEST_FLAGS}") set(ASM_OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/${name}.s") add_custom_target(copy_${name} ALL diff --git a/thirdparty_builtin/benchmark-1.8.0/test/BUILD b/thirdparty_builtin/benchmark-1.8.0/test/BUILD new file mode 100644 index 000000000..8262d080f --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/BUILD @@ -0,0 +1,110 @@ +load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") + +platform( + name = "windows", + constraint_values = [ + "@platforms//os:windows", + ], +) + +TEST_COPTS = [ + "-pedantic", + "-pedantic-errors", + "-std=c++11", + "-Wall", + "-Wconversion", + "-Wextra", + "-Wshadow", + # "-Wshorten-64-to-32", + "-Wfloat-equal", + "-fstrict-aliasing", +] + +# Some of the issues with DoNotOptimize only occur when optimization is enabled +PER_SRC_COPTS = { + "donotoptimize_test.cc": ["-O3"], +} + +TEST_ARGS = ["--benchmark_min_time=0.01s"] + +PER_SRC_TEST_ARGS = { + "user_counters_tabular_test.cc": ["--benchmark_counters_tabular=true"], + "repetitions_test.cc": [" --benchmark_repetitions=3"], + "spec_arg_test.cc": ["--benchmark_filter=BM_NotChosen"], + "spec_arg_verbosity_test.cc": ["--v=42"], +} + +cc_library( + name = "output_test_helper", + testonly = 1, + srcs = ["output_test_helper.cc"], + hdrs = ["output_test.h"], + copts = select({ + "//:windows": [], + "//conditions:default": TEST_COPTS, + }), + deps = [ + "//:benchmark", + "//:benchmark_internal_headers", + ], +) + +[ + cc_test( + name = test_src[:-len(".cc")], + size = "small", + srcs = [test_src], + args = TEST_ARGS + PER_SRC_TEST_ARGS.get(test_src, []), + copts = select({ + "//:windows": [], + "//conditions:default": TEST_COPTS, + }) + PER_SRC_COPTS.get(test_src, []), + deps = [ + ":output_test_helper", + "//:benchmark", + "//:benchmark_internal_headers", + "@com_google_googletest//:gtest", + "@com_google_googletest//:gtest_main", + ], + # FIXME: Add support for assembly tests to bazel. + # See Issue #556 + # https://github.com/google/benchmark/issues/556 + ) + for test_src in glob( + ["*test.cc"], + exclude = [ + "*_assembly_test.cc", + "cxx03_test.cc", + "link_main_test.cc", + ], + ) +] + +cc_test( + name = "cxx03_test", + size = "small", + srcs = ["cxx03_test.cc"], + copts = TEST_COPTS + ["-std=c++03"], + target_compatible_with = select({ + "//:windows": ["@platforms//:incompatible"], + "//conditions:default": [], + }), + deps = [ + ":output_test_helper", + "//:benchmark", + "//:benchmark_internal_headers", + "@com_google_googletest//:gtest", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( + name = "link_main_test", + size = "small", + srcs = ["link_main_test.cc"], + copts = select({ + "//:windows": [], + "//conditions:default": TEST_COPTS, + }), + deps = ["//:benchmark_main"], +) diff --git a/thirdparty_builtin/benchmark-1.5.0/test/CMakeLists.txt b/thirdparty_builtin/benchmark-1.8.0/test/CMakeLists.txt similarity index 60% rename from thirdparty_builtin/benchmark-1.5.0/test/CMakeLists.txt rename to thirdparty_builtin/benchmark-1.8.0/test/CMakeLists.txt index 030f35aae..78d6d5175 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/CMakeLists.txt +++ b/thirdparty_builtin/benchmark-1.8.0/test/CMakeLists.txt @@ -1,5 +1,7 @@ # Enable the tests +set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads REQUIRED) include(CheckCXXCompilerFlag) @@ -22,6 +24,10 @@ if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" ) endforeach() endif() +if (NOT BUILD_SHARED_LIBS) + add_definitions(-DBENCHMARK_STATIC_DEFINE) +endif() + check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) set(BENCHMARK_O3_FLAG "") if (BENCHMARK_HAS_O3_FLAG) @@ -35,33 +41,52 @@ if (DEFINED BENCHMARK_CXX_LINKER_FLAGS) endif() add_library(output_test_helper STATIC output_test_helper.cc output_test.h) +target_link_libraries(output_test_helper PRIVATE benchmark::benchmark) macro(compile_benchmark_test name) add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark ${CMAKE_THREAD_LIBS_INIT}) + target_link_libraries(${name} benchmark::benchmark ${CMAKE_THREAD_LIBS_INIT}) + if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "NVHPC") + target_compile_options( ${name} PRIVATE --diag_suppress partial_override ) + endif() endmacro(compile_benchmark_test) macro(compile_benchmark_test_with_main name) add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark_main) + target_link_libraries(${name} benchmark::benchmark_main) endmacro(compile_benchmark_test_with_main) macro(compile_output_test name) add_executable(${name} "${name}.cc" output_test.h) - target_link_libraries(${name} output_test_helper benchmark + target_link_libraries(${name} output_test_helper benchmark::benchmark_main ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) endmacro(compile_output_test) # Demonstration executable compile_benchmark_test(benchmark_test) -add_test(benchmark benchmark_test --benchmark_min_time=0.01) +add_test(NAME benchmark COMMAND benchmark_test --benchmark_min_time=0.01s) + +compile_benchmark_test(spec_arg_test) +add_test(NAME spec_arg COMMAND spec_arg_test --benchmark_filter=BM_NotChosen) + +compile_benchmark_test(spec_arg_verbosity_test) +add_test(NAME spec_arg_verbosity COMMAND spec_arg_verbosity_test --v=42) + +compile_benchmark_test(benchmark_setup_teardown_test) +add_test(NAME benchmark_setup_teardown COMMAND benchmark_setup_teardown_test) compile_benchmark_test(filter_test) macro(add_filter_test name filter expect) - add_test(${name} filter_test --benchmark_min_time=0.01 --benchmark_filter=${filter} ${expect}) - add_test(${name}_list_only filter_test --benchmark_list_tests --benchmark_filter=${filter} ${expect}) + add_test(NAME ${name} COMMAND filter_test --benchmark_min_time=0.01s --benchmark_filter=${filter} ${expect}) + add_test(NAME ${name}_list_only COMMAND filter_test --benchmark_list_tests --benchmark_filter=${filter} ${expect}) endmacro(add_filter_test) +compile_benchmark_test(benchmark_min_time_flag_time_test) +add_test(NAME min_time_flag_time COMMAND benchmark_min_time_flag_time_test) + +compile_benchmark_test(benchmark_min_time_flag_iters_test) +add_test(NAME min_time_flag_iters COMMAND benchmark_min_time_flag_iters_test) + add_filter_test(filter_simple "Foo" 3) add_filter_test(filter_simple_negative "-Foo" 2) add_filter_test(filter_suffix "BM_.*" 4) @@ -82,16 +107,19 @@ add_filter_test(filter_regex_end ".*Ba$" 1) add_filter_test(filter_regex_end_negative "-.*Ba$" 4) compile_benchmark_test(options_test) -add_test(options_benchmarks options_test --benchmark_min_time=0.01) +add_test(NAME options_benchmarks COMMAND options_test --benchmark_min_time=0.01s) compile_benchmark_test(basic_test) -add_test(basic_benchmark basic_test --benchmark_min_time=0.01) +add_test(NAME basic_benchmark COMMAND basic_test --benchmark_min_time=0.01s) + +compile_output_test(repetitions_test) +add_test(NAME repetitions_benchmark COMMAND repetitions_test --benchmark_min_time=0.01s --benchmark_repetitions=3) compile_benchmark_test(diagnostics_test) -add_test(diagnostics_test diagnostics_test --benchmark_min_time=0.01) +add_test(NAME diagnostics_test COMMAND diagnostics_test --benchmark_min_time=0.01s) compile_benchmark_test(skip_with_error_test) -add_test(skip_with_error_test skip_with_error_test --benchmark_min_time=0.01) +add_test(NAME skip_with_error_test COMMAND skip_with_error_test --benchmark_min_time=0.01s) compile_benchmark_test(donotoptimize_test) # Some of the issues with DoNotOptimize only occur when optimization is enabled @@ -99,77 +127,90 @@ check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) if (BENCHMARK_HAS_O3_FLAG) set_target_properties(donotoptimize_test PROPERTIES COMPILE_FLAGS "-O3") endif() -add_test(donotoptimize_test donotoptimize_test --benchmark_min_time=0.01) +add_test(NAME donotoptimize_test COMMAND donotoptimize_test --benchmark_min_time=0.01s) compile_benchmark_test(fixture_test) -add_test(fixture_test fixture_test --benchmark_min_time=0.01) +add_test(NAME fixture_test COMMAND fixture_test --benchmark_min_time=0.01s) compile_benchmark_test(register_benchmark_test) -add_test(register_benchmark_test register_benchmark_test --benchmark_min_time=0.01) +add_test(NAME register_benchmark_test COMMAND register_benchmark_test --benchmark_min_time=0.01s) compile_benchmark_test(map_test) -add_test(map_test map_test --benchmark_min_time=0.01) +add_test(NAME map_test COMMAND map_test --benchmark_min_time=0.01s) compile_benchmark_test(multiple_ranges_test) -add_test(multiple_ranges_test multiple_ranges_test --benchmark_min_time=0.01) +add_test(NAME multiple_ranges_test COMMAND multiple_ranges_test --benchmark_min_time=0.01s) + +compile_benchmark_test(args_product_test) +add_test(NAME args_product_test COMMAND args_product_test --benchmark_min_time=0.01s) compile_benchmark_test_with_main(link_main_test) -add_test(link_main_test link_main_test --benchmark_min_time=0.01) +add_test(NAME link_main_test COMMAND link_main_test --benchmark_min_time=0.01s) compile_output_test(reporter_output_test) -add_test(reporter_output_test reporter_output_test --benchmark_min_time=0.01) +add_test(NAME reporter_output_test COMMAND reporter_output_test --benchmark_min_time=0.01s) compile_output_test(templated_fixture_test) -add_test(templated_fixture_test templated_fixture_test --benchmark_min_time=0.01) +add_test(NAME templated_fixture_test COMMAND templated_fixture_test --benchmark_min_time=0.01s) compile_output_test(user_counters_test) -add_test(user_counters_test user_counters_test --benchmark_min_time=0.01) +add_test(NAME user_counters_test COMMAND user_counters_test --benchmark_min_time=0.01s) + +compile_output_test(perf_counters_test) +add_test(NAME perf_counters_test COMMAND perf_counters_test --benchmark_min_time=0.01s --benchmark_perf_counters=CYCLES,BRANCHES) compile_output_test(internal_threading_test) -add_test(internal_threading_test internal_threading_test --benchmark_min_time=0.01) +add_test(NAME internal_threading_test COMMAND internal_threading_test --benchmark_min_time=0.01s) compile_output_test(report_aggregates_only_test) -add_test(report_aggregates_only_test report_aggregates_only_test --benchmark_min_time=0.01) +add_test(NAME report_aggregates_only_test COMMAND report_aggregates_only_test --benchmark_min_time=0.01s) compile_output_test(display_aggregates_only_test) -add_test(display_aggregates_only_test display_aggregates_only_test --benchmark_min_time=0.01) +add_test(NAME display_aggregates_only_test COMMAND display_aggregates_only_test --benchmark_min_time=0.01s) compile_output_test(user_counters_tabular_test) -add_test(user_counters_tabular_test user_counters_tabular_test --benchmark_counters_tabular=true --benchmark_min_time=0.01) +add_test(NAME user_counters_tabular_test COMMAND user_counters_tabular_test --benchmark_counters_tabular=true --benchmark_min_time=0.01s) compile_output_test(user_counters_thousands_test) -add_test(user_counters_thousands_test user_counters_thousands_test --benchmark_min_time=0.01) +add_test(NAME user_counters_thousands_test COMMAND user_counters_thousands_test --benchmark_min_time=0.01s) compile_output_test(memory_manager_test) -add_test(memory_manager_test memory_manager_test --benchmark_min_time=0.01) +add_test(NAME memory_manager_test COMMAND memory_manager_test --benchmark_min_time=0.01s) -check_cxx_compiler_flag(-std=c++03 BENCHMARK_HAS_CXX03_FLAG) -if (BENCHMARK_HAS_CXX03_FLAG) +# MSVC does not allow to set the language standard to C++98/03. +if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") compile_benchmark_test(cxx03_test) set_target_properties(cxx03_test PROPERTIES - COMPILE_FLAGS "-std=c++03") + CXX_STANDARD 98 + CXX_STANDARD_REQUIRED YES) # libstdc++ provides different definitions within between dialects. When # LTO is enabled and -Werror is specified GCC diagnoses this ODR violation # causing the test to fail to compile. To prevent this we explicitly disable # the warning. check_cxx_compiler_flag(-Wno-odr BENCHMARK_HAS_WNO_ODR) - if (BENCHMARK_ENABLE_LTO AND BENCHMARK_HAS_WNO_ODR) - set_target_properties(cxx03_test - PROPERTIES - LINK_FLAGS "-Wno-odr") + check_cxx_compiler_flag(-Wno-lto-type-mismatch BENCHMARK_HAS_WNO_LTO_TYPE_MISMATCH) + # Cannot set_target_properties multiple times here because the warnings will + # be overwritten on each call + set (DISABLE_LTO_WARNINGS "") + if (BENCHMARK_HAS_WNO_ODR) + set(DISABLE_LTO_WARNINGS "${DISABLE_LTO_WARNINGS} -Wno-odr") + endif() + if (BENCHMARK_HAS_WNO_LTO_TYPE_MISMATCH) + set(DISABLE_LTO_WARNINGS "${DISABLE_LTO_WARNINGS} -Wno-lto-type-mismatch") endif() - add_test(cxx03 cxx03_test --benchmark_min_time=0.01) + set_target_properties(cxx03_test PROPERTIES LINK_FLAGS "${DISABLE_LTO_WARNINGS}") + add_test(NAME cxx03 COMMAND cxx03_test --benchmark_min_time=0.01s) endif() # Attempt to work around flaky test failures when running on Appveyor servers. if (DEFINED ENV{APPVEYOR}) - set(COMPLEXITY_MIN_TIME "0.5") + set(COMPLEXITY_MIN_TIME "0.5s") else() - set(COMPLEXITY_MIN_TIME "0.01") + set(COMPLEXITY_MIN_TIME "0.01s") endif() compile_output_test(complexity_test) -add_test(complexity_benchmark complexity_test --benchmark_min_time=${COMPLEXITY_MIN_TIME}) +add_test(NAME complexity_benchmark COMMAND complexity_test --benchmark_min_time=${COMPLEXITY_MIN_TIME}) ############################################################################### # GoogleTest Unit Tests @@ -178,20 +219,24 @@ add_test(complexity_benchmark complexity_test --benchmark_min_time=${COMPLEXITY_ if (BENCHMARK_ENABLE_GTEST_TESTS) macro(compile_gtest name) add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark + target_link_libraries(${name} benchmark::benchmark gmock_main ${CMAKE_THREAD_LIBS_INIT}) endmacro(compile_gtest) macro(add_gtest name) compile_gtest(${name}) - add_test(${name} ${name}) + add_test(NAME ${name} COMMAND ${name}) endmacro() add_gtest(benchmark_gtest) add_gtest(benchmark_name_gtest) + add_gtest(benchmark_random_interleaving_gtest) add_gtest(commandlineflags_gtest) add_gtest(statistics_gtest) add_gtest(string_util_gtest) + add_gtest(perf_counters_gtest) + add_gtest(time_unit_gtest) + add_gtest(min_time_parse_gtest) endif(BENCHMARK_ENABLE_GTEST_TESTS) ############################################################################### diff --git a/thirdparty_builtin/benchmark-1.8.0/test/args_product_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/args_product_test.cc new file mode 100644 index 000000000..63b8b71e4 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/args_product_test.cc @@ -0,0 +1,77 @@ +#include +#include +#include +#include + +#include "benchmark/benchmark.h" + +class ArgsProductFixture : public ::benchmark::Fixture { + public: + ArgsProductFixture() + : expectedValues({{0, 100, 2000, 30000}, + {1, 15, 3, 8}, + {1, 15, 3, 9}, + {1, 15, 7, 8}, + {1, 15, 7, 9}, + {1, 15, 10, 8}, + {1, 15, 10, 9}, + {2, 15, 3, 8}, + {2, 15, 3, 9}, + {2, 15, 7, 8}, + {2, 15, 7, 9}, + {2, 15, 10, 8}, + {2, 15, 10, 9}, + {4, 5, 6, 11}}) {} + + void SetUp(const ::benchmark::State& state) override { + std::vector ranges = {state.range(0), state.range(1), + state.range(2), state.range(3)}; + + assert(expectedValues.find(ranges) != expectedValues.end()); + + actualValues.insert(ranges); + } + + // NOTE: This is not TearDown as we want to check after _all_ runs are + // complete. + ~ArgsProductFixture() override { + if (actualValues != expectedValues) { + std::cout << "EXPECTED\n"; + for (const auto& v : expectedValues) { + std::cout << "{"; + for (int64_t iv : v) { + std::cout << iv << ", "; + } + std::cout << "}\n"; + } + std::cout << "ACTUAL\n"; + for (const auto& v : actualValues) { + std::cout << "{"; + for (int64_t iv : v) { + std::cout << iv << ", "; + } + std::cout << "}\n"; + } + } + } + + std::set> expectedValues; + std::set> actualValues; +}; + +BENCHMARK_DEFINE_F(ArgsProductFixture, Empty)(benchmark::State& state) { + for (auto _ : state) { + int64_t product = + state.range(0) * state.range(1) * state.range(2) * state.range(3); + for (int64_t x = 0; x < product; x++) { + benchmark::DoNotOptimize(x); + } + } +} + +BENCHMARK_REGISTER_F(ArgsProductFixture, Empty) + ->Args({0, 100, 2000, 30000}) + ->ArgsProduct({{1, 2}, {15}, {3, 7, 10}, {8, 9}}) + ->Args({4, 5, 6, 11}); + +BENCHMARK_MAIN(); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/basic_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/basic_test.cc similarity index 54% rename from thirdparty_builtin/benchmark-1.5.0/test/basic_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/basic_test.cc index 5f3dd1a3e..cba1b0f99 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/basic_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/basic_test.cc @@ -5,7 +5,8 @@ void BM_empty(benchmark::State& state) { for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } } BENCHMARK(BM_empty); @@ -13,7 +14,7 @@ BENCHMARK(BM_empty)->ThreadPerCpu(); void BM_spin_empty(benchmark::State& state) { for (auto _ : state) { - for (int x = 0; x < state.range(0); ++x) { + for (auto x = 0; x < state.range(0); ++x) { benchmark::DoNotOptimize(x); } } @@ -22,11 +23,11 @@ BASIC_BENCHMARK_TEST(BM_spin_empty); BASIC_BENCHMARK_TEST(BM_spin_empty)->ThreadPerCpu(); void BM_spin_pause_before(benchmark::State& state) { - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } } @@ -37,11 +38,11 @@ BASIC_BENCHMARK_TEST(BM_spin_pause_before)->ThreadPerCpu(); void BM_spin_pause_during(benchmark::State& state) { for (auto _ : state) { state.PauseTiming(); - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } state.ResumeTiming(); - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } } @@ -62,11 +63,11 @@ BENCHMARK(BM_pause_during)->UseRealTime()->ThreadPerCpu(); void BM_spin_pause_after(benchmark::State& state) { for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } } - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } } @@ -74,15 +75,15 @@ BASIC_BENCHMARK_TEST(BM_spin_pause_after); BASIC_BENCHMARK_TEST(BM_spin_pause_after)->ThreadPerCpu(); void BM_spin_pause_before_and_after(benchmark::State& state) { - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } } - for (int i = 0; i < state.range(0); ++i) { + for (auto i = 0; i < state.range(0); ++i) { benchmark::DoNotOptimize(i); } } @@ -96,7 +97,6 @@ void BM_empty_stop_start(benchmark::State& state) { BENCHMARK(BM_empty_stop_start); BENCHMARK(BM_empty_stop_start)->ThreadPerCpu(); - void BM_KeepRunning(benchmark::State& state) { benchmark::IterationCount iter_count = 0; assert(iter_count == state.iterations()); @@ -108,15 +108,30 @@ void BM_KeepRunning(benchmark::State& state) { BENCHMARK(BM_KeepRunning); void BM_KeepRunningBatch(benchmark::State& state) { - // Choose a prime batch size to avoid evenly dividing max_iterations. - const benchmark::IterationCount batch_size = 101; + // Choose a batch size >1000 to skip the typical runs with iteration + // targets of 10, 100 and 1000. If these are not actually skipped the + // bug would be detectable as consecutive runs with the same iteration + // count. Below we assert that this does not happen. + const benchmark::IterationCount batch_size = 1009; + + static benchmark::IterationCount prior_iter_count = 0; benchmark::IterationCount iter_count = 0; while (state.KeepRunningBatch(batch_size)) { iter_count += batch_size; } assert(state.iterations() == iter_count); + + // Verify that the iteration count always increases across runs (see + // comment above). + assert(iter_count == batch_size // max_iterations == 1 + || iter_count > prior_iter_count); // max_iterations > batch_size + prior_iter_count = iter_count; } -BENCHMARK(BM_KeepRunningBatch); +// Register with a fixed repetition count to establish the invariant that +// the iteration count should always change across runs. This overrides +// the --benchmark_repetitions command line flag, which would otherwise +// cause this test to fail if set > 1. +BENCHMARK(BM_KeepRunningBatch)->Repetitions(1); void BM_RangedFor(benchmark::State& state) { benchmark::IterationCount iter_count = 0; @@ -127,10 +142,39 @@ void BM_RangedFor(benchmark::State& state) { } BENCHMARK(BM_RangedFor); +#ifdef BENCHMARK_HAS_CXX11 +template +void BM_OneTemplateFunc(benchmark::State& state) { + auto arg = state.range(0); + T sum = 0; + for (auto _ : state) { + sum += static_cast(arg); + } +} +BENCHMARK(BM_OneTemplateFunc)->Arg(1); +BENCHMARK(BM_OneTemplateFunc)->Arg(1); + +template +void BM_TwoTemplateFunc(benchmark::State& state) { + auto arg = state.range(0); + A sum = 0; + B prod = 1; + for (auto _ : state) { + sum += static_cast(arg); + prod *= static_cast(arg); + } +} +BENCHMARK(BM_TwoTemplateFunc)->Arg(1); +BENCHMARK(BM_TwoTemplateFunc)->Arg(1); + +#endif // BENCHMARK_HAS_CXX11 + // Ensure that StateIterator provides all the necessary typedefs required to // instantiate std::iterator_traits. -static_assert(std::is_same< - typename std::iterator_traits::value_type, - typename benchmark::State::StateIterator::value_type>::value, ""); +static_assert( + std::is_same::value_type, + typename benchmark::State::StateIterator::value_type>::value, + ""); BENCHMARK_MAIN(); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/benchmark_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_gtest.cc similarity index 73% rename from thirdparty_builtin/benchmark-1.5.0/test/benchmark_gtest.cc rename to thirdparty_builtin/benchmark-1.8.0/test/benchmark_gtest.cc index 9557b20ec..2c9e555d9 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/benchmark_gtest.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_gtest.cc @@ -1,11 +1,15 @@ +#include +#include #include #include "../src/benchmark_register.h" +#include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace benchmark { namespace internal { + namespace { TEST(AddRangeTest, Simple) { @@ -34,8 +38,9 @@ TEST(AddRangeTest, Advanced64) { TEST(AddRangeTest, FullRange8) { std::vector dst; - AddRange(&dst, int8_t{1}, std::numeric_limits::max(), 8); - EXPECT_THAT(dst, testing::ElementsAre(1, 8, 64, 127)); + AddRange(&dst, int8_t{1}, std::numeric_limits::max(), int8_t{8}); + EXPECT_THAT( + dst, testing::ElementsAre(int8_t{1}, int8_t{8}, int8_t{64}, int8_t{127})); } TEST(AddRangeTest, FullRange64) { @@ -90,6 +95,12 @@ TEST(AddRangeTest, ZeroOnlyRange) { EXPECT_THAT(dst, testing::ElementsAre(0)); } +TEST(AddRangeTest, ZeroStartingRange) { + std::vector dst; + AddRange(&dst, 0, 2, 2); + EXPECT_THAT(dst, testing::ElementsAre(0, 1, 2)); +} + TEST(AddRangeTest, NegativeRange64) { std::vector dst; AddRange(&dst, -4, 4, 2); @@ -119,8 +130,38 @@ TEST(AddRangeTest, FullNegativeRange64) { TEST(AddRangeTest, Simple8) { std::vector dst; - AddRange(&dst, 1, 8, 2); - EXPECT_THAT(dst, testing::ElementsAre(1, 2, 4, 8)); + AddRange(&dst, int8_t{1}, int8_t{8}, int8_t{2}); + EXPECT_THAT(dst, + testing::ElementsAre(int8_t{1}, int8_t{2}, int8_t{4}, int8_t{8})); +} + +TEST(AddCustomContext, Simple) { + std::map *&global_context = GetGlobalContext(); + EXPECT_THAT(global_context, nullptr); + + AddCustomContext("foo", "bar"); + AddCustomContext("baz", "qux"); + + EXPECT_THAT(*global_context, + testing::UnorderedElementsAre(testing::Pair("foo", "bar"), + testing::Pair("baz", "qux"))); + + delete global_context; + global_context = nullptr; +} + +TEST(AddCustomContext, DuplicateKey) { + std::map *&global_context = GetGlobalContext(); + EXPECT_THAT(global_context, nullptr); + + AddCustomContext("foo", "bar"); + AddCustomContext("foo", "qux"); + + EXPECT_THAT(*global_context, + testing::UnorderedElementsAre(testing::Pair("foo", "bar"))); + + delete global_context; + global_context = nullptr; } } // namespace diff --git a/thirdparty_builtin/benchmark-1.8.0/test/benchmark_min_time_flag_iters_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_min_time_flag_iters_test.cc new file mode 100644 index 000000000..eb9414acd --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_min_time_flag_iters_test.cc @@ -0,0 +1,66 @@ +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" + +// Tests that we can specify the number of iterations with +// --benchmark_min_time=x. +namespace { + +class TestReporter : public benchmark::ConsoleReporter { + public: + virtual bool ReportContext(const Context& context) BENCHMARK_OVERRIDE { + return ConsoleReporter::ReportContext(context); + }; + + virtual void ReportRuns(const std::vector& report) BENCHMARK_OVERRIDE { + assert(report.size() == 1); + iter_nums_.push_back(report[0].iterations); + ConsoleReporter::ReportRuns(report); + }; + + TestReporter() {} + + virtual ~TestReporter() {} + + const std::vector& GetIters() const { + return iter_nums_; + } + + private: + std::vector iter_nums_; +}; + +} // end namespace + +static void BM_MyBench(benchmark::State& state) { + for (auto s : state) { + } +} +BENCHMARK(BM_MyBench); + +int main(int argc, char** argv) { + // Make a fake argv and append the new --benchmark_min_time= to it. + int fake_argc = argc + 1; + const char** fake_argv = new const char*[fake_argc]; + for (int i = 0; i < argc; ++i) fake_argv[i] = argv[i]; + fake_argv[argc] = "--benchmark_min_time=4x"; + + benchmark::Initialize(&fake_argc, const_cast(fake_argv)); + + TestReporter test_reporter; + const size_t returned_count = + benchmark::RunSpecifiedBenchmarks(&test_reporter, "BM_MyBench"); + assert(returned_count == 1); + + // Check the executed iters. + const std::vector iters = test_reporter.GetIters(); + assert(!iters.empty() && iters[0] == 4); + + delete[] fake_argv; + return 0; +} diff --git a/thirdparty_builtin/benchmark-1.8.0/test/benchmark_min_time_flag_time_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_min_time_flag_time_test.cc new file mode 100644 index 000000000..b172cccba --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_min_time_flag_time_test.cc @@ -0,0 +1,90 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" + +// Tests that we can specify the min time with +// --benchmark_min_time= (no suffix needed) OR +// --benchmark_min_time=s +namespace { + +// This is from benchmark.h +typedef int64_t IterationCount; + +class TestReporter : public benchmark::ConsoleReporter { + public: + virtual bool ReportContext(const Context& context) BENCHMARK_OVERRIDE { + return ConsoleReporter::ReportContext(context); + }; + + virtual void ReportRuns(const std::vector& report) BENCHMARK_OVERRIDE { + assert(report.size() == 1); + ConsoleReporter::ReportRuns(report); + }; + + virtual void ReportRunsConfig(double min_time, bool /* has_explicit_iters */, + IterationCount /* iters */) BENCHMARK_OVERRIDE { + min_times_.push_back(min_time); + } + + TestReporter() {} + + virtual ~TestReporter() {} + + const std::vector& GetMinTimes() const { return min_times_; } + + private: + std::vector min_times_; +}; + +bool AlmostEqual(double a, double b) { + return std::fabs(a - b) < std::numeric_limits::epsilon(); +} + +void DoTestHelper(int* argc, const char** argv, double expected) { + benchmark::Initialize(argc, const_cast(argv)); + + TestReporter test_reporter; + const size_t returned_count = + benchmark::RunSpecifiedBenchmarks(&test_reporter, "BM_MyBench"); + assert(returned_count == 1); + + // Check the min_time + const std::vector& min_times = test_reporter.GetMinTimes(); + assert(!min_times.empty() && AlmostEqual(min_times[0], expected)); +} + +} // end namespace + +static void BM_MyBench(benchmark::State& state) { + for (auto s : state) { + } +} +BENCHMARK(BM_MyBench); + +int main(int argc, char** argv) { + // Make a fake argv and append the new --benchmark_min_time= to it. + int fake_argc = argc + 1; + const char** fake_argv = new const char*[fake_argc]; + + for (int i = 0; i < argc; ++i) fake_argv[i] = argv[i]; + + const char* no_suffix = "--benchmark_min_time=4"; + const char* with_suffix = "--benchmark_min_time=4.0s"; + double expected = 4.0; + + fake_argv[argc] = no_suffix; + DoTestHelper(&fake_argc, fake_argv, expected); + + fake_argv[argc] = with_suffix; + DoTestHelper(&fake_argc, fake_argv, expected); + + delete[] fake_argv; + return 0; +} diff --git a/thirdparty_builtin/benchmark-1.5.0/test/benchmark_name_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_name_gtest.cc similarity index 88% rename from thirdparty_builtin/benchmark-1.5.0/test/benchmark_name_gtest.cc rename to thirdparty_builtin/benchmark-1.8.0/test/benchmark_name_gtest.cc index afb401c1f..0a6746d04 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/benchmark_name_gtest.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_name_gtest.cc @@ -32,6 +32,14 @@ TEST(BenchmarkNameTest, MinTime) { EXPECT_EQ(name.str(), "function_name/some_args:3/4/min_time:3.4s"); } +TEST(BenchmarkNameTest, MinWarmUpTime) { + auto name = BenchmarkName(); + name.function_name = "function_name"; + name.args = "some_args:3/4"; + name.min_warmup_time = "min_warmup_time:3.5s"; + EXPECT_EQ(name.str(), "function_name/some_args:3/4/min_warmup_time:3.5s"); +} + TEST(BenchmarkNameTest, Iterations) { auto name = BenchmarkName(); name.function_name = "function_name"; diff --git a/thirdparty_builtin/benchmark-1.8.0/test/benchmark_random_interleaving_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_random_interleaving_gtest.cc new file mode 100644 index 000000000..7f2086750 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_random_interleaving_gtest.cc @@ -0,0 +1,126 @@ +#include +#include +#include + +#include "../src/commandlineflags.h" +#include "../src/string_util.h" +#include "benchmark/benchmark.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace benchmark { + +BM_DECLARE_bool(benchmark_enable_random_interleaving); +BM_DECLARE_string(benchmark_filter); +BM_DECLARE_int32(benchmark_repetitions); + +namespace internal { +namespace { + +class EventQueue : public std::queue { + public: + void Put(const std::string& event) { push(event); } + + void Clear() { + while (!empty()) { + pop(); + } + } + + std::string Get() { + std::string event = front(); + pop(); + return event; + } +}; + +EventQueue* queue = new EventQueue(); + +class NullReporter : public BenchmarkReporter { + public: + bool ReportContext(const Context& /*context*/) override { return true; } + void ReportRuns(const std::vector& /* report */) override {} +}; + +class BenchmarkTest : public testing::Test { + public: + static void SetupHook(int /* num_threads */) { queue->push("Setup"); } + + static void TeardownHook(int /* num_threads */) { queue->push("Teardown"); } + + void Execute(const std::string& pattern) { + queue->Clear(); + + std::unique_ptr reporter(new NullReporter()); + FLAGS_benchmark_filter = pattern; + RunSpecifiedBenchmarks(reporter.get()); + + queue->Put("DONE"); // End marker + } +}; + +void BM_Match1(benchmark::State& state) { + const int64_t arg = state.range(0); + + for (auto _ : state) { + } + queue->Put(StrFormat("BM_Match1/%d", static_cast(arg))); +} +BENCHMARK(BM_Match1) + ->Iterations(100) + ->Arg(1) + ->Arg(2) + ->Arg(3) + ->Range(10, 80) + ->Args({90}) + ->Args({100}); + +TEST_F(BenchmarkTest, Match1) { + Execute("BM_Match1"); + ASSERT_EQ("BM_Match1/1", queue->Get()); + ASSERT_EQ("BM_Match1/2", queue->Get()); + ASSERT_EQ("BM_Match1/3", queue->Get()); + ASSERT_EQ("BM_Match1/10", queue->Get()); + ASSERT_EQ("BM_Match1/64", queue->Get()); + ASSERT_EQ("BM_Match1/80", queue->Get()); + ASSERT_EQ("BM_Match1/90", queue->Get()); + ASSERT_EQ("BM_Match1/100", queue->Get()); + ASSERT_EQ("DONE", queue->Get()); +} + +TEST_F(BenchmarkTest, Match1WithRepetition) { + FLAGS_benchmark_repetitions = 2; + + Execute("BM_Match1/(64|80)"); + ASSERT_EQ("BM_Match1/64", queue->Get()); + ASSERT_EQ("BM_Match1/64", queue->Get()); + ASSERT_EQ("BM_Match1/80", queue->Get()); + ASSERT_EQ("BM_Match1/80", queue->Get()); + ASSERT_EQ("DONE", queue->Get()); +} + +TEST_F(BenchmarkTest, Match1WithRandomInterleaving) { + FLAGS_benchmark_enable_random_interleaving = true; + FLAGS_benchmark_repetitions = 100; + + std::map element_count; + std::map interleaving_count; + Execute("BM_Match1/(64|80)"); + for (int i = 0; i < 100; ++i) { + std::vector interleaving; + interleaving.push_back(queue->Get()); + interleaving.push_back(queue->Get()); + element_count[interleaving[0]]++; + element_count[interleaving[1]]++; + interleaving_count[StrFormat("%s,%s", interleaving[0].c_str(), + interleaving[1].c_str())]++; + } + EXPECT_EQ(element_count["BM_Match1/64"], 100) << "Unexpected repetitions."; + EXPECT_EQ(element_count["BM_Match1/80"], 100) << "Unexpected repetitions."; + EXPECT_GE(interleaving_count.size(), 2) << "Interleaving was not randomized."; + ASSERT_EQ("DONE", queue->Get()); +} + +} // namespace +} // namespace internal +} // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/test/benchmark_setup_teardown_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_setup_teardown_test.cc new file mode 100644 index 000000000..6c3cc2e58 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_setup_teardown_test.cc @@ -0,0 +1,157 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" + +// Test that Setup() and Teardown() are called exactly once +// for each benchmark run (single-threaded). +namespace singlethreaded { +static int setup_call = 0; +static int teardown_call = 0; +} // namespace singlethreaded +static void DoSetup1(const benchmark::State& state) { + ++singlethreaded::setup_call; + + // Setup/Teardown should never be called with any thread_idx != 0. + assert(state.thread_index() == 0); +} + +static void DoTeardown1(const benchmark::State& state) { + ++singlethreaded::teardown_call; + assert(state.thread_index() == 0); +} + +static void BM_with_setup(benchmark::State& state) { + for (auto s : state) { + } +} +BENCHMARK(BM_with_setup) + ->Arg(1) + ->Arg(3) + ->Arg(5) + ->Arg(7) + ->Iterations(100) + ->Setup(DoSetup1) + ->Teardown(DoTeardown1); + +// Test that Setup() and Teardown() are called once for each group of threads. +namespace concurrent { +static std::atomic setup_call(0); +static std::atomic teardown_call(0); +static std::atomic func_call(0); +} // namespace concurrent + +static void DoSetup2(const benchmark::State& state) { + concurrent::setup_call.fetch_add(1, std::memory_order_acquire); + assert(state.thread_index() == 0); +} + +static void DoTeardown2(const benchmark::State& state) { + concurrent::teardown_call.fetch_add(1, std::memory_order_acquire); + assert(state.thread_index() == 0); +} + +static void BM_concurrent(benchmark::State& state) { + for (auto s : state) { + } + concurrent::func_call.fetch_add(1, std::memory_order_acquire); +} + +BENCHMARK(BM_concurrent) + ->Setup(DoSetup2) + ->Teardown(DoTeardown2) + ->Iterations(100) + ->Threads(5) + ->Threads(10) + ->Threads(15); + +// Testing interaction with Fixture::Setup/Teardown +namespace fixture_interaction { +int setup = 0; +int fixture_setup = 0; +} // namespace fixture_interaction + +#define FIXTURE_BECHMARK_NAME MyFixture + +class FIXTURE_BECHMARK_NAME : public ::benchmark::Fixture { + public: + void SetUp(const ::benchmark::State&) override { + fixture_interaction::fixture_setup++; + } + + ~FIXTURE_BECHMARK_NAME() override {} +}; + +BENCHMARK_F(FIXTURE_BECHMARK_NAME, BM_WithFixture)(benchmark::State& st) { + for (auto _ : st) { + } +} + +static void DoSetupWithFixture(const benchmark::State&) { + fixture_interaction::setup++; +} + +BENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, BM_WithFixture) + ->Arg(1) + ->Arg(3) + ->Arg(5) + ->Arg(7) + ->Setup(DoSetupWithFixture) + ->Repetitions(1) + ->Iterations(100); + +// Testing repetitions. +namespace repetitions { +int setup = 0; +} + +static void DoSetupWithRepetitions(const benchmark::State&) { + repetitions::setup++; +} +static void BM_WithRep(benchmark::State& state) { + for (auto _ : state) { + } +} + +BENCHMARK(BM_WithRep) + ->Arg(1) + ->Arg(3) + ->Arg(5) + ->Arg(7) + ->Setup(DoSetupWithRepetitions) + ->Iterations(100) + ->Repetitions(4); + +int main(int argc, char** argv) { + benchmark::Initialize(&argc, argv); + + size_t ret = benchmark::RunSpecifiedBenchmarks("."); + assert(ret > 0); + + // Setup/Teardown is called once for each arg group (1,3,5,7). + assert(singlethreaded::setup_call == 4); + assert(singlethreaded::teardown_call == 4); + + // 3 group of threads calling this function (3,5,10). + assert(concurrent::setup_call.load(std::memory_order_relaxed) == 3); + assert(concurrent::teardown_call.load(std::memory_order_relaxed) == 3); + assert((5 + 10 + 15) == + concurrent::func_call.load(std::memory_order_relaxed)); + + // Setup is called 4 times, once for each arg group (1,3,5,7) + assert(fixture_interaction::setup == 4); + // Fixture::Setup is called every time the bm routine is run. + // The exact number is indeterministic, so we just assert that + // it's more than setup. + assert(fixture_interaction::fixture_setup > fixture_interaction::setup); + + // Setup is call once for each repetition * num_arg = 4 * 4 = 16. + assert(repetitions::setup == 16); + + return 0; +} diff --git a/thirdparty_builtin/benchmark-1.5.0/test/benchmark_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_test.cc similarity index 78% rename from thirdparty_builtin/benchmark-1.5.0/test/benchmark_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/benchmark_test.cc index 3cd4f5565..94590d5e4 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/benchmark_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/benchmark_test.cc @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -26,7 +27,7 @@ namespace { -int BENCHMARK_NOINLINE Factorial(uint32_t n) { +int BENCHMARK_NOINLINE Factorial(int n) { return (n == 1) ? 1 : n * Factorial(n - 1); } @@ -74,7 +75,8 @@ BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024); static void BM_CalculatePi(benchmark::State& state) { static const int depth = 1024; for (auto _ : state) { - benchmark::DoNotOptimize(CalculatePi(static_cast(depth))); + double pi = CalculatePi(static_cast(depth)); + benchmark::DoNotOptimize(pi); } } BENCHMARK(BM_CalculatePi)->Threads(8); @@ -90,11 +92,13 @@ static void BM_SetInsert(benchmark::State& state) { for (int j = 0; j < state.range(1); ++j) data.insert(rand()); } state.SetItemsProcessed(state.iterations() * state.range(1)); - state.SetBytesProcessed(state.iterations() * state.range(1) * sizeof(int)); + state.SetBytesProcessed(state.iterations() * state.range(1) * + static_cast(sizeof(int))); } -// Test many inserts at once to reduce the total iterations needed. Otherwise, the slower, -// non-timed part of each iteration will make the benchmark take forever. +// Test many inserts at once to reduce the total iterations needed. Otherwise, +// the slower, non-timed part of each iteration will make the benchmark take +// forever. BENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}}); template (sizeof(v))); } BENCHMARK_TEMPLATE2(BM_Sequential, std::vector, int) ->Range(1 << 0, 1 << 10); @@ -121,12 +125,15 @@ static void BM_StringCompare(benchmark::State& state) { size_t len = static_cast(state.range(0)); std::string s1(len, '-'); std::string s2(len, '-'); - for (auto _ : state) benchmark::DoNotOptimize(s1.compare(s2)); + for (auto _ : state) { + auto comp = s1.compare(s2); + benchmark::DoNotOptimize(comp); + } } BENCHMARK(BM_StringCompare)->Range(1, 1 << 20); static void BM_SetupTeardown(benchmark::State& state) { - if (state.thread_index == 0) { + if (state.thread_index() == 0) { // No need to lock test_vector_mu here as this is running single-threaded. test_vector = new std::vector(); } @@ -139,7 +146,7 @@ static void BM_SetupTeardown(benchmark::State& state) { test_vector->pop_back(); ++i; } - if (state.thread_index == 0) { + if (state.thread_index() == 0) { delete test_vector; } } @@ -156,11 +163,11 @@ BENCHMARK(BM_LongTest)->Range(1 << 16, 1 << 28); static void BM_ParallelMemset(benchmark::State& state) { int64_t size = state.range(0) / static_cast(sizeof(int)); - int thread_size = static_cast(size) / state.threads; - int from = thread_size * state.thread_index; + int thread_size = static_cast(size) / state.threads(); + int from = thread_size * state.thread_index(); int to = from + thread_size; - if (state.thread_index == 0) { + if (state.thread_index() == 0) { test_vector = new std::vector(static_cast(size)); } @@ -168,11 +175,11 @@ static void BM_ParallelMemset(benchmark::State& state) { for (int i = from; i < to; i++) { // No need to lock test_vector_mu as ranges // do not overlap between threads. - benchmark::DoNotOptimize(test_vector->at(i) = 1); + benchmark::DoNotOptimize(test_vector->at(static_cast(i)) = 1); } } - if (state.thread_index == 0) { + if (state.thread_index() == 0) { delete test_vector; } } @@ -214,7 +221,8 @@ BENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string("abc"), std::pair(42, 3.8)); void BM_non_template_args(benchmark::State& state, int, double) { - while(state.KeepRunning()) {} + while (state.KeepRunning()) { + } } BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0); @@ -223,14 +231,14 @@ BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0); static void BM_DenseThreadRanges(benchmark::State& st) { switch (st.range(0)) { case 1: - assert(st.threads == 1 || st.threads == 2 || st.threads == 3); + assert(st.threads() == 1 || st.threads() == 2 || st.threads() == 3); break; case 2: - assert(st.threads == 1 || st.threads == 3 || st.threads == 4); + assert(st.threads() == 1 || st.threads() == 3 || st.threads() == 4); break; case 3: - assert(st.threads == 5 || st.threads == 8 || st.threads == 11 || - st.threads == 14); + assert(st.threads() == 5 || st.threads() == 8 || st.threads() == 11 || + st.threads() == 14); break; default: assert(false && "Invalid test case number"); @@ -242,4 +250,25 @@ BENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3); BENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2); BENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3); +static void BM_BenchmarkName(benchmark::State& state) { + for (auto _ : state) { + } + + // Check that the benchmark name is passed correctly to `state`. + assert("BM_BenchmarkName" == state.name()); +} +BENCHMARK(BM_BenchmarkName); + +// regression test for #1446 +template +static void BM_templated_test(benchmark::State& state) { + for (auto _ : state) { + type created_string; + benchmark::DoNotOptimize(created_string); + } +} + +static auto BM_templated_test_double = BM_templated_test>; +BENCHMARK(BM_templated_test_double); + BENCHMARK_MAIN(); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/clobber_memory_assembly_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/clobber_memory_assembly_test.cc similarity index 97% rename from thirdparty_builtin/benchmark-1.5.0/test/clobber_memory_assembly_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/clobber_memory_assembly_test.cc index f41911a39..54e26ccda 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/clobber_memory_assembly_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/clobber_memory_assembly_test.cc @@ -3,13 +3,13 @@ #ifdef __clang__ #pragma clang diagnostic ignored "-Wreturn-type" #endif +BENCHMARK_DISABLE_DEPRECATED_WARNING extern "C" { extern int ExternInt; extern int ExternInt2; extern int ExternInt3; - } // CHECK-LABEL: test_basic: diff --git a/thirdparty_builtin/benchmark-1.8.0/test/commandlineflags_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/commandlineflags_gtest.cc new file mode 100644 index 000000000..8412008ff --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/commandlineflags_gtest.cc @@ -0,0 +1,228 @@ +#include + +#include "../src/commandlineflags.h" +#include "../src/internal_macros.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace benchmark { +namespace { + +#if defined(BENCHMARK_OS_WINDOWS) +int setenv(const char* name, const char* value, int overwrite) { + if (!overwrite) { + // NOTE: getenv_s is far superior but not available under mingw. + char* env_value = getenv(name); + if (env_value == nullptr) { + return -1; + } + } + return _putenv_s(name, value); +} + +int unsetenv(const char* name) { return _putenv_s(name, ""); } + +#endif // BENCHMARK_OS_WINDOWS + +TEST(BoolFromEnv, Default) { + ASSERT_EQ(unsetenv("NOT_IN_ENV"), 0); + EXPECT_EQ(BoolFromEnv("not_in_env", true), true); +} + +TEST(BoolFromEnv, False) { + ASSERT_EQ(setenv("IN_ENV", "0", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "N", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "n", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "NO", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "No", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "no", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "F", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "f", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "FALSE", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "False", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "false", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "OFF", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "Off", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "off", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", true), false); + unsetenv("IN_ENV"); +} + +TEST(BoolFromEnv, True) { + ASSERT_EQ(setenv("IN_ENV", "1", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "Y", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "y", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "YES", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "Yes", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "yes", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "T", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "t", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "TRUE", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "True", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "true", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "ON", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "On", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + + ASSERT_EQ(setenv("IN_ENV", "on", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); + +#ifndef BENCHMARK_OS_WINDOWS + ASSERT_EQ(setenv("IN_ENV", "", 1), 0); + EXPECT_EQ(BoolFromEnv("in_env", false), true); + unsetenv("IN_ENV"); +#endif +} + +TEST(Int32FromEnv, NotInEnv) { + ASSERT_EQ(unsetenv("NOT_IN_ENV"), 0); + EXPECT_EQ(Int32FromEnv("not_in_env", 42), 42); +} + +TEST(Int32FromEnv, InvalidInteger) { + ASSERT_EQ(setenv("IN_ENV", "foo", 1), 0); + EXPECT_EQ(Int32FromEnv("in_env", 42), 42); + unsetenv("IN_ENV"); +} + +TEST(Int32FromEnv, ValidInteger) { + ASSERT_EQ(setenv("IN_ENV", "42", 1), 0); + EXPECT_EQ(Int32FromEnv("in_env", 64), 42); + unsetenv("IN_ENV"); +} + +TEST(DoubleFromEnv, NotInEnv) { + ASSERT_EQ(unsetenv("NOT_IN_ENV"), 0); + EXPECT_EQ(DoubleFromEnv("not_in_env", 0.51), 0.51); +} + +TEST(DoubleFromEnv, InvalidReal) { + ASSERT_EQ(setenv("IN_ENV", "foo", 1), 0); + EXPECT_EQ(DoubleFromEnv("in_env", 0.51), 0.51); + unsetenv("IN_ENV"); +} + +TEST(DoubleFromEnv, ValidReal) { + ASSERT_EQ(setenv("IN_ENV", "0.51", 1), 0); + EXPECT_EQ(DoubleFromEnv("in_env", 0.71), 0.51); + unsetenv("IN_ENV"); +} + +TEST(StringFromEnv, Default) { + ASSERT_EQ(unsetenv("NOT_IN_ENV"), 0); + EXPECT_STREQ(StringFromEnv("not_in_env", "foo"), "foo"); +} + +TEST(StringFromEnv, Valid) { + ASSERT_EQ(setenv("IN_ENV", "foo", 1), 0); + EXPECT_STREQ(StringFromEnv("in_env", "bar"), "foo"); + unsetenv("IN_ENV"); +} + +TEST(KvPairsFromEnv, Default) { + ASSERT_EQ(unsetenv("NOT_IN_ENV"), 0); + EXPECT_THAT(KvPairsFromEnv("not_in_env", {{"foo", "bar"}}), + testing::ElementsAre(testing::Pair("foo", "bar"))); +} + +TEST(KvPairsFromEnv, MalformedReturnsDefault) { + ASSERT_EQ(setenv("IN_ENV", "foo", 1), 0); + EXPECT_THAT(KvPairsFromEnv("in_env", {{"foo", "bar"}}), + testing::ElementsAre(testing::Pair("foo", "bar"))); + unsetenv("IN_ENV"); +} + +TEST(KvPairsFromEnv, Single) { + ASSERT_EQ(setenv("IN_ENV", "foo=bar", 1), 0); + EXPECT_THAT(KvPairsFromEnv("in_env", {}), + testing::ElementsAre(testing::Pair("foo", "bar"))); + unsetenv("IN_ENV"); +} + +TEST(KvPairsFromEnv, Multiple) { + ASSERT_EQ(setenv("IN_ENV", "foo=bar,baz=qux", 1), 0); + EXPECT_THAT(KvPairsFromEnv("in_env", {}), + testing::UnorderedElementsAre(testing::Pair("foo", "bar"), + testing::Pair("baz", "qux"))); + unsetenv("IN_ENV"); +} + +} // namespace +} // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.5.0/test/complexity_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/complexity_test.cc similarity index 70% rename from thirdparty_builtin/benchmark-1.5.0/test/complexity_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/complexity_test.cc index d4febbbc1..76891e07b 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/complexity_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/complexity_test.cc @@ -4,6 +4,7 @@ #include #include #include + #include "benchmark/benchmark.h" #include "output_test.h" @@ -12,8 +13,10 @@ namespace { #define ADD_COMPLEXITY_CASES(...) \ int CONCAT(dummy, __LINE__) = AddComplexityTest(__VA_ARGS__) -int AddComplexityTest(std::string test_name, std::string big_o_test_name, - std::string rms_test_name, std::string big_o) { +int AddComplexityTest(const std::string &test_name, + const std::string &big_o_test_name, + const std::string &rms_test_name, + const std::string &big_o, int family_index) { SetSubstitutions({{"%name", test_name}, {"%bigo_name", big_o_test_name}, {"%rms_name", rms_test_name}, @@ -25,25 +28,33 @@ int AddComplexityTest(std::string test_name, std::string big_o_test_name, {{"^%bigo_name %bigo_str %bigo_str[ ]*$"}, {"^%bigo_name", MR_Not}, // Assert we we didn't only matched a name. {"^%rms_name %rms %rms[ ]*$", MR_Next}}); - AddCases(TC_JSONOut, {{"\"name\": \"%bigo_name\",$"}, - {"\"run_name\": \"%name\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": %int,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"BigO\",$", MR_Next}, - {"\"cpu_coefficient\": %float,$", MR_Next}, - {"\"real_coefficient\": %float,$", MR_Next}, - {"\"big_o\": \"%bigo\",$", MR_Next}, - {"\"time_unit\": \"ns\"$", MR_Next}, - {"}", MR_Next}, - {"\"name\": \"%rms_name\",$"}, - {"\"run_name\": \"%name\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": %int,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"RMS\",$", MR_Next}, - {"\"rms\": %float$", MR_Next}, - {"}", MR_Next}}); + AddCases( + TC_JSONOut, + {{"\"name\": \"%bigo_name\",$"}, + {"\"family_index\": " + std::to_string(family_index) + ",$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"%name\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": %int,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"BigO\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"cpu_coefficient\": %float,$", MR_Next}, + {"\"real_coefficient\": %float,$", MR_Next}, + {"\"big_o\": \"%bigo\",$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}, + {"\"name\": \"%rms_name\",$"}, + {"\"family_index\": " + std::to_string(family_index) + ",$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"%name\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": %int,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"RMS\",$", MR_Next}, + {"\"aggregate_unit\": \"percentage\",$", MR_Next}, + {"\"rms\": %float$", MR_Next}, + {"}", MR_Next}}); AddCases(TC_CSVOut, {{"^\"%bigo_name\",,%float,%float,%bigo,,,,,$"}, {"^\"%bigo_name\"", MR_Not}, {"^\"%rms_name\",,%float,%float,,,,,,$", MR_Next}}); @@ -56,10 +67,10 @@ int AddComplexityTest(std::string test_name, std::string big_o_test_name, // --------------------------- Testing BigO O(1) --------------------------- // // ========================================================================= // -void BM_Complexity_O1(benchmark::State& state) { +void BM_Complexity_O1(benchmark::State &state) { for (auto _ : state) { for (int i = 0; i < 1024; ++i) { - benchmark::DoNotOptimize(&i); + benchmark::DoNotOptimize(i); } } state.SetComplexityN(state.range(0)); @@ -82,15 +93,15 @@ const char *lambda_big_o_1 = "f\\(N\\)"; // Add enum tests ADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name, - enum_big_o_1); + enum_big_o_1, /*family_index=*/0); // Add auto enum tests ADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name, - auto_big_o_1); + auto_big_o_1, /*family_index=*/1); // Add lambda tests ADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name, - lambda_big_o_1); + lambda_big_o_1, /*family_index=*/2); // ========================================================================= // // --------------------------- Testing BigO O(N) --------------------------- // @@ -98,19 +109,20 @@ ADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name, std::vector ConstructRandomVector(int64_t size) { std::vector v; - v.reserve(static_cast(size)); + v.reserve(static_cast(size)); for (int i = 0; i < size; ++i) { v.push_back(static_cast(std::rand() % size)); } return v; } -void BM_Complexity_O_N(benchmark::State& state) { +void BM_Complexity_O_N(benchmark::State &state) { auto v = ConstructRandomVector(state.range(0)); // Test worst case scenario (item not in vector) const int64_t item_not_in_vector = state.range(0) * 2; for (auto _ : state) { - benchmark::DoNotOptimize(std::find(v.begin(), v.end(), item_not_in_vector)); + auto it = std::find(v.begin(), v.end(), item_not_in_vector); + benchmark::DoNotOptimize(it); } state.SetComplexityN(state.range(0)); } @@ -137,17 +149,17 @@ const char *lambda_big_o_n = "f\\(N\\)"; // Add enum tests ADD_COMPLEXITY_CASES(n_test_name, big_o_n_test_name, rms_o_n_test_name, - enum_auto_big_o_n); + enum_auto_big_o_n, /*family_index=*/3); // Add lambda tests ADD_COMPLEXITY_CASES(n_test_name, big_o_n_test_name, rms_o_n_test_name, - lambda_big_o_n); + lambda_big_o_n, /*family_index=*/4); // ========================================================================= // // ------------------------- Testing BigO O(N*lgN) ------------------------- // // ========================================================================= // -static void BM_Complexity_O_N_log_N(benchmark::State& state) { +static void BM_Complexity_O_N_log_N(benchmark::State &state) { auto v = ConstructRandomVector(state.range(0)); for (auto _ : state) { std::sort(v.begin(), v.end()); @@ -163,7 +175,7 @@ BENCHMARK(BM_Complexity_O_N_log_N) ->RangeMultiplier(2) ->Range(1 << 10, 1 << 16) ->Complexity([](benchmark::IterationCount n) { - return kLog2E * n * log(static_cast(n)); + return kLog2E * static_cast(n) * log(static_cast(n)); }); BENCHMARK(BM_Complexity_O_N_log_N) ->RangeMultiplier(2) @@ -178,18 +190,23 @@ const char *lambda_big_o_n_lg_n = "f\\(N\\)"; // Add enum tests ADD_COMPLEXITY_CASES(n_lg_n_test_name, big_o_n_lg_n_test_name, - rms_o_n_lg_n_test_name, enum_auto_big_o_n_lg_n); + rms_o_n_lg_n_test_name, enum_auto_big_o_n_lg_n, + /*family_index=*/6); // Add lambda tests ADD_COMPLEXITY_CASES(n_lg_n_test_name, big_o_n_lg_n_test_name, - rms_o_n_lg_n_test_name, lambda_big_o_n_lg_n); + rms_o_n_lg_n_test_name, lambda_big_o_n_lg_n, + /*family_index=*/7); // ========================================================================= // // -------- Testing formatting of Complexity with captured args ------------ // // ========================================================================= // -void BM_ComplexityCaptureArgs(benchmark::State& state, int n) { +void BM_ComplexityCaptureArgs(benchmark::State &state, int n) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } state.SetComplexityN(n); } @@ -202,7 +219,7 @@ const std::string complexity_capture_name = "BM_ComplexityCaptureArgs/capture_test"; ADD_COMPLEXITY_CASES(complexity_capture_name, complexity_capture_name + "_BigO", - complexity_capture_name + "_RMS", "N"); + complexity_capture_name + "_RMS", "N", /*family_index=*/9); // ========================================================================= // // --------------------------- TEST CASES END ------------------------------ // diff --git a/thirdparty_builtin/benchmark-1.5.0/test/cxx03_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/cxx03_test.cc similarity index 93% rename from thirdparty_builtin/benchmark-1.5.0/test/cxx03_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/cxx03_test.cc index c4c9a5227..9711c1bd4 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/cxx03_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/cxx03_test.cc @@ -44,8 +44,7 @@ BENCHMARK_TEMPLATE(BM_template1, long); BENCHMARK_TEMPLATE1(BM_template1, int); template -struct BM_Fixture : public ::benchmark::Fixture { -}; +struct BM_Fixture : public ::benchmark::Fixture {}; BENCHMARK_TEMPLATE_F(BM_Fixture, BM_template1, long)(benchmark::State& state) { BM_empty(state); @@ -55,8 +54,8 @@ BENCHMARK_TEMPLATE1_F(BM_Fixture, BM_template2, int)(benchmark::State& state) { } void BM_counters(benchmark::State& state) { - BM_empty(state); - state.counters["Foo"] = 2; + BM_empty(state); + state.counters["Foo"] = 2; } BENCHMARK(BM_counters); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/diagnostics_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/diagnostics_test.cc similarity index 84% rename from thirdparty_builtin/benchmark-1.5.0/test/diagnostics_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/diagnostics_test.cc index dd64a3365..fda14b3d5 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/diagnostics_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/diagnostics_test.cc @@ -26,7 +26,8 @@ void TestHandler() { } void try_invalid_pause_resume(benchmark::State& state) { -#if !defined(TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) && !defined(TEST_HAS_NO_EXCEPTIONS) +#if !defined(TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) && \ + !defined(TEST_HAS_NO_EXCEPTIONS) try { state.PauseTiming(); std::abort(); @@ -48,7 +49,8 @@ void BM_diagnostic_test(benchmark::State& state) { if (called_once == false) try_invalid_pause_resume(state); for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } if (called_once == false) try_invalid_pause_resume(state); @@ -57,14 +59,14 @@ void BM_diagnostic_test(benchmark::State& state) { } BENCHMARK(BM_diagnostic_test); - void BM_diagnostic_test_keep_running(benchmark::State& state) { static bool called_once = false; if (called_once == false) try_invalid_pause_resume(state); - while(state.KeepRunning()) { - benchmark::DoNotOptimize(state.iterations()); + while (state.KeepRunning()) { + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } if (called_once == false) try_invalid_pause_resume(state); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/display_aggregates_only_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/display_aggregates_only_test.cc similarity index 85% rename from thirdparty_builtin/benchmark-1.5.0/test/display_aggregates_only_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/display_aggregates_only_test.cc index 3c36d3f03..6ad65e7f5 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/display_aggregates_only_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/display_aggregates_only_test.cc @@ -19,21 +19,23 @@ BENCHMARK(BM_SummaryRepeat)->Repetitions(3)->DisplayAggregatesOnly(); int main(int argc, char* argv[]) { const std::string output = GetFileReporterOutput(argc, argv); - if (SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3") != 6 || + if (SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3") != 7 || SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3\"") != 3 || SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_mean\"") != 1 || SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_median\"") != 1 || SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"") != - 1) { - std::cout << "Precondition mismatch. Expected to only find 6 " + 1 || + SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_cv\"") != 1) { + std::cout << "Precondition mismatch. Expected to only find 8 " "occurrences of \"BM_SummaryRepeat/repeats:3\" substring:\n" "\"name\": \"BM_SummaryRepeat/repeats:3\", " "\"name\": \"BM_SummaryRepeat/repeats:3\", " "\"name\": \"BM_SummaryRepeat/repeats:3\", " "\"name\": \"BM_SummaryRepeat/repeats:3_mean\", " "\"name\": \"BM_SummaryRepeat/repeats:3_median\", " - "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"\nThe entire " + "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\", " + "\"name\": \"BM_SummaryRepeat/repeats:3_cv\"\nThe entire " "output:\n"; std::cout << output; return 1; diff --git a/thirdparty_builtin/benchmark-1.5.0/test/donotoptimize_assembly_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/donotoptimize_assembly_test.cc similarity index 78% rename from thirdparty_builtin/benchmark-1.5.0/test/donotoptimize_assembly_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/donotoptimize_assembly_test.cc index d4b0bab70..dc286f53e 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/donotoptimize_assembly_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/donotoptimize_assembly_test.cc @@ -3,19 +3,23 @@ #ifdef __clang__ #pragma clang diagnostic ignored "-Wreturn-type" #endif +BENCHMARK_DISABLE_DEPRECATED_WARNING extern "C" { extern int ExternInt; extern int ExternInt2; extern int ExternInt3; +extern int BigArray[2049]; + +const int ConstBigArray[2049]{}; inline int Add42(int x) { return x + 42; } struct NotTriviallyCopyable { NotTriviallyCopyable(); explicit NotTriviallyCopyable(int x) : value(x) {} - NotTriviallyCopyable(NotTriviallyCopyable const&); + NotTriviallyCopyable(NotTriviallyCopyable const &); int value; }; @@ -24,7 +28,14 @@ struct Large { int data[2]; }; +struct ExtraLarge { + int arr[2049]; +}; } + +extern ExtraLarge ExtraLargeObj; +const ExtraLarge ConstExtraLargeObj{}; + // CHECK-LABEL: test_with_rvalue: extern "C" void test_with_rvalue() { benchmark::DoNotOptimize(Add42(0)); @@ -69,6 +80,22 @@ extern "C" void test_with_large_lvalue() { // CHECK: ret } +// CHECK-LABEL: test_with_extra_large_lvalue_with_op: +extern "C" void test_with_extra_large_lvalue_with_op() { + ExtraLargeObj.arr[16] = 42; + benchmark::DoNotOptimize(ExtraLargeObj); + // CHECK: movl $42, ExtraLargeObj+64(%rip) + // CHECK: ret +} + +// CHECK-LABEL: test_with_big_array_with_op +extern "C" void test_with_big_array_with_op() { + BigArray[16] = 42; + benchmark::DoNotOptimize(BigArray); + // CHECK: movl $42, BigArray+64(%rip) + // CHECK: ret +} + // CHECK-LABEL: test_with_non_trivial_lvalue: extern "C" void test_with_non_trivial_lvalue() { NotTriviallyCopyable NTC(ExternInt); @@ -97,6 +124,18 @@ extern "C" void test_with_large_const_lvalue() { // CHECK: ret } +// CHECK-LABEL: test_with_const_extra_large_obj: +extern "C" void test_with_const_extra_large_obj() { + benchmark::DoNotOptimize(ConstExtraLargeObj); + // CHECK: ret +} + +// CHECK-LABEL: test_with_const_big_array +extern "C" void test_with_const_big_array() { + benchmark::DoNotOptimize(ConstBigArray); + // CHECK: ret +} + // CHECK-LABEL: test_with_non_trivial_const_lvalue: extern "C" void test_with_non_trivial_const_lvalue() { const NotTriviallyCopyable Obj(ExternInt); @@ -118,8 +157,7 @@ extern "C" int test_div_by_two(int input) { // CHECK-LABEL: test_inc_integer: extern "C" int test_inc_integer() { int x = 0; - for (int i=0; i < 5; ++i) - benchmark::DoNotOptimize(++x); + for (int i = 0; i < 5; ++i) benchmark::DoNotOptimize(++x); // CHECK: movl $1, [[DEST:.*]] // CHECK: {{(addl \$1,|incl)}} [[DEST]] // CHECK: {{(addl \$1,|incl)}} [[DEST]] @@ -147,7 +185,7 @@ extern "C" void test_pointer_const_lvalue() { // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]]) // CHECK: ret int x = 42; - int * const xp = &x; + int *const xp = &x; benchmark::DoNotOptimize(xp); } diff --git a/thirdparty_builtin/benchmark-1.5.0/test/donotoptimize_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/donotoptimize_test.cc similarity index 61% rename from thirdparty_builtin/benchmark-1.5.0/test/donotoptimize_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/donotoptimize_test.cc index 2ce92d1c7..90d5af35f 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/donotoptimize_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/donotoptimize_test.cc @@ -1,33 +1,43 @@ -#include "benchmark/benchmark.h" - #include +#include "benchmark/benchmark.h" + namespace { #if defined(__GNUC__) -std::uint64_t double_up(const std::uint64_t x) __attribute__((const)); +std::int64_t double_up(const std::int64_t x) __attribute__((const)); #endif -std::uint64_t double_up(const std::uint64_t x) { return x * 2; } -} +std::int64_t double_up(const std::int64_t x) { return x * 2; } +} // namespace // Using DoNotOptimize on types like BitRef seem to cause a lot of problems // with the inline assembly on both GCC and Clang. struct BitRef { int index; - unsigned char &byte; + unsigned char& byte; -public: + public: static BitRef Make() { static unsigned char arr[2] = {}; BitRef b(1, arr[0]); return b; } -private: + + private: BitRef(int i, unsigned char& b) : index(i), byte(b) {} }; int main(int, char*[]) { // this test verifies compilation of DoNotOptimize() for some types + char buffer1[1] = ""; + benchmark::DoNotOptimize(buffer1); + + char buffer2[2] = ""; + benchmark::DoNotOptimize(buffer2); + + char buffer3[3] = ""; + benchmark::DoNotOptimize(buffer3); + char buffer8[8] = ""; benchmark::DoNotOptimize(buffer8); @@ -36,17 +46,19 @@ int main(int, char*[]) { char buffer1024[1024] = ""; benchmark::DoNotOptimize(buffer1024); - benchmark::DoNotOptimize(&buffer1024[0]); + char* bptr = &buffer1024[0]; + benchmark::DoNotOptimize(bptr); int x = 123; benchmark::DoNotOptimize(x); - benchmark::DoNotOptimize(&x); + int* xp = &x; + benchmark::DoNotOptimize(xp); benchmark::DoNotOptimize(x += 42); - benchmark::DoNotOptimize(double_up(x)); + std::int64_t y = double_up(x); + benchmark::DoNotOptimize(y); // These tests are to e - benchmark::DoNotOptimize(BitRef::Make()); BitRef lval = BitRef::Make(); benchmark::DoNotOptimize(lval); } diff --git a/thirdparty_builtin/benchmark-1.5.0/test/filter_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/filter_test.cc similarity index 60% rename from thirdparty_builtin/benchmark-1.5.0/test/filter_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/filter_test.cc index 0e27065c1..4c8b8ea48 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/filter_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/filter_test.cc @@ -1,36 +1,40 @@ -#include "benchmark/benchmark.h" - +#include #include #include #include #include - #include #include #include #include +#include "benchmark/benchmark.h" + namespace { class TestReporter : public benchmark::ConsoleReporter { public: - virtual bool ReportContext(const Context& context) { + bool ReportContext(const Context& context) override { return ConsoleReporter::ReportContext(context); }; - virtual void ReportRuns(const std::vector& report) { + void ReportRuns(const std::vector& report) override { ++count_; + max_family_index_ = std::max(max_family_index_, report[0].family_index); ConsoleReporter::ReportRuns(report); }; - TestReporter() : count_(0) {} + TestReporter() : count_(0), max_family_index_(0) {} - virtual ~TestReporter() {} + ~TestReporter() override {} - size_t GetCount() const { return count_; } + int GetCount() const { return count_; } + + int64_t GetMaxFamilyIndex() const { return max_family_index_; } private: - mutable size_t count_; + mutable int count_; + mutable int64_t max_family_index_; }; } // end namespace @@ -65,7 +69,7 @@ static void BM_FooBa(benchmark::State& state) { } BENCHMARK(BM_FooBa); -int main(int argc, char **argv) { +int main(int argc, char** argv) { bool list_only = false; for (int i = 0; i < argc; ++i) list_only |= std::string(argv[i]).find("--benchmark_list_tests") != @@ -74,13 +78,13 @@ int main(int argc, char **argv) { benchmark::Initialize(&argc, argv); TestReporter test_reporter; - const size_t returned_count = - benchmark::RunSpecifiedBenchmarks(&test_reporter); + const int64_t returned_count = + static_cast(benchmark::RunSpecifiedBenchmarks(&test_reporter)); if (argc == 2) { // Make sure we ran all of the tests std::stringstream ss(argv[1]); - size_t expected_return; + int64_t expected_return; ss >> expected_return; if (returned_count != expected_return) { @@ -90,14 +94,23 @@ int main(int argc, char **argv) { return -1; } - const size_t expected_reports = list_only ? 0 : expected_return; - const size_t reports_count = test_reporter.GetCount(); + const int64_t expected_reports = list_only ? 0 : expected_return; + const int64_t reports_count = test_reporter.GetCount(); if (reports_count != expected_reports) { std::cerr << "ERROR: Expected " << expected_reports << " tests to be run but reported_count = " << reports_count << std::endl; return -1; } + + const int64_t max_family_index = test_reporter.GetMaxFamilyIndex(); + const int64_t num_families = reports_count == 0 ? 0 : 1 + max_family_index; + if (num_families != expected_reports) { + std::cerr << "ERROR: Expected " << expected_reports + << " test families to be run but num_families = " + << num_families << std::endl; + return -1; + } } return 0; diff --git a/thirdparty_builtin/benchmark-1.8.0/test/fixture_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/fixture_test.cc new file mode 100644 index 000000000..d1093ebf5 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/fixture_test.cc @@ -0,0 +1,51 @@ + +#include +#include + +#include "benchmark/benchmark.h" + +#define FIXTURE_BECHMARK_NAME MyFixture + +class FIXTURE_BECHMARK_NAME : public ::benchmark::Fixture { + public: + void SetUp(const ::benchmark::State& state) override { + if (state.thread_index() == 0) { + assert(data.get() == nullptr); + data.reset(new int(42)); + } + } + + void TearDown(const ::benchmark::State& state) override { + if (state.thread_index() == 0) { + assert(data.get() != nullptr); + data.reset(); + } + } + + ~FIXTURE_BECHMARK_NAME() override { assert(data == nullptr); } + + std::unique_ptr data; +}; + +BENCHMARK_F(FIXTURE_BECHMARK_NAME, Foo)(benchmark::State& st) { + assert(data.get() != nullptr); + assert(*data == 42); + for (auto _ : st) { + } +} + +BENCHMARK_DEFINE_F(FIXTURE_BECHMARK_NAME, Bar)(benchmark::State& st) { + if (st.thread_index() == 0) { + assert(data.get() != nullptr); + assert(*data == 42); + } + for (auto _ : st) { + assert(data.get() != nullptr); + assert(*data == 42); + } + st.SetItemsProcessed(st.range(0)); +} +BENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, Bar)->Arg(42); +BENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, Bar)->Arg(42)->ThreadPerCpu(); + +BENCHMARK_MAIN(); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/internal_threading_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/internal_threading_test.cc similarity index 99% rename from thirdparty_builtin/benchmark-1.5.0/test/internal_threading_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/internal_threading_test.cc index 039d7c14a..62b5b955a 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/internal_threading_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/internal_threading_test.cc @@ -3,6 +3,7 @@ #include #include + #include "../src/timers.h" #include "benchmark/benchmark.h" #include "output_test.h" diff --git a/thirdparty_builtin/benchmark-1.5.0/test/link_main_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/link_main_test.cc similarity index 60% rename from thirdparty_builtin/benchmark-1.5.0/test/link_main_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/link_main_test.cc index 241ad5c39..e806500a9 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/link_main_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/link_main_test.cc @@ -2,7 +2,8 @@ void BM_empty(benchmark::State& state) { for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } } BENCHMARK(BM_empty); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/map_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/map_test.cc similarity index 81% rename from thirdparty_builtin/benchmark-1.5.0/test/map_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/map_test.cc index dbf7982a3..0fdba7c87 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/map_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/map_test.cc @@ -1,8 +1,8 @@ -#include "benchmark/benchmark.h" - #include #include +#include "benchmark/benchmark.h" + namespace { std::map ConstructRandomMap(int size) { @@ -24,7 +24,8 @@ static void BM_MapLookup(benchmark::State& state) { m = ConstructRandomMap(size); state.ResumeTiming(); for (int i = 0; i < size; ++i) { - benchmark::DoNotOptimize(m.find(std::rand() % size)); + auto it = m.find(std::rand() % size); + benchmark::DoNotOptimize(it); } } state.SetItemsProcessed(state.iterations() * size); @@ -34,11 +35,11 @@ BENCHMARK(BM_MapLookup)->Range(1 << 3, 1 << 12); // Using fixtures. class MapFixture : public ::benchmark::Fixture { public: - void SetUp(const ::benchmark::State& st) { + void SetUp(const ::benchmark::State& st) override { m = ConstructRandomMap(static_cast(st.range(0))); } - void TearDown(const ::benchmark::State&) { m.clear(); } + void TearDown(const ::benchmark::State&) override { m.clear(); } std::map m; }; @@ -47,7 +48,8 @@ BENCHMARK_DEFINE_F(MapFixture, Lookup)(benchmark::State& state) { const int size = static_cast(state.range(0)); for (auto _ : state) { for (int i = 0; i < size; ++i) { - benchmark::DoNotOptimize(m.find(std::rand() % size)); + auto it = m.find(std::rand() % size); + benchmark::DoNotOptimize(it); } } state.SetItemsProcessed(state.iterations() * size); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/memory_manager_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/memory_manager_test.cc similarity index 76% rename from thirdparty_builtin/benchmark-1.5.0/test/memory_manager_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/memory_manager_test.cc index 90bed16cf..d94bd5161 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/memory_manager_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/memory_manager_test.cc @@ -5,25 +5,28 @@ #include "output_test.h" class TestMemoryManager : public benchmark::MemoryManager { - void Start() {} - void Stop(Result* result) { - result->num_allocs = 42; - result->max_bytes_used = 42000; + void Start() override {} + void Stop(Result& result) override { + result.num_allocs = 42; + result.max_bytes_used = 42000; } }; void BM_empty(benchmark::State& state) { for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } } BENCHMARK(BM_empty); ADD_CASES(TC_ConsoleOut, {{"^BM_empty %console_report$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_empty\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_empty\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, diff --git a/thirdparty_builtin/benchmark-1.8.0/test/min_time_parse_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/min_time_parse_gtest.cc new file mode 100644 index 000000000..e2bdf6785 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/min_time_parse_gtest.cc @@ -0,0 +1,30 @@ +#include "../src/benchmark_runner.h" +#include "gtest/gtest.h" + +namespace { + +TEST(ParseMinTimeTest, InvalidInput) { +#if GTEST_HAS_DEATH_TEST + // Tests only runnable in debug mode (when BM_CHECK is enabled). +#ifndef NDEBUG +#ifndef TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS + ASSERT_DEATH_IF_SUPPORTED( + { benchmark::internal::ParseBenchMinTime("abc"); }, + "Malformed seconds value passed to --benchmark_min_time: `abc`"); + + ASSERT_DEATH_IF_SUPPORTED( + { benchmark::internal::ParseBenchMinTime("123ms"); }, + "Malformed seconds value passed to --benchmark_min_time: `123ms`"); + + ASSERT_DEATH_IF_SUPPORTED( + { benchmark::internal::ParseBenchMinTime("1z"); }, + "Malformed seconds value passed to --benchmark_min_time: `1z`"); + + ASSERT_DEATH_IF_SUPPORTED( + { benchmark::internal::ParseBenchMinTime("1hs"); }, + "Malformed seconds value passed to --benchmark_min_time: `1hs`"); +#endif +#endif +#endif +} +} // namespace diff --git a/thirdparty_builtin/benchmark-1.5.0/test/multiple_ranges_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/multiple_ranges_test.cc similarity index 93% rename from thirdparty_builtin/benchmark-1.5.0/test/multiple_ranges_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/multiple_ranges_test.cc index b25f40eb5..5300a9603 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/multiple_ranges_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/multiple_ranges_test.cc @@ -1,10 +1,10 @@ -#include "benchmark/benchmark.h" - #include #include #include #include +#include "benchmark/benchmark.h" + class MultipleRangesFixture : public ::benchmark::Fixture { public: MultipleRangesFixture() @@ -28,7 +28,7 @@ class MultipleRangesFixture : public ::benchmark::Fixture { {2, 7, 15}, {7, 6, 3}}) {} - void SetUp(const ::benchmark::State& state) { + void SetUp(const ::benchmark::State& state) override { std::vector ranges = {state.range(0), state.range(1), state.range(2)}; @@ -39,10 +39,10 @@ class MultipleRangesFixture : public ::benchmark::Fixture { // NOTE: This is not TearDown as we want to check after _all_ runs are // complete. - virtual ~MultipleRangesFixture() { + ~MultipleRangesFixture() override { if (actualValues != expectedValues) { std::cout << "EXPECTED\n"; - for (auto v : expectedValues) { + for (const auto& v : expectedValues) { std::cout << "{"; for (int64_t iv : v) { std::cout << iv << ", "; @@ -50,7 +50,7 @@ class MultipleRangesFixture : public ::benchmark::Fixture { std::cout << "}\n"; } std::cout << "ACTUAL\n"; - for (auto v : actualValues) { + for (const auto& v : actualValues) { std::cout << "{"; for (int64_t iv : v) { std::cout << iv << ", "; diff --git a/thirdparty_builtin/benchmark-1.5.0/test/options_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/options_test.cc similarity index 91% rename from thirdparty_builtin/benchmark-1.5.0/test/options_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/options_test.cc index 7bfc23546..a1b209f3e 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/options_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/options_test.cc @@ -1,7 +1,8 @@ -#include "benchmark/benchmark.h" #include #include +#include "benchmark/benchmark.h" + #if defined(NDEBUG) #undef NDEBUG #endif @@ -25,12 +26,15 @@ BENCHMARK(BM_basic)->Arg(42); BENCHMARK(BM_basic_slow)->Arg(10)->Unit(benchmark::kNanosecond); BENCHMARK(BM_basic_slow)->Arg(100)->Unit(benchmark::kMicrosecond); BENCHMARK(BM_basic_slow)->Arg(1000)->Unit(benchmark::kMillisecond); +BENCHMARK(BM_basic_slow)->Arg(1000)->Unit(benchmark::kSecond); BENCHMARK(BM_basic)->Range(1, 8); BENCHMARK(BM_basic)->RangeMultiplier(2)->Range(1, 8); BENCHMARK(BM_basic)->DenseRange(10, 15); BENCHMARK(BM_basic)->Args({42, 42}); BENCHMARK(BM_basic)->Ranges({{64, 512}, {64, 512}}); BENCHMARK(BM_basic)->MinTime(0.7); +BENCHMARK(BM_basic)->MinWarmUpTime(0.8); +BENCHMARK(BM_basic)->MinTime(0.1)->MinWarmUpTime(0.2); BENCHMARK(BM_basic)->UseRealTime(); BENCHMARK(BM_basic)->ThreadRange(2, 4); BENCHMARK(BM_basic)->ThreadPerCpu(); @@ -63,12 +67,10 @@ void BM_explicit_iteration_count(benchmark::State& state) { // Test that the requested iteration count is respected. assert(state.max_iterations == 42); - size_t actual_iterations = 0; - for (auto _ : state) - ++actual_iterations; + for (auto _ : state) { + } assert(state.iterations() == state.max_iterations); assert(state.iterations() == 42); - } BENCHMARK(BM_explicit_iteration_count)->Iterations(42); diff --git a/thirdparty_builtin/benchmark-1.5.0/test/output_test.h b/thirdparty_builtin/benchmark-1.8.0/test/output_test.h similarity index 85% rename from thirdparty_builtin/benchmark-1.5.0/test/output_test.h rename to thirdparty_builtin/benchmark-1.8.0/test/output_test.h index 9385761b2..c08fe1d87 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/output_test.h +++ b/thirdparty_builtin/benchmark-1.8.0/test/output_test.h @@ -85,7 +85,7 @@ std::string GetFileReporterOutput(int argc, char* argv[]); struct Results; typedef std::function ResultsCheckFn; -size_t AddChecker(const char* bm_name_pattern, ResultsCheckFn fn); +size_t AddChecker(const std::string& bm_name_pattern, const ResultsCheckFn& fn); // Class holding the results of a benchmark. // It is passed in calls to checker functions. @@ -113,13 +113,11 @@ struct Results { return NumIterations() * GetTime(kRealTime); } // get the cpu_time duration of the benchmark in seconds - double DurationCPUTime() const { - return NumIterations() * GetTime(kCpuTime); - } + double DurationCPUTime() const { return NumIterations() * GetTime(kCpuTime); } // get the string for a result by name, or nullptr if the name // is not found - const std::string* Get(const char* entry_name) const { + const std::string* Get(const std::string& entry_name) const { auto it = values.find(entry_name); if (it == values.end()) return nullptr; return &it->second; @@ -128,12 +126,12 @@ struct Results { // get a result by name, parsed as a specific type. // NOTE: for counters, use GetCounterAs instead. template - T GetAs(const char* entry_name) const; + T GetAs(const std::string& entry_name) const; // counters are written as doubles, so they have to be read first // as a double, and only then converted to the asked type. template - T GetCounterAs(const char* entry_name) const { + T GetCounterAs(const std::string& entry_name) const { double dval = GetAs(entry_name); T tval = static_cast(dval); return tval; @@ -141,14 +139,14 @@ struct Results { }; template -T Results::GetAs(const char* entry_name) const { +T Results::GetAs(const std::string& entry_name) const { auto* sv = Get(entry_name); - CHECK(sv != nullptr && !sv->empty()); + BM_CHECK(sv != nullptr && !sv->empty()); std::stringstream ss; ss << *sv; T out; ss >> out; - CHECK(!ss.fail()); + BM_CHECK(!ss.fail()); return out; } @@ -158,8 +156,8 @@ T Results::GetAs(const char* entry_name) const { // clang-format off -#define _CHECK_RESULT_VALUE(entry, getfn, var_type, var_name, relationship, value) \ - CONCAT(CHECK_, relationship) \ +#define CHECK_RESULT_VALUE_IMPL(entry, getfn, var_type, var_name, relationship, value) \ + CONCAT(BM_CHECK_, relationship) \ (entry.getfn< var_type >(var_name), (value)) << "\n" \ << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ << __FILE__ << ":" << __LINE__ << ": " \ @@ -169,8 +167,8 @@ T Results::GetAs(const char* entry_name) const { // check with tolerance. eps_factor is the tolerance window, which is // interpreted relative to value (eg, 0.1 means 10% of value). -#define _CHECK_FLOAT_RESULT_VALUE(entry, getfn, var_type, var_name, relationship, value, eps_factor) \ - CONCAT(CHECK_FLOAT_, relationship) \ +#define CHECK_FLOAT_RESULT_VALUE_IMPL(entry, getfn, var_type, var_name, relationship, value, eps_factor) \ + CONCAT(BM_CHECK_FLOAT_, relationship) \ (entry.getfn< var_type >(var_name), (value), (eps_factor) * (value)) << "\n" \ << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ << __FILE__ << ":" << __LINE__ << ": " \ @@ -187,16 +185,16 @@ T Results::GetAs(const char* entry_name) const { << "%)" #define CHECK_RESULT_VALUE(entry, var_type, var_name, relationship, value) \ - _CHECK_RESULT_VALUE(entry, GetAs, var_type, var_name, relationship, value) + CHECK_RESULT_VALUE_IMPL(entry, GetAs, var_type, var_name, relationship, value) #define CHECK_COUNTER_VALUE(entry, var_type, var_name, relationship, value) \ - _CHECK_RESULT_VALUE(entry, GetCounterAs, var_type, var_name, relationship, value) + CHECK_RESULT_VALUE_IMPL(entry, GetCounterAs, var_type, var_name, relationship, value) #define CHECK_FLOAT_RESULT_VALUE(entry, var_name, relationship, value, eps_factor) \ - _CHECK_FLOAT_RESULT_VALUE(entry, GetAs, double, var_name, relationship, value, eps_factor) + CHECK_FLOAT_RESULT_VALUE_IMPL(entry, GetAs, double, var_name, relationship, value, eps_factor) #define CHECK_FLOAT_COUNTER_VALUE(entry, var_name, relationship, value, eps_factor) \ - _CHECK_FLOAT_RESULT_VALUE(entry, GetCounterAs, double, var_name, relationship, value, eps_factor) + CHECK_FLOAT_RESULT_VALUE_IMPL(entry, GetCounterAs, double, var_name, relationship, value, eps_factor) // clang-format on diff --git a/thirdparty_builtin/benchmark-1.5.0/test/output_test_helper.cc b/thirdparty_builtin/benchmark-1.8.0/test/output_test_helper.cc similarity index 81% rename from thirdparty_builtin/benchmark-1.5.0/test/output_test_helper.cc rename to thirdparty_builtin/benchmark-1.8.0/test/output_test_helper.cc index 5dc951d2b..241af5c91 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/output_test_helper.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/output_test_helper.cc @@ -10,6 +10,7 @@ #include "../src/benchmark_api_internal.h" #include "../src/check.h" // NOTE: check.h is for internal use only! +#include "../src/log.h" // NOTE: log.h is for internal use only #include "../src/re.h" // NOTE: re.h is for internal use only #include "output_test.h" @@ -40,14 +41,20 @@ SubMap& GetSubstitutions() { // clang-format off static std::string safe_dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"; static std::string time_re = "([0-9]+[.])?[0-9]+"; + static std::string percentage_re = "[0-9]+[.][0-9]{2}"; static SubMap map = { {"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"}, // human-readable float {"%hrfloat", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?[kMGTPEZYmunpfazy]?"}, + {"%percentage", percentage_re}, {"%int", "[ ]*[0-9]+"}, {" %s ", "[ ]+"}, {"%time", "[ ]*" + time_re + "[ ]+ns"}, {"%console_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns [ ]*[0-9]+"}, + {"%console_percentage_report", "[ ]*" + percentage_re + "[ ]+% [ ]*" + percentage_re + "[ ]+% [ ]*[0-9]+"}, + {"%console_us_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us [ ]*[0-9]+"}, + {"%console_ms_report", "[ ]*" + time_re + "[ ]+ms [ ]*" + time_re + "[ ]+ms [ ]*[0-9]+"}, + {"%console_s_report", "[ ]*" + time_re + "[ ]+s [ ]*" + time_re + "[ ]+s [ ]*[0-9]+"}, {"%console_time_only_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns"}, {"%console_us_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us [ ]*[0-9]+"}, {"%console_us_time_only_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us"}, @@ -56,6 +63,8 @@ SubMap& GetSubstitutions() { "items_per_second,label,error_occurred,error_message"}, {"%csv_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,,,"}, {"%csv_us_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",us,,,,,"}, + {"%csv_ms_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ms,,,,,"}, + {"%csv_s_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",s,,,,,"}, {"%csv_bytes_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + ",,,,"}, {"%csv_items_report", @@ -89,27 +98,27 @@ void CheckCase(std::stringstream& remaining_output, TestCase const& TC, bool on_first = true; std::string line; while (remaining_output.eof() == false) { - CHECK(remaining_output.good()); + BM_CHECK(remaining_output.good()); std::getline(remaining_output, line); if (on_first) { first_line = line; on_first = false; } for (const auto& NC : not_checks) { - CHECK(!NC.regex->Match(line)) + BM_CHECK(!NC.regex->Match(line)) << "Unexpected match for line \"" << line << "\" for MR_Not regex \"" << NC.regex_str << "\"" << "\n actual regex string \"" << TC.substituted_regex << "\"" << "\n started matching near: " << first_line; } if (TC.regex->Match(line)) return; - CHECK(TC.match_rule != MR_Next) + BM_CHECK(TC.match_rule != MR_Next) << "Expected line \"" << line << "\" to match regex \"" << TC.regex_str << "\"" << "\n actual regex string \"" << TC.substituted_regex << "\"" << "\n started matching near: " << first_line; } - CHECK(remaining_output.eof() == false) + BM_CHECK(remaining_output.eof() == false) << "End of output reached before match for regex \"" << TC.regex_str << "\" was found" << "\n actual regex string \"" << TC.substituted_regex << "\"" @@ -132,14 +141,14 @@ void CheckCases(TestCaseList const& checks, std::stringstream& output) { class TestReporter : public benchmark::BenchmarkReporter { public: TestReporter(std::vector reps) - : reporters_(reps) {} + : reporters_(std::move(reps)) {} - virtual bool ReportContext(const Context& context) { + bool ReportContext(const Context& context) override { bool last_ret = false; bool first = true; for (auto rep : reporters_) { bool new_ret = rep->ReportContext(context); - CHECK(first || new_ret == last_ret) + BM_CHECK(first || new_ret == last_ret) << "Reports return different values for ReportContext"; first = false; last_ret = new_ret; @@ -148,10 +157,10 @@ class TestReporter : public benchmark::BenchmarkReporter { return last_ret; } - void ReportRuns(const std::vector& report) { + void ReportRuns(const std::vector& report) override { for (auto rep : reporters_) rep->ReportRuns(report); } - void Finalize() { + void Finalize() override { for (auto rep : reporters_) rep->Finalize(); } @@ -174,7 +183,7 @@ class ResultsChecker { public: struct PatternAndFn : public TestCase { // reusing TestCase for its regexes PatternAndFn(const std::string& rx, ResultsCheckFn fn_) - : TestCase(rx), fn(fn_) {} + : TestCase(rx), fn(std::move(fn_)) {} ResultsCheckFn fn; }; @@ -182,7 +191,7 @@ class ResultsChecker { std::vector results; std::vector field_names; - void Add(const std::string& entry_pattern, ResultsCheckFn fn); + void Add(const std::string& entry_pattern, const ResultsCheckFn& fn); void CheckResults(std::stringstream& output); @@ -201,7 +210,8 @@ ResultsChecker& GetResultsChecker() { } // add a results checker for a benchmark -void ResultsChecker::Add(const std::string& entry_pattern, ResultsCheckFn fn) { +void ResultsChecker::Add(const std::string& entry_pattern, + const ResultsCheckFn& fn) { check_patterns.emplace_back(entry_pattern, fn); } @@ -221,7 +231,7 @@ void ResultsChecker::CheckResults(std::stringstream& output) { std::string line; bool on_first = true; while (output.eof() == false) { - CHECK(output.good()); + BM_CHECK(output.good()); std::getline(output, line); if (on_first) { SetHeader_(line); // this is important @@ -232,18 +242,17 @@ void ResultsChecker::CheckResults(std::stringstream& output) { } // finally we can call the subscribed check functions for (const auto& p : check_patterns) { - VLOG(2) << "--------------------------------\n"; - VLOG(2) << "checking for benchmarks matching " << p.regex_str << "...\n"; + BM_VLOG(2) << "--------------------------------\n"; + BM_VLOG(2) << "checking for benchmarks matching " << p.regex_str << "...\n"; for (const auto& r : results) { if (!p.regex->Match(r.name)) { - VLOG(2) << p.regex_str << " is not matched by " << r.name << "\n"; + BM_VLOG(2) << p.regex_str << " is not matched by " << r.name << "\n"; continue; - } else { - VLOG(2) << p.regex_str << " is matched by " << r.name << "\n"; } - VLOG(1) << "Checking results of " << r.name << ": ... \n"; + BM_VLOG(2) << p.regex_str << " is matched by " << r.name << "\n"; + BM_VLOG(1) << "Checking results of " << r.name << ": ... \n"; p.fn(r); - VLOG(1) << "Checking results of " << r.name << ": OK.\n"; + BM_VLOG(1) << "Checking results of " << r.name << ": OK.\n"; } } } @@ -256,9 +265,9 @@ void ResultsChecker::SetHeader_(const std::string& csv_header) { // set the values for a benchmark void ResultsChecker::SetValues_(const std::string& entry_csv_line) { if (entry_csv_line.empty()) return; // some lines are empty - CHECK(!field_names.empty()); + BM_CHECK(!field_names.empty()); auto vals = SplitCsv_(entry_csv_line); - CHECK_EQ(vals.size(), field_names.size()); + BM_CHECK_EQ(vals.size(), field_names.size()); results.emplace_back(vals[0]); // vals[0] is the benchmark name auto& entry = results.back(); for (size_t i = 1, e = vals.size(); i < e; ++i) { @@ -273,7 +282,7 @@ std::vector ResultsChecker::SplitCsv_(const std::string& line) { if (!field_names.empty()) out.reserve(field_names.size()); size_t prev = 0, pos = line.find_first_of(','), curr = pos; while (pos != line.npos) { - CHECK(curr > 0); + BM_CHECK(curr > 0); if (line[prev] == '"') ++prev; if (line[curr - 1] == '"') --curr; out.push_back(line.substr(prev, curr - prev)); @@ -290,7 +299,7 @@ std::vector ResultsChecker::SplitCsv_(const std::string& line) { } // end namespace internal -size_t AddChecker(const char* bm_name, ResultsCheckFn fn) { +size_t AddChecker(const std::string& bm_name, const ResultsCheckFn& fn) { auto& rc = internal::GetResultsChecker(); rc.Add(bm_name, fn); return rc.results.size(); @@ -304,32 +313,32 @@ int Results::NumThreads() const { ss << name.substr(pos + 9, end); int num = 1; ss >> num; - CHECK(!ss.fail()); + BM_CHECK(!ss.fail()); return num; } -double Results::NumIterations() const { - return GetAs("iterations"); -} +double Results::NumIterations() const { return GetAs("iterations"); } double Results::GetTime(BenchmarkTime which) const { - CHECK(which == kCpuTime || which == kRealTime); + BM_CHECK(which == kCpuTime || which == kRealTime); const char* which_str = which == kCpuTime ? "cpu_time" : "real_time"; double val = GetAs(which_str); auto unit = Get("time_unit"); - CHECK(unit); + BM_CHECK(unit); if (*unit == "ns") { return val * 1.e-9; - } else if (*unit == "us") { + } + if (*unit == "us") { return val * 1.e-6; - } else if (*unit == "ms") { + } + if (*unit == "ms") { return val * 1.e-3; - } else if (*unit == "s") { + } + if (*unit == "s") { return val; - } else { - CHECK(1 == 0) << "unknown time unit: " << *unit; - return 0; } + BM_CHECK(1 == 0) << "unknown time unit: " << *unit; + return 0; } // ========================================================================= // @@ -343,10 +352,10 @@ TestCase::TestCase(std::string re, int rule) regex(std::make_shared()) { std::string err_str; regex->Init(substituted_regex, &err_str); - CHECK(err_str.empty()) << "Could not construct regex \"" << substituted_regex - << "\"" - << "\n originally \"" << regex_str << "\"" - << "\n got error: " << err_str; + BM_CHECK(err_str.empty()) + << "Could not construct regex \"" << substituted_regex << "\"" + << "\n originally \"" << regex_str << "\"" + << "\n got error: " << err_str; } int AddCases(TestCaseID ID, std::initializer_list il) { @@ -373,6 +382,10 @@ int SetSubstitutions( return 0; } +// Disable deprecated warnings temporarily because we need to reference +// CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations +BENCHMARK_DISABLE_DEPRECATED_WARNING + void RunOutputTests(int argc, char* argv[]) { using internal::GetTestCaseList; benchmark::Initialize(&argc, argv); @@ -381,14 +394,14 @@ void RunOutputTests(int argc, char* argv[]) { benchmark::JSONReporter JR; benchmark::CSVReporter CSVR; struct ReporterTest { - const char* name; + std::string name; std::vector& output_cases; std::vector& error_cases; benchmark::BenchmarkReporter& reporter; std::stringstream out_stream; std::stringstream err_stream; - ReporterTest(const char* n, std::vector& out_tc, + ReporterTest(const std::string& n, std::vector& out_tc, std::vector& err_tc, benchmark::BenchmarkReporter& br) : name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) { @@ -396,12 +409,12 @@ void RunOutputTests(int argc, char* argv[]) { reporter.SetErrorStream(&err_stream); } } TestCases[] = { - {"ConsoleReporter", GetTestCaseList(TC_ConsoleOut), + {std::string("ConsoleReporter"), GetTestCaseList(TC_ConsoleOut), GetTestCaseList(TC_ConsoleErr), CR}, - {"JSONReporter", GetTestCaseList(TC_JSONOut), GetTestCaseList(TC_JSONErr), - JR}, - {"CSVReporter", GetTestCaseList(TC_CSVOut), GetTestCaseList(TC_CSVErr), - CSVR}, + {std::string("JSONReporter"), GetTestCaseList(TC_JSONOut), + GetTestCaseList(TC_JSONErr), JR}, + {std::string("CSVReporter"), GetTestCaseList(TC_CSVOut), + GetTestCaseList(TC_CSVErr), CSVR}, }; // Create the test reporter and run the benchmarks. @@ -410,7 +423,8 @@ void RunOutputTests(int argc, char* argv[]) { benchmark::RunSpecifiedBenchmarks(&test_rep); for (auto& rep_test : TestCases) { - std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n"; + std::string msg = + std::string("\nTesting ") + rep_test.name + std::string(" Output\n"); std::string banner(msg.size() - 1, '-'); std::cout << banner << msg << banner << "\n"; @@ -427,10 +441,12 @@ void RunOutputTests(int argc, char* argv[]) { // the checks to subscribees. auto& csv = TestCases[2]; // would use == but gcc spits a warning - CHECK(std::strcmp(csv.name, "CSVReporter") == 0); + BM_CHECK(csv.name == std::string("CSVReporter")); internal::GetResultsChecker().CheckResults(csv.out_stream); } +BENCHMARK_RESTORE_DEPRECATED_WARNING + int SubstrCnt(const std::string& haystack, const std::string& pat) { if (pat.length() == 0) return 0; int count = 0; @@ -453,9 +469,8 @@ static char RandomHexChar() { static std::string GetRandomFileName() { std::string model = "test.%%%%%%"; - for (auto & ch : model) { - if (ch == '%') - ch = RandomHexChar(); + for (auto& ch : model) { + if (ch == '%') ch = RandomHexChar(); } return model; } @@ -472,8 +487,7 @@ static std::string GetTempFileName() { int retries = 3; while (--retries) { std::string name = GetRandomFileName(); - if (!FileExists(name)) - return name; + if (!FileExists(name)) return name; } std::cerr << "Failed to create unique temporary file name" << std::endl; std::abort(); diff --git a/thirdparty_builtin/benchmark-1.8.0/test/perf_counters_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/perf_counters_gtest.cc new file mode 100644 index 000000000..e73ebc588 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/perf_counters_gtest.cc @@ -0,0 +1,316 @@ +#include +#include + +#include "../src/perf_counters.h" +#include "gtest/gtest.h" + +#ifndef GTEST_SKIP +struct MsgHandler { + void operator=(std::ostream&) {} +}; +#define GTEST_SKIP() return MsgHandler() = std::cout +#endif + +using benchmark::internal::PerfCounters; +using benchmark::internal::PerfCountersMeasurement; +using benchmark::internal::PerfCounterValues; + +namespace { +const char kGenericPerfEvent1[] = "CYCLES"; +const char kGenericPerfEvent2[] = "BRANCHES"; +const char kGenericPerfEvent3[] = "INSTRUCTIONS"; + +TEST(PerfCountersTest, Init) { + EXPECT_EQ(PerfCounters::Initialize(), PerfCounters::kSupported); +} + +TEST(PerfCountersTest, OneCounter) { + if (!PerfCounters::kSupported) { + GTEST_SKIP() << "Performance counters not supported.\n"; + } + EXPECT_TRUE(PerfCounters::Initialize()); + EXPECT_EQ(PerfCounters::Create({kGenericPerfEvent1}).num_counters(), 1); +} + +TEST(PerfCountersTest, NegativeTest) { + if (!PerfCounters::kSupported) { + EXPECT_FALSE(PerfCounters::Initialize()); + return; + } + EXPECT_TRUE(PerfCounters::Initialize()); + // Sanity checks + // Create() will always create a valid object, even if passed no or + // wrong arguments as the new behavior is to warn and drop unsupported + // counters + EXPECT_EQ(PerfCounters::Create({}).num_counters(), 0); + EXPECT_EQ(PerfCounters::Create({""}).num_counters(), 0); + EXPECT_EQ(PerfCounters::Create({"not a counter name"}).num_counters(), 0); + { + // Try sneaking in a bad egg to see if it is filtered out. The + // number of counters has to be two, not zero + auto counter = + PerfCounters::Create({kGenericPerfEvent2, "", kGenericPerfEvent1}); + EXPECT_EQ(counter.num_counters(), 2); + EXPECT_EQ(counter.names(), std::vector( + {kGenericPerfEvent2, kGenericPerfEvent1})); + } + { + // Try sneaking in an outrageous counter, like a fat finger mistake + auto counter = PerfCounters::Create( + {kGenericPerfEvent3, "not a counter name", kGenericPerfEvent1}); + EXPECT_EQ(counter.num_counters(), 2); + EXPECT_EQ(counter.names(), std::vector( + {kGenericPerfEvent3, kGenericPerfEvent1})); + } + { + // Finally try a golden input - it should like all them + EXPECT_EQ(PerfCounters::Create( + {kGenericPerfEvent1, kGenericPerfEvent2, kGenericPerfEvent3}) + .num_counters(), + 3); + } + { + // Add a bad apple in the end of the chain to check the edges + auto counter = PerfCounters::Create({kGenericPerfEvent1, kGenericPerfEvent2, + kGenericPerfEvent3, + "MISPREDICTED_BRANCH_RETIRED"}); + EXPECT_EQ(counter.num_counters(), 3); + EXPECT_EQ(counter.names(), + std::vector({kGenericPerfEvent1, kGenericPerfEvent2, + kGenericPerfEvent3})); + } +} + +TEST(PerfCountersTest, Read1Counter) { + if (!PerfCounters::kSupported) { + GTEST_SKIP() << "Test skipped because libpfm is not supported.\n"; + } + EXPECT_TRUE(PerfCounters::Initialize()); + auto counters = PerfCounters::Create({kGenericPerfEvent1}); + EXPECT_EQ(counters.num_counters(), 1); + PerfCounterValues values1(1); + EXPECT_TRUE(counters.Snapshot(&values1)); + EXPECT_GT(values1[0], 0); + PerfCounterValues values2(1); + EXPECT_TRUE(counters.Snapshot(&values2)); + EXPECT_GT(values2[0], 0); + EXPECT_GT(values2[0], values1[0]); +} + +TEST(PerfCountersTest, Read2Counters) { + if (!PerfCounters::kSupported) { + GTEST_SKIP() << "Test skipped because libpfm is not supported.\n"; + } + EXPECT_TRUE(PerfCounters::Initialize()); + auto counters = + PerfCounters::Create({kGenericPerfEvent1, kGenericPerfEvent2}); + EXPECT_EQ(counters.num_counters(), 2); + PerfCounterValues values1(2); + EXPECT_TRUE(counters.Snapshot(&values1)); + EXPECT_GT(values1[0], 0); + EXPECT_GT(values1[1], 0); + PerfCounterValues values2(2); + EXPECT_TRUE(counters.Snapshot(&values2)); + EXPECT_GT(values2[0], 0); + EXPECT_GT(values2[1], 0); +} + +TEST(PerfCountersTest, ReopenExistingCounters) { + // This test works in recent and old Intel hardware + // However we cannot make assumptions beyond 3 HW counters + if (!PerfCounters::kSupported) { + GTEST_SKIP() << "Test skipped because libpfm is not supported.\n"; + } + EXPECT_TRUE(PerfCounters::Initialize()); + std::vector kMetrics({kGenericPerfEvent1}); + std::vector counters(3); + for (auto& counter : counters) { + counter = PerfCounters::Create(kMetrics); + } + PerfCounterValues values(1); + EXPECT_TRUE(counters[0].Snapshot(&values)); + EXPECT_TRUE(counters[1].Snapshot(&values)); + EXPECT_TRUE(counters[2].Snapshot(&values)); +} + +TEST(PerfCountersTest, CreateExistingMeasurements) { + // The test works (i.e. causes read to fail) for the assumptions + // about hardware capabilities (i.e. small number (3) hardware + // counters) at this date, + // the same as previous test ReopenExistingCounters. + if (!PerfCounters::kSupported) { + GTEST_SKIP() << "Test skipped because libpfm is not supported.\n"; + } + EXPECT_TRUE(PerfCounters::Initialize()); + + // This means we will try 10 counters but we can only guarantee + // for sure at this time that only 3 will work. Perhaps in the future + // we could use libpfm to query for the hardware limits on this + // particular platform. + const int kMaxCounters = 10; + const int kMinValidCounters = 3; + + // Let's use a ubiquitous counter that is guaranteed to work + // on all platforms + const std::vector kMetrics{"cycles"}; + + // Cannot create a vector of actual objects because the + // copy constructor of PerfCounters is deleted - and so is + // implicitly deleted on PerfCountersMeasurement too + std::vector> + perf_counter_measurements; + + perf_counter_measurements.reserve(kMaxCounters); + for (int j = 0; j < kMaxCounters; ++j) { + perf_counter_measurements.emplace_back( + new PerfCountersMeasurement(kMetrics)); + } + + std::vector> measurements; + + // Start all counters together to see if they hold + int max_counters = kMaxCounters; + for (int i = 0; i < kMaxCounters; ++i) { + auto& counter(*perf_counter_measurements[i]); + EXPECT_EQ(counter.num_counters(), 1); + if (!counter.Start()) { + max_counters = i; + break; + }; + } + + ASSERT_GE(max_counters, kMinValidCounters); + + // Start all together + for (int i = 0; i < max_counters; ++i) { + auto& counter(*perf_counter_measurements[i]); + EXPECT_TRUE(counter.Stop(measurements) || (i >= kMinValidCounters)); + } + + // Start/stop individually + for (int i = 0; i < max_counters; ++i) { + auto& counter(*perf_counter_measurements[i]); + measurements.clear(); + counter.Start(); + EXPECT_TRUE(counter.Stop(measurements) || (i >= kMinValidCounters)); + } +} + +// We try to do some meaningful work here but the compiler +// insists in optimizing away our loop so we had to add a +// no-optimize macro. In case it fails, we added some entropy +// to this pool as well. + +BENCHMARK_DONT_OPTIMIZE size_t do_work() { + static std::mt19937 rd{std::random_device{}()}; + static std::uniform_int_distribution mrand(0, 10); + const size_t kNumLoops = 1000000; + size_t sum = 0; + for (size_t j = 0; j < kNumLoops; ++j) { + sum += mrand(rd); + } + benchmark::DoNotOptimize(sum); + return sum; +} + +void measure(size_t threadcount, PerfCounterValues* before, + PerfCounterValues* after) { + BM_CHECK_NE(before, nullptr); + BM_CHECK_NE(after, nullptr); + std::vector threads(threadcount); + auto work = [&]() { BM_CHECK(do_work() > 1000); }; + + // We need to first set up the counters, then start the threads, so the + // threads would inherit the counters. But later, we need to first destroy + // the thread pool (so all the work finishes), then measure the counters. So + // the scopes overlap, and we need to explicitly control the scope of the + // threadpool. + auto counters = + PerfCounters::Create({kGenericPerfEvent1, kGenericPerfEvent3}); + for (auto& t : threads) t = std::thread(work); + counters.Snapshot(before); + for (auto& t : threads) t.join(); + counters.Snapshot(after); +} + +TEST(PerfCountersTest, MultiThreaded) { + if (!PerfCounters::kSupported) { + GTEST_SKIP() << "Test skipped because libpfm is not supported."; + } + EXPECT_TRUE(PerfCounters::Initialize()); + PerfCounterValues before(2); + PerfCounterValues after(2); + + // Notice that this test will work even if we taskset it to a single CPU + // In this case the threads will run sequentially + // Start two threads and measure the number of combined cycles and + // instructions + measure(2, &before, &after); + std::vector Elapsed2Threads{ + static_cast(after[0] - before[0]), + static_cast(after[1] - before[1])}; + + // Start four threads and measure the number of combined cycles and + // instructions + measure(4, &before, &after); + std::vector Elapsed4Threads{ + static_cast(after[0] - before[0]), + static_cast(after[1] - before[1])}; + + // Some extra work will happen on the main thread - like joining the threads + // - so the ratio won't be quite 2.0, but very close. + EXPECT_GE(Elapsed4Threads[0], 1.9 * Elapsed2Threads[0]); + EXPECT_GE(Elapsed4Threads[1], 1.9 * Elapsed2Threads[1]); +} + +TEST(PerfCountersTest, HardwareLimits) { + // The test works (i.e. causes read to fail) for the assumptions + // about hardware capabilities (i.e. small number (3-4) hardware + // counters) at this date, + // the same as previous test ReopenExistingCounters. + if (!PerfCounters::kSupported) { + GTEST_SKIP() << "Test skipped because libpfm is not supported.\n"; + } + EXPECT_TRUE(PerfCounters::Initialize()); + + // Taken straight from `perf list` on x86-64 + // Got all hardware names since these are the problematic ones + std::vector counter_names{"cycles", // leader + "instructions", + "branches", + "L1-dcache-loads", + "L1-dcache-load-misses", + "L1-dcache-prefetches", + "L1-icache-load-misses", // leader + "L1-icache-loads", + "branch-load-misses", + "branch-loads", + "dTLB-load-misses", + "dTLB-loads", + "iTLB-load-misses", // leader + "iTLB-loads", + "branch-instructions", + "branch-misses", + "cache-misses", + "cache-references", + "stalled-cycles-backend", // leader + "stalled-cycles-frontend"}; + + // In the off-chance that some of these values are not supported, + // we filter them out so the test will complete without failure + // albeit it might not actually test the grouping on that platform + std::vector valid_names; + for (const std::string& name : counter_names) { + if (PerfCounters::IsCounterSupported(name)) { + valid_names.push_back(name); + } + } + PerfCountersMeasurement counter(valid_names); + + std::vector> measurements; + + counter.Start(); + EXPECT_TRUE(counter.Stop(measurements)); +} + +} // namespace diff --git a/thirdparty_builtin/benchmark-1.8.0/test/perf_counters_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/perf_counters_test.cc new file mode 100644 index 000000000..f0e9a1715 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/perf_counters_test.cc @@ -0,0 +1,28 @@ +#undef NDEBUG + +#include "../src/perf_counters.h" + +#include "benchmark/benchmark.h" +#include "output_test.h" + +static void BM_Simple(benchmark::State& state) { + for (auto _ : state) { + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); + } +} +BENCHMARK(BM_Simple); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Simple\",$"}}); + +static void CheckSimple(Results const& e) { + CHECK_COUNTER_VALUE(e, double, "CYCLES", GT, 0); + CHECK_COUNTER_VALUE(e, double, "BRANCHES", GT, 0.0); +} +CHECK_BENCHMARK_RESULTS("BM_Simple", &CheckSimple); + +int main(int argc, char* argv[]) { + if (!benchmark::internal::PerfCounters::kSupported) { + return 0; + } + RunOutputTests(argc, argv); +} diff --git a/thirdparty_builtin/benchmark-1.5.0/test/register_benchmark_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/register_benchmark_test.cc similarity index 82% rename from thirdparty_builtin/benchmark-1.5.0/test/register_benchmark_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/register_benchmark_test.cc index 3ac5b21fb..d69d144a4 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/register_benchmark_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/register_benchmark_test.cc @@ -10,7 +10,7 @@ namespace { class TestReporter : public benchmark::ConsoleReporter { public: - virtual void ReportRuns(const std::vector& report) { + void ReportRuns(const std::vector& report) override { all_runs_.insert(all_runs_.end(), begin(report), end(report)); ConsoleReporter::ReportRuns(report); } @@ -19,24 +19,24 @@ class TestReporter : public benchmark::ConsoleReporter { }; struct TestCase { - std::string name; - const char* label; + const std::string name; + const std::string label; // Note: not explicit as we rely on it being converted through ADD_CASES. - TestCase(const char* xname) : TestCase(xname, nullptr) {} - TestCase(const char* xname, const char* xlabel) + TestCase(const std::string& xname) : TestCase(xname, "") {} + TestCase(const std::string& xname, const std::string& xlabel) : name(xname), label(xlabel) {} typedef benchmark::BenchmarkReporter::Run Run; void CheckRun(Run const& run) const { // clang-format off - CHECK(name == run.benchmark_name()) << "expected " << name << " got " + BM_CHECK(name == run.benchmark_name()) << "expected " << name << " got " << run.benchmark_name(); - if (label) { - CHECK(run.report_label == label) << "expected " << label << " got " + if (!label.empty()) { + BM_CHECK(run.report_label == label) << "expected " << label << " got " << run.report_label; } else { - CHECK(run.report_label == ""); + BM_CHECK(run.report_label.empty()); } // clang-format on } @@ -45,7 +45,7 @@ struct TestCase { std::vector ExpectedResults; int AddCases(std::initializer_list const& v) { - for (auto N : v) { + for (const auto& N : v) { ExpectedResults.push_back(N); } return 0; @@ -95,6 +95,18 @@ ADD_CASES({"test1", "One"}, {"test2", "Two"}, {"test3", "Three"}); #endif // BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK +//----------------------------------------------------------------------------// +// Test RegisterBenchmark with DISABLED_ benchmark +//----------------------------------------------------------------------------// +void DISABLED_BM_function(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(DISABLED_BM_function); +ReturnVal dummy3 = benchmark::RegisterBenchmark("DISABLED_BM_function_manual", + DISABLED_BM_function); +// No need to add cases because we don't expect them to run. + //----------------------------------------------------------------------------// // Test RegisterBenchmark with different callable types //----------------------------------------------------------------------------// @@ -111,7 +123,7 @@ void TestRegistrationAtRuntime() { { CustomFixture fx; benchmark::RegisterBenchmark("custom_fixture", fx); - AddCases({"custom_fixture"}); + AddCases({std::string("custom_fixture")}); } #endif #ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK diff --git a/thirdparty_builtin/benchmark-1.8.0/test/repetitions_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/repetitions_test.cc new file mode 100644 index 000000000..569777d5f --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/repetitions_test.cc @@ -0,0 +1,214 @@ + +#include "benchmark/benchmark.h" +#include "output_test.h" + +// ========================================================================= // +// ------------------------ Testing Basic Output --------------------------- // +// ========================================================================= // + +static void BM_ExplicitRepetitions(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_ExplicitRepetitions)->Repetitions(2); + +ADD_CASES(TC_ConsoleOut, + {{"^BM_ExplicitRepetitions/repeats:2 %console_report$"}}); +ADD_CASES(TC_ConsoleOut, + {{"^BM_ExplicitRepetitions/repeats:2 %console_report$"}}); +ADD_CASES(TC_ConsoleOut, + {{"^BM_ExplicitRepetitions/repeats:2_mean %console_report$"}}); +ADD_CASES(TC_ConsoleOut, + {{"^BM_ExplicitRepetitions/repeats:2_median %console_report$"}}); +ADD_CASES(TC_ConsoleOut, + {{"^BM_ExplicitRepetitions/repeats:2_stddev %console_report$"}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_ExplicitRepetitions/repeats:2\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ExplicitRepetitions/repeats:2\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_ExplicitRepetitions/repeats:2\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ExplicitRepetitions/repeats:2\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"repetition_index\": 1,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_ExplicitRepetitions/repeats:2_mean\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ExplicitRepetitions/repeats:2\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_ExplicitRepetitions/repeats:2_median\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ExplicitRepetitions/repeats:2\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_ExplicitRepetitions/repeats:2_stddev\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ExplicitRepetitions/repeats:2\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_ExplicitRepetitions/repeats:2\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_ExplicitRepetitions/repeats:2\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_ExplicitRepetitions/repeats:2_mean\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_ExplicitRepetitions/repeats:2_median\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_ExplicitRepetitions/repeats:2_stddev\",%csv_report$"}}); + +// ========================================================================= // +// ------------------------ Testing Basic Output --------------------------- // +// ========================================================================= // + +static void BM_ImplicitRepetitions(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_ImplicitRepetitions); + +ADD_CASES(TC_ConsoleOut, {{"^BM_ImplicitRepetitions %console_report$"}}); +ADD_CASES(TC_ConsoleOut, {{"^BM_ImplicitRepetitions %console_report$"}}); +ADD_CASES(TC_ConsoleOut, {{"^BM_ImplicitRepetitions %console_report$"}}); +ADD_CASES(TC_ConsoleOut, {{"^BM_ImplicitRepetitions_mean %console_report$"}}); +ADD_CASES(TC_ConsoleOut, {{"^BM_ImplicitRepetitions_median %console_report$"}}); +ADD_CASES(TC_ConsoleOut, {{"^BM_ImplicitRepetitions_stddev %console_report$"}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_ImplicitRepetitions\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ImplicitRepetitions\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_ImplicitRepetitions\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ImplicitRepetitions\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"repetition_index\": 1,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_ImplicitRepetitions\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ImplicitRepetitions\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"repetition_index\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_ImplicitRepetitions_mean\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ImplicitRepetitions\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_ImplicitRepetitions_median\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ImplicitRepetitions\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_ImplicitRepetitions_stddev\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_ImplicitRepetitions\",$", MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_ImplicitRepetitions\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_ImplicitRepetitions\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_ImplicitRepetitions_mean\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_ImplicitRepetitions_median\",%csv_report$"}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_ImplicitRepetitions_stddev\",%csv_report$"}}); + +// ========================================================================= // +// --------------------------- TEST CASES END ------------------------------ // +// ========================================================================= // + +int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/thirdparty_builtin/benchmark-1.5.0/test/report_aggregates_only_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/report_aggregates_only_test.cc similarity index 83% rename from thirdparty_builtin/benchmark-1.5.0/test/report_aggregates_only_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/report_aggregates_only_test.cc index 9646b9be5..47da50358 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/report_aggregates_only_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/report_aggregates_only_test.cc @@ -19,17 +19,19 @@ BENCHMARK(BM_SummaryRepeat)->Repetitions(3)->ReportAggregatesOnly(); int main(int argc, char* argv[]) { const std::string output = GetFileReporterOutput(argc, argv); - if (SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3") != 3 || + if (SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3") != 4 || SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_mean\"") != 1 || SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_median\"") != 1 || SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"") != - 1) { - std::cout << "Precondition mismatch. Expected to only find three " + 1 || + SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_cv\"") != 1) { + std::cout << "Precondition mismatch. Expected to only find four " "occurrences of \"BM_SummaryRepeat/repeats:3\" substring:\n" "\"name\": \"BM_SummaryRepeat/repeats:3_mean\", " "\"name\": \"BM_SummaryRepeat/repeats:3_median\", " - "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"\nThe entire " + "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\", " + "\"name\": \"BM_SummaryRepeat/repeats:3_cv\"\nThe entire " "output:\n"; std::cout << output; return 1; diff --git a/thirdparty_builtin/benchmark-1.5.0/test/reporter_output_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/reporter_output_test.cc similarity index 64% rename from thirdparty_builtin/benchmark-1.5.0/test/reporter_output_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/reporter_output_test.cc index c8090d4ac..2eb545a8d 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/reporter_output_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/reporter_output_test.cc @@ -1,5 +1,6 @@ #undef NDEBUG +#include #include #include "benchmark/benchmark.h" @@ -15,8 +16,8 @@ ADD_CASES(TC_ConsoleOut, {{"^[-]+$", MR_Next}, static int AddContextCases() { AddCases(TC_ConsoleErr, { - {"%int[-/]%int[-/]%int %int:%int:%int$", MR_Default}, - {"Running .*/reporter_output_test(\\.exe)?$", MR_Next}, + {"^%int-%int-%intT%int:%int:%int[-+]%int:%int$", MR_Default}, + {"Running .*(/|\\\\)reporter_output_test(\\.exe)?$", MR_Next}, {"Run on \\(%int X %float MHz CPU s?\\)", MR_Next}, }); AddCases(TC_JSONOut, @@ -28,8 +29,7 @@ static int AddContextCases() { MR_Next}, {"\"num_cpus\": %int,$", MR_Next}, {"\"mhz_per_cpu\": %float,$", MR_Next}, - {"\"cpu_scaling_enabled\": ", MR_Next}, - {"\"caches\": \\[$", MR_Next}}); + {"\"caches\": \\[$", MR_Default}}); auto const& Info = benchmark::CPUInfo::Get(); auto const& Caches = Info.caches; if (!Caches.empty()) { @@ -38,9 +38,9 @@ static int AddContextCases() { for (size_t I = 0; I < Caches.size(); ++I) { std::string num_caches_str = Caches[I].num_sharing != 0 ? " \\(x%int\\)$" : "$"; - AddCases( - TC_ConsoleErr, - {{"L%int (Data|Instruction|Unified) %intK" + num_caches_str, MR_Next}}); + AddCases(TC_ConsoleErr, + {{"L%int (Data|Instruction|Unified) %int KiB" + num_caches_str, + MR_Next}}); AddCases(TC_JSONOut, {{"\\{$", MR_Next}, {"\"type\": \"", MR_Next}, {"\"level\": %int,$", MR_Next}, @@ -72,9 +72,11 @@ BENCHMARK(BM_basic); ADD_CASES(TC_ConsoleOut, {{"^BM_basic %console_report$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_basic\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_basic\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -90,6 +92,9 @@ ADD_CASES(TC_CSVOut, {{"^\"BM_basic\",%csv_report$"}}); void BM_bytes_per_second(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } state.SetBytesProcessed(1); } @@ -98,9 +103,11 @@ BENCHMARK(BM_bytes_per_second); ADD_CASES(TC_ConsoleOut, {{"^BM_bytes_per_second %console_report " "bytes_per_second=%float[kM]{0,1}/s$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_bytes_per_second\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_bytes_per_second\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -117,6 +124,9 @@ ADD_CASES(TC_CSVOut, {{"^\"BM_bytes_per_second\",%csv_bytes_report$"}}); void BM_items_per_second(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } state.SetItemsProcessed(1); } @@ -125,9 +135,11 @@ BENCHMARK(BM_items_per_second); ADD_CASES(TC_ConsoleOut, {{"^BM_items_per_second %console_report " "items_per_second=%float[kM]{0,1}/s$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_items_per_second\",$"}, + {"\"family_index\": 2,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_items_per_second\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -151,9 +163,11 @@ BENCHMARK(BM_label); ADD_CASES(TC_ConsoleOut, {{"^BM_label %console_report some label$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_label\",$"}, + {"\"family_index\": 3,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_label\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -165,6 +179,101 @@ ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_label\",$"}, ADD_CASES(TC_CSVOut, {{"^\"BM_label\",%csv_label_report_begin\"some " "label\"%csv_label_report_end$"}}); +// ========================================================================= // +// ------------------------ Testing Time Label Output ---------------------- // +// ========================================================================= // + +void BM_time_label_nanosecond(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_time_label_nanosecond)->Unit(benchmark::kNanosecond); + +ADD_CASES(TC_ConsoleOut, {{"^BM_time_label_nanosecond %console_report$"}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_time_label_nanosecond\",$"}, + {"\"family_index\": 4,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_time_label_nanosecond\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_time_label_nanosecond\",%csv_report$"}}); + +void BM_time_label_microsecond(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_time_label_microsecond)->Unit(benchmark::kMicrosecond); + +ADD_CASES(TC_ConsoleOut, {{"^BM_time_label_microsecond %console_us_report$"}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_time_label_microsecond\",$"}, + {"\"family_index\": 5,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_time_label_microsecond\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"us\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_time_label_microsecond\",%csv_us_report$"}}); + +void BM_time_label_millisecond(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_time_label_millisecond)->Unit(benchmark::kMillisecond); + +ADD_CASES(TC_ConsoleOut, {{"^BM_time_label_millisecond %console_ms_report$"}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_time_label_millisecond\",$"}, + {"\"family_index\": 6,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_time_label_millisecond\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ms\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_time_label_millisecond\",%csv_ms_report$"}}); + +void BM_time_label_second(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_time_label_second)->Unit(benchmark::kSecond); + +ADD_CASES(TC_ConsoleOut, {{"^BM_time_label_second %console_s_report$"}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_time_label_second\",$"}, + {"\"family_index\": 7,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_time_label_second\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"s\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_time_label_second\",%csv_s_report$"}}); + // ========================================================================= // // ------------------------ Testing Error Output --------------------------- // // ========================================================================= // @@ -177,9 +286,11 @@ void BM_error(benchmark::State& state) { BENCHMARK(BM_error); ADD_CASES(TC_ConsoleOut, {{"^BM_error[ ]+ERROR OCCURRED: 'message'$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_error\",$"}, + {"\"family_index\": 8,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_error\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"error_occurred\": true,$", MR_Next}, @@ -199,15 +310,17 @@ void BM_no_arg_name(benchmark::State& state) { BENCHMARK(BM_no_arg_name)->Arg(3); ADD_CASES(TC_ConsoleOut, {{"^BM_no_arg_name/3 %console_report$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_no_arg_name/3\",$"}, + {"\"family_index\": 9,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_no_arg_name/3\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{"^\"BM_no_arg_name/3\",%csv_report$"}}); // ========================================================================= // -// ------------------------ Testing Arg Name Output ----------------------- // +// ------------------------ Testing Arg Name Output ------------------------ // // ========================================================================= // void BM_arg_name(benchmark::State& state) { @@ -217,9 +330,11 @@ void BM_arg_name(benchmark::State& state) { BENCHMARK(BM_arg_name)->ArgName("first")->Arg(3); ADD_CASES(TC_ConsoleOut, {{"^BM_arg_name/first:3 %console_report$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_arg_name/first:3\",$"}, + {"\"family_index\": 10,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_arg_name/first:3\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{"^\"BM_arg_name/first:3\",%csv_report$"}}); @@ -237,13 +352,41 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_arg_names/first:2/5/third:4 %console_report$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_arg_names/first:2/5/third:4\",$"}, + {"\"family_index\": 11,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_arg_names/first:2/5/third:4\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{"^\"BM_arg_names/first:2/5/third:4\",%csv_report$"}}); +// ========================================================================= // +// ------------------------ Testing Name Output ---------------------------- // +// ========================================================================= // + +void BM_name(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_name)->Name("BM_custom_name"); + +ADD_CASES(TC_ConsoleOut, {{"^BM_custom_name %console_report$"}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_custom_name\",$"}, + {"\"family_index\": 12,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_custom_name\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\"$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_custom_name\",%csv_report$"}}); + // ========================================================================= // // ------------------------ Testing Big Args Output ------------------------ // // ========================================================================= // @@ -262,6 +405,9 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_BigArgs/1073741824 %console_report$"}, void BM_Complexity_O1(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } state.SetComplexityN(state.range(0)); } @@ -289,37 +435,50 @@ ADD_CASES(TC_ConsoleOut, {"^BM_Repeat/repeats:2_median %console_time_only_report [ ]*2$"}, {"^BM_Repeat/repeats:2_stddev %console_time_only_report [ ]*2$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:2\",$"}, + {"\"family_index\": 15,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:2\"", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:2\",$"}, + {"\"family_index\": 15,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"repetition_index\": 1,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:2_mean\",$"}, + {"\"family_index\": 15,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:2_median\",$"}, + {"\"family_index\": 15,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:2_stddev\",$"}, + {"\"family_index\": 15,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:2\",%csv_report$"}, {"^\"BM_Repeat/repeats:2\",%csv_report$"}, @@ -336,43 +495,58 @@ ADD_CASES(TC_ConsoleOut, {"^BM_Repeat/repeats:3_median %console_time_only_report [ ]*3$"}, {"^BM_Repeat/repeats:3_stddev %console_time_only_report [ ]*3$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:3\",$"}, + {"\"family_index\": 16,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:3\",$"}, + {"\"family_index\": 16,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"repetition_index\": 1,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:3\",$"}, + {"\"family_index\": 16,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"repetition_index\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:3_mean\",$"}, + {"\"family_index\": 16,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:3_median\",$"}, + {"\"family_index\": 16,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:3_stddev\",$"}, + {"\"family_index\": 16,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:3\",%csv_report$"}, {"^\"BM_Repeat/repeats:3\",%csv_report$"}, @@ -391,49 +565,66 @@ ADD_CASES(TC_ConsoleOut, {"^BM_Repeat/repeats:4_median %console_time_only_report [ ]*4$"}, {"^BM_Repeat/repeats:4_stddev %console_time_only_report [ ]*4$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:4\",$"}, + {"\"family_index\": 17,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 4,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:4\",$"}, + {"\"family_index\": 17,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 4,$", MR_Next}, {"\"repetition_index\": 1,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:4\",$"}, + {"\"family_index\": 17,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 4,$", MR_Next}, {"\"repetition_index\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:4\",$"}, + {"\"family_index\": 17,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 4,$", MR_Next}, {"\"repetition_index\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:4_mean\",$"}, + {"\"family_index\": 17,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 4,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 4,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:4_median\",$"}, + {"\"family_index\": 17,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 4,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 4,$", MR_Next}, {"\"name\": \"BM_Repeat/repeats:4_stddev\",$"}, + {"\"family_index\": 17,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 4,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 4,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:4\",%csv_report$"}, {"^\"BM_Repeat/repeats:4\",%csv_report$"}, @@ -452,6 +643,8 @@ void BM_RepeatOnce(benchmark::State& state) { BENCHMARK(BM_RepeatOnce)->Repetitions(1)->ReportAggregatesOnly(); ADD_CASES(TC_ConsoleOut, {{"^BM_RepeatOnce/repeats:1 %console_report$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_RepeatOnce/repeats:1\",$"}, + {"\"family_index\": 18,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_RepeatOnce/repeats:1\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 1,$", MR_Next}, @@ -474,25 +667,34 @@ ADD_CASES( ADD_CASES(TC_JSONOut, {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, {"\"name\": \"BM_SummaryRepeat/repeats:3_mean\",$"}, + {"\"family_index\": 19,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_SummaryRepeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"name\": \"BM_SummaryRepeat/repeats:3_median\",$"}, + {"\"family_index\": 19,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_SummaryRepeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"name\": \"BM_SummaryRepeat/repeats:3_stddev\",$"}, + {"\"family_index\": 19,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_SummaryRepeat/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, {"^\"BM_SummaryRepeat/repeats:3_mean\",%csv_report$"}, @@ -516,25 +718,34 @@ ADD_CASES( ADD_CASES(TC_JSONOut, {{".*BM_SummaryDisplay/repeats:2 ", MR_Not}, {"\"name\": \"BM_SummaryDisplay/repeats:2_mean\",$"}, + {"\"family_index\": 20,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_SummaryDisplay/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}, {"\"name\": \"BM_SummaryDisplay/repeats:2_median\",$"}, + {"\"family_index\": 20,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_SummaryDisplay/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}, {"\"name\": \"BM_SummaryDisplay/repeats:2_stddev\",$"}, + {"\"family_index\": 20,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_SummaryDisplay/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}}); ADD_CASES(TC_CSVOut, {{".*BM_SummaryDisplay/repeats:2 ", MR_Not}, @@ -562,27 +773,36 @@ ADD_CASES( ADD_CASES(TC_JSONOut, {{".*BM_RepeatTimeUnit/repeats:3 ", MR_Not}, {"\"name\": \"BM_RepeatTimeUnit/repeats:3_mean\",$"}, + {"\"family_index\": 21,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_RepeatTimeUnit/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"time_unit\": \"us\",?$"}, {"\"name\": \"BM_RepeatTimeUnit/repeats:3_median\",$"}, + {"\"family_index\": 21,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_RepeatTimeUnit/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"time_unit\": \"us\",?$"}, {"\"name\": \"BM_RepeatTimeUnit/repeats:3_stddev\",$"}, + {"\"family_index\": 21,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_RepeatTimeUnit/repeats:3\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"time_unit\": \"us\",?$"}}); ADD_CASES(TC_CSVOut, @@ -630,6 +850,8 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_UserStats/iterations:5/repeats:3/manual_time [ " ADD_CASES( TC_JSONOut, {{"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$"}, + {"\"family_index\": 22,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, @@ -639,6 +861,8 @@ ADD_CASES( {"\"iterations\": 5,$", MR_Next}, {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$"}, + {"\"family_index\": 22,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, @@ -648,6 +872,8 @@ ADD_CASES( {"\"iterations\": 5,$", MR_Next}, {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$"}, + {"\"family_index\": 22,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, @@ -657,39 +883,51 @@ ADD_CASES( {"\"iterations\": 5,$", MR_Next}, {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_mean\",$"}, + {"\"family_index\": 22,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_median\",$"}, + {"\"family_index\": 22,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_stddev\",$"}, + {"\"family_index\": 22,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"real_time\": %float,$", MR_Next}, {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_\",$"}, + {"\"family_index\": 22,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 3,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 3,$", MR_Next}, {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}}); ADD_CASES( @@ -704,10 +942,158 @@ ADD_CASES( "manual_time_stddev\",%csv_report$"}, {"^\"BM_UserStats/iterations:5/repeats:3/manual_time_\",%csv_report$"}}); +// ========================================================================= // +// ------------- Testing relative standard deviation statistics ------------ // +// ========================================================================= // + +const auto UserPercentStatistics = [](const std::vector&) { + return 1. / 100.; +}; +void BM_UserPercentStats(benchmark::State& state) { + for (auto _ : state) { + state.SetIterationTime(150 / 10e8); + } +} +// clang-format off +BENCHMARK(BM_UserPercentStats) + ->Repetitions(3) + ->Iterations(5) + ->UseManualTime() + ->Unit(benchmark::TimeUnit::kNanosecond) + ->ComputeStatistics("", UserPercentStatistics, benchmark::StatisticUnit::kPercentage); +// clang-format on + +// check that UserPercent-provided stats is calculated, and is after the +// default-ones empty string as name is intentional, it would sort before +// anything else +ADD_CASES(TC_ConsoleOut, + {{"^BM_UserPercentStats/iterations:5/repeats:3/manual_time [ " + "]* 150 ns %time [ ]*5$"}, + {"^BM_UserPercentStats/iterations:5/repeats:3/manual_time [ " + "]* 150 ns %time [ ]*5$"}, + {"^BM_UserPercentStats/iterations:5/repeats:3/manual_time [ " + "]* 150 ns %time [ ]*5$"}, + {"^BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time_mean [ ]* 150 ns %time [ ]*3$"}, + {"^BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time_median [ ]* 150 ns %time [ ]*3$"}, + {"^BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time_stddev [ ]* 0.000 ns %time [ ]*3$"}, + {"^BM_UserPercentStats/iterations:5/repeats:3/manual_time_ " + "[ ]* 1.00 % [ ]* 1.00 %[ ]*3$"}}); +ADD_CASES( + TC_JSONOut, + {{"\"name\": \"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$"}, + {"\"family_index\": 23,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": 5,$", MR_Next}, + {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, + {"\"name\": \"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$"}, + {"\"family_index\": 23,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"repetition_index\": 1,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": 5,$", MR_Next}, + {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, + {"\"name\": \"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$"}, + {"\"family_index\": 23,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"repetition_index\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": 5,$", MR_Next}, + {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, + {"\"name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_mean\",$"}, + {"\"family_index\": 23,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": 3,$", MR_Next}, + {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, + {"\"name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_median\",$"}, + {"\"family_index\": 23,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": 3,$", MR_Next}, + {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, + {"\"name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_stddev\",$"}, + {"\"family_index\": 23,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": 3,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_\",$"}, + {"\"family_index\": 23,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": " + "\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 3,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"\",$", MR_Next}, + {"\"aggregate_unit\": \"percentage\",$", MR_Next}, + {"\"iterations\": 3,$", MR_Next}, + {"\"real_time\": 1\\.(0)*e-(0)*2,$", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time\",%csv_report$"}, + {"^\"BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time\",%csv_report$"}, + {"^\"BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time\",%csv_report$"}, + {"^\"BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time_mean\",%csv_report$"}, + {"^\"BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time_median\",%csv_report$"}, + {"^\"BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time_stddev\",%csv_report$"}, + {"^\"BM_UserPercentStats/iterations:5/repeats:3/" + "manual_time_\",%csv_report$"}}); + // ========================================================================= // // ------------------------- Testing StrEscape JSON ------------------------ // // ========================================================================= // -#if 0 // enable when csv testing code correctly handles multi-line fields +#if 0 // enable when csv testing code correctly handles multi-line fields void BM_JSON_Format(benchmark::State& state) { state.SkipWithError("val\b\f\n\r\t\\\"with\"es,capes"); for (auto _ : state) { @@ -715,9 +1101,11 @@ void BM_JSON_Format(benchmark::State& state) { } BENCHMARK(BM_JSON_Format); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_JSON_Format\",$"}, + {"\"family_index\": 23,$", MR_Next}, +{"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_JSON_Format\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"error_occurred\": true,$", MR_Next}, diff --git a/thirdparty_builtin/benchmark-1.5.0/test/skip_with_error_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/skip_with_error_test.cc similarity index 84% rename from thirdparty_builtin/benchmark-1.5.0/test/skip_with_error_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/skip_with_error_test.cc index 06579772f..b4c5e154c 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/skip_with_error_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/skip_with_error_test.cc @@ -10,17 +10,17 @@ namespace { class TestReporter : public benchmark::ConsoleReporter { public: - virtual bool ReportContext(const Context& context) { + bool ReportContext(const Context& context) override { return ConsoleReporter::ReportContext(context); }; - virtual void ReportRuns(const std::vector& report) { + void ReportRuns(const std::vector& report) override { all_runs_.insert(all_runs_.end(), begin(report), end(report)); ConsoleReporter::ReportRuns(report); } TestReporter() {} - virtual ~TestReporter() {} + ~TestReporter() override {} mutable std::vector all_runs_; }; @@ -33,21 +33,23 @@ struct TestCase { typedef benchmark::BenchmarkReporter::Run Run; void CheckRun(Run const& run) const { - CHECK(name == run.benchmark_name()) + BM_CHECK(name == run.benchmark_name()) << "expected " << name << " got " << run.benchmark_name(); - CHECK(error_occurred == run.error_occurred); - CHECK(error_message == run.error_message); + BM_CHECK_EQ(error_occurred, + benchmark::internal::SkippedWithError == run.skipped); + BM_CHECK(error_message == run.skip_message); if (error_occurred) { - // CHECK(run.iterations == 0); + // BM_CHECK(run.iterations == 0); } else { - CHECK(run.iterations != 0); + BM_CHECK(run.iterations != 0); } } }; std::vector ExpectedResults; -int AddCases(const char* base_name, std::initializer_list const& v) { +int AddCases(const std::string& base_name, + std::initializer_list const& v) { for (auto TC : v) { TC.name = base_name + TC.name; ExpectedResults.push_back(std::move(TC)); @@ -61,6 +63,12 @@ int AddCases(const char* base_name, std::initializer_list const& v) { } // end namespace +void BM_error_no_running(benchmark::State& state) { + state.SkipWithError("error message"); +} +BENCHMARK(BM_error_no_running); +ADD_CASES("BM_error_no_running", {{"", true, "error message"}}); + void BM_error_before_running(benchmark::State& state) { state.SkipWithError("error message"); while (state.KeepRunning()) { @@ -91,7 +99,7 @@ ADD_CASES("BM_error_before_running_range_for", {{"", true, "error message"}}); void BM_error_during_running(benchmark::State& state) { int first_iter = true; while (state.KeepRunning()) { - if (state.range(0) == 1 && state.thread_index <= (state.threads / 2)) { + if (state.range(0) == 1 && state.thread_index() <= (state.threads() / 2)) { assert(first_iter); first_iter = false; state.SkipWithError("error message"); @@ -113,12 +121,13 @@ ADD_CASES("BM_error_during_running", {{"/1/threads:1", true, "error message"}, void BM_error_during_running_ranged_for(benchmark::State& state) { assert(state.max_iterations > 3 && "test requires at least a few iterations"); - int first_iter = true; + bool first_iter = true; // NOTE: Users should not write the for loop explicitly. for (auto It = state.begin(), End = state.end(); It != End; ++It) { if (state.range(0) == 1) { assert(first_iter); first_iter = false; + (void)first_iter; state.SkipWithError("error message"); // Test the unfortunate but documented behavior that the ranged-for loop // doesn't automatically terminate when SkipWithError is set. @@ -134,9 +143,10 @@ ADD_CASES("BM_error_during_running_ranged_for", void BM_error_after_running(benchmark::State& state) { for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } - if (state.thread_index <= (state.threads / 2)) + if (state.thread_index() <= (state.threads() / 2)) state.SkipWithError("error message"); } BENCHMARK(BM_error_after_running)->ThreadRange(1, 8); @@ -148,7 +158,7 @@ ADD_CASES("BM_error_after_running", {{"/threads:1", true, "error message"}, void BM_error_while_paused(benchmark::State& state) { bool first_iter = true; while (state.KeepRunning()) { - if (state.range(0) == 1 && state.thread_index <= (state.threads / 2)) { + if (state.range(0) == 1 && state.thread_index() <= (state.threads() / 2)) { assert(first_iter); first_iter = false; state.PauseTiming(); diff --git a/thirdparty_builtin/benchmark-1.8.0/test/spec_arg_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/spec_arg_test.cc new file mode 100644 index 000000000..06aafbeb9 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/spec_arg_test.cc @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "benchmark/benchmark.h" + +// Tests that we can override benchmark-spec value from FLAGS_benchmark_filter +// with argument to RunSpecifiedBenchmarks(...). + +namespace { + +class TestReporter : public benchmark::ConsoleReporter { + public: + bool ReportContext(const Context& context) override { + return ConsoleReporter::ReportContext(context); + }; + + void ReportRuns(const std::vector& report) override { + assert(report.size() == 1); + matched_functions.push_back(report[0].run_name.function_name); + ConsoleReporter::ReportRuns(report); + }; + + TestReporter() {} + + ~TestReporter() override {} + + const std::vector& GetMatchedFunctions() const { + return matched_functions; + } + + private: + std::vector matched_functions; +}; + +} // end namespace + +static void BM_NotChosen(benchmark::State& state) { + assert(false && "SHOULD NOT BE CALLED"); + for (auto _ : state) { + } +} +BENCHMARK(BM_NotChosen); + +static void BM_Chosen(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_Chosen); + +int main(int argc, char** argv) { + const std::string flag = "BM_NotChosen"; + + // Verify that argv specify --benchmark_filter=BM_NotChosen. + bool found = false; + for (int i = 0; i < argc; ++i) { + if (strcmp("--benchmark_filter=BM_NotChosen", argv[i]) == 0) { + found = true; + break; + } + } + assert(found); + + benchmark::Initialize(&argc, argv); + + // Check that the current flag value is reported accurately via the + // GetBenchmarkFilter() function. + if (flag != benchmark::GetBenchmarkFilter()) { + std::cerr + << "Seeing different value for flags. GetBenchmarkFilter() returns [" + << benchmark::GetBenchmarkFilter() << "] expected flag=[" << flag + << "]\n"; + return 1; + } + TestReporter test_reporter; + const char* const spec = "BM_Chosen"; + const size_t returned_count = + benchmark::RunSpecifiedBenchmarks(&test_reporter, spec); + assert(returned_count == 1); + const std::vector matched_functions = + test_reporter.GetMatchedFunctions(); + assert(matched_functions.size() == 1); + if (strcmp(spec, matched_functions.front().c_str()) != 0) { + std::cerr << "Expected benchmark [" << spec << "] to run, but got [" + << matched_functions.front() << "]\n"; + return 2; + } + + // Test that SetBenchmarkFilter works. + const std::string golden_value = "golden_value"; + benchmark::SetBenchmarkFilter(golden_value); + std::string current_value = benchmark::GetBenchmarkFilter(); + if (golden_value != current_value) { + std::cerr << "Expected [" << golden_value + << "] for --benchmark_filter but got [" << current_value << "]\n"; + return 3; + } + return 0; +} diff --git a/thirdparty_builtin/benchmark-1.8.0/test/spec_arg_verbosity_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/spec_arg_verbosity_test.cc new file mode 100644 index 000000000..8f8eb6d37 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/spec_arg_verbosity_test.cc @@ -0,0 +1,43 @@ +#include + +#include + +#include "benchmark/benchmark.h" + +// Tests that the user specified verbosity level can be get. +static void BM_Verbosity(benchmark::State& state) { + for (auto _ : state) { + } +} +BENCHMARK(BM_Verbosity); + +int main(int argc, char** argv) { + const int32_t flagv = 42; + + // Verify that argv specify --v=42. + bool found = false; + for (int i = 0; i < argc; ++i) { + if (strcmp("--v=42", argv[i]) == 0) { + found = true; + break; + } + } + if (!found) { + std::cerr << "This test requires '--v=42' to be passed as a command-line " + << "argument.\n"; + return 1; + } + + benchmark::Initialize(&argc, argv); + + // Check that the current flag value is reported accurately via the + // GetBenchmarkVerbosity() function. + if (flagv != benchmark::GetBenchmarkVerbosity()) { + std::cerr + << "Seeing different value for flags. GetBenchmarkVerbosity() returns [" + << benchmark::GetBenchmarkVerbosity() << "] expected flag=[" << flagv + << "]\n"; + return 1; + } + return 0; +} diff --git a/thirdparty_builtin/benchmark-1.5.0/test/state_assembly_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/state_assembly_test.cc similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/test/state_assembly_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/state_assembly_test.cc diff --git a/thirdparty_builtin/benchmark-1.5.0/test/statistics_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/statistics_gtest.cc similarity index 71% rename from thirdparty_builtin/benchmark-1.5.0/test/statistics_gtest.cc rename to thirdparty_builtin/benchmark-1.8.0/test/statistics_gtest.cc index 99e314920..1de2d87d4 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/statistics_gtest.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/statistics_gtest.cc @@ -21,8 +21,15 @@ TEST(StatisticsTest, Median) { TEST(StatisticsTest, StdDev) { EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({101, 101, 101, 101}), 0.0); EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({1, 2, 3}), 1.0); - EXPECT_FLOAT_EQ(benchmark::StatisticsStdDev({1.5, 2.4, 3.3, 4.2, 5.1}), - 1.42302495); + EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({2.5, 2.4, 3.3, 4.2, 5.1}), + 1.151086443322134); +} + +TEST(StatisticsTest, CV) { + EXPECT_DOUBLE_EQ(benchmark::StatisticsCV({101, 101, 101, 101}), 0.0); + EXPECT_DOUBLE_EQ(benchmark::StatisticsCV({1, 2, 3}), 1. / 2.); + EXPECT_DOUBLE_EQ(benchmark::StatisticsCV({2.5, 2.4, 3.3, 4.2, 5.1}), + 0.32888184094918121); } } // end namespace diff --git a/thirdparty_builtin/benchmark-1.8.0/test/string_util_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/string_util_gtest.cc new file mode 100644 index 000000000..8bfdb7a72 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/string_util_gtest.cc @@ -0,0 +1,163 @@ +//===---------------------------------------------------------------------===// +// statistics_test - Unit tests for src/statistics.cc +//===---------------------------------------------------------------------===// + +#include + +#include "../src/internal_macros.h" +#include "../src/string_util.h" +#include "gtest/gtest.h" + +namespace { +TEST(StringUtilTest, stoul) { + { + size_t pos = 0; + EXPECT_EQ(0ul, benchmark::stoul("0", &pos)); + EXPECT_EQ(1ul, pos); + } + { + size_t pos = 0; + EXPECT_EQ(7ul, benchmark::stoul("7", &pos)); + EXPECT_EQ(1ul, pos); + } + { + size_t pos = 0; + EXPECT_EQ(135ul, benchmark::stoul("135", &pos)); + EXPECT_EQ(3ul, pos); + } +#if ULONG_MAX == 0xFFFFFFFFul + { + size_t pos = 0; + EXPECT_EQ(0xFFFFFFFFul, benchmark::stoul("4294967295", &pos)); + EXPECT_EQ(10ul, pos); + } +#elif ULONG_MAX == 0xFFFFFFFFFFFFFFFFul + { + size_t pos = 0; + EXPECT_EQ(0xFFFFFFFFFFFFFFFFul, + benchmark::stoul("18446744073709551615", &pos)); + EXPECT_EQ(20ul, pos); + } +#endif + { + size_t pos = 0; + EXPECT_EQ(10ul, benchmark::stoul("1010", &pos, 2)); + EXPECT_EQ(4ul, pos); + } + { + size_t pos = 0; + EXPECT_EQ(520ul, benchmark::stoul("1010", &pos, 8)); + EXPECT_EQ(4ul, pos); + } + { + size_t pos = 0; + EXPECT_EQ(1010ul, benchmark::stoul("1010", &pos, 10)); + EXPECT_EQ(4ul, pos); + } + { + size_t pos = 0; + EXPECT_EQ(4112ul, benchmark::stoul("1010", &pos, 16)); + EXPECT_EQ(4ul, pos); + } + { + size_t pos = 0; + EXPECT_EQ(0xBEEFul, benchmark::stoul("BEEF", &pos, 16)); + EXPECT_EQ(4ul, pos); + } +#ifndef BENCHMARK_HAS_NO_EXCEPTIONS + { + ASSERT_THROW(std::ignore = benchmark::stoul("this is a test"), + std::invalid_argument); + } +#endif +} + +TEST(StringUtilTest, stoi){{size_t pos = 0; +EXPECT_EQ(0, benchmark::stoi("0", &pos)); +EXPECT_EQ(1ul, pos); +} // namespace +{ + size_t pos = 0; + EXPECT_EQ(-17, benchmark::stoi("-17", &pos)); + EXPECT_EQ(3ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(1357, benchmark::stoi("1357", &pos)); + EXPECT_EQ(4ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(10, benchmark::stoi("1010", &pos, 2)); + EXPECT_EQ(4ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(520, benchmark::stoi("1010", &pos, 8)); + EXPECT_EQ(4ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(1010, benchmark::stoi("1010", &pos, 10)); + EXPECT_EQ(4ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(4112, benchmark::stoi("1010", &pos, 16)); + EXPECT_EQ(4ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(0xBEEF, benchmark::stoi("BEEF", &pos, 16)); + EXPECT_EQ(4ul, pos); +} +#ifndef BENCHMARK_HAS_NO_EXCEPTIONS +{ + ASSERT_THROW(std::ignore = benchmark::stoi("this is a test"), + std::invalid_argument); +} +#endif +} + +TEST(StringUtilTest, stod){{size_t pos = 0; +EXPECT_EQ(0.0, benchmark::stod("0", &pos)); +EXPECT_EQ(1ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(-84.0, benchmark::stod("-84", &pos)); + EXPECT_EQ(3ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(1234.0, benchmark::stod("1234", &pos)); + EXPECT_EQ(4ul, pos); +} +{ + size_t pos = 0; + EXPECT_EQ(1.5, benchmark::stod("1.5", &pos)); + EXPECT_EQ(3ul, pos); +} +{ + size_t pos = 0; + /* Note: exactly representable as double */ + EXPECT_EQ(-1.25e+9, benchmark::stod("-1.25e+9", &pos)); + EXPECT_EQ(8ul, pos); +} +#ifndef BENCHMARK_HAS_NO_EXCEPTIONS +{ + ASSERT_THROW(std::ignore = benchmark::stod("this is a test"), + std::invalid_argument); +} +#endif +} + +TEST(StringUtilTest, StrSplit) { + EXPECT_EQ(benchmark::StrSplit("", ','), std::vector{}); + EXPECT_EQ(benchmark::StrSplit("hello", ','), + std::vector({"hello"})); + EXPECT_EQ(benchmark::StrSplit("hello,there,is,more", ','), + std::vector({"hello", "there", "is", "more"})); +} + +} // end namespace diff --git a/thirdparty_builtin/benchmark-1.5.0/test/templated_fixture_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/templated_fixture_test.cc similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/test/templated_fixture_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/templated_fixture_test.cc index fe9865cc7..af239c3a7 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/templated_fixture_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/templated_fixture_test.cc @@ -1,9 +1,9 @@ -#include "benchmark/benchmark.h" - #include #include +#include "benchmark/benchmark.h" + template class MyFixture : public ::benchmark::Fixture { public: diff --git a/thirdparty_builtin/benchmark-1.8.0/test/time_unit_gtest.cc b/thirdparty_builtin/benchmark-1.8.0/test/time_unit_gtest.cc new file mode 100644 index 000000000..484ecbcfb --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/time_unit_gtest.cc @@ -0,0 +1,37 @@ +#include "../include/benchmark/benchmark.h" +#include "gtest/gtest.h" + +namespace benchmark { +namespace internal { + +namespace { + +class DummyBenchmark : public Benchmark { + public: + DummyBenchmark() : Benchmark("dummy") {} + void Run(State&) override {} +}; + +TEST(DefaultTimeUnitTest, TimeUnitIsNotSet) { + DummyBenchmark benchmark; + EXPECT_EQ(benchmark.GetTimeUnit(), kNanosecond); +} + +TEST(DefaultTimeUnitTest, DefaultIsSet) { + DummyBenchmark benchmark; + EXPECT_EQ(benchmark.GetTimeUnit(), kNanosecond); + SetDefaultTimeUnit(kMillisecond); + EXPECT_EQ(benchmark.GetTimeUnit(), kMillisecond); +} + +TEST(DefaultTimeUnitTest, DefaultAndExplicitUnitIsSet) { + DummyBenchmark benchmark; + benchmark.Unit(kMillisecond); + SetDefaultTimeUnit(kMicrosecond); + + EXPECT_EQ(benchmark.GetTimeUnit(), kMillisecond); +} + +} // namespace +} // namespace internal +} // namespace benchmark diff --git a/thirdparty_builtin/benchmark-1.8.0/test/user_counters_tabular_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/user_counters_tabular_test.cc new file mode 100644 index 000000000..c98b769af --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/test/user_counters_tabular_test.cc @@ -0,0 +1,558 @@ + +#undef NDEBUG + +#include "benchmark/benchmark.h" +#include "output_test.h" + +// @todo: this checks the full output at once; the rule for +// CounterSet1 was failing because it was not matching "^[-]+$". +// @todo: check that the counters are vertically aligned. +ADD_CASES(TC_ConsoleOut, + { + // keeping these lines long improves readability, so: + // clang-format off + {"^[-]+$", MR_Next}, + {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Bat %s Baz %s Foo %s Frob %s Lob$", MR_Next}, + {"^[-]+$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:1 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:1 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:1_mean %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:1_median %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:1_stddev %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:1_cv %console_percentage_report [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*%$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:2 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:2 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:2_mean %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:2_median %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:2_stddev %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_Counters_Tabular/repeats:2/threads:2_cv %console_percentage_report [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*%$", MR_Next}, + {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, + {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, + {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, + {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, + {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, + {"^[-]+$", MR_Next}, + {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Baz %s Foo$", MR_Next}, + {"^[-]+$", MR_Next}, + {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^[-]+$", MR_Next}, + {"^Benchmark %s Time %s CPU %s Iterations %s Bat %s Baz %s Foo$", MR_Next}, + {"^[-]+$", MR_Next}, + {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, + {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$"}, + // clang-format on + }); +ADD_CASES(TC_CSVOut, {{"%csv_header," + "\"Bar\",\"Bat\",\"Baz\",\"Foo\",\"Frob\",\"Lob\""}}); + +// ========================================================================= // +// ------------------------- Tabular Counters Output ----------------------- // +// ========================================================================= // + +void BM_Counters_Tabular(benchmark::State& state) { + for (auto _ : state) { + } + namespace bm = benchmark; + state.counters.insert({ + {"Foo", {1, bm::Counter::kAvgThreads}}, + {"Bar", {2, bm::Counter::kAvgThreads}}, + {"Baz", {4, bm::Counter::kAvgThreads}}, + {"Bat", {8, bm::Counter::kAvgThreads}}, + {"Frob", {16, bm::Counter::kAvgThreads}}, + {"Lob", {32, bm::Counter::kAvgThreads}}, + }); +} +BENCHMARK(BM_Counters_Tabular)->ThreadRange(1, 2)->Repetitions(2); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"repetition_index\": 1,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:1_mean\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:1_median\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:1_stddev\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:1_cv\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:1\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"aggregate_name\": \"cv\",$", MR_Next}, + {"\"aggregate_unit\": \"percentage\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); + +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:2\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 1,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:2\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 2,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:2\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 1,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:2\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"repetition_index\": 1,$", MR_Next}, + {"\"threads\": 2,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:2_median\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 1,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:2\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 2,$", MR_Next}, + {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:2_stddev\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 1,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:2\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 2,$", MR_Next}, + {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_Tabular/repeats:2/threads:2_cv\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 1,$", MR_Next}, + {"\"run_name\": \"BM_Counters_Tabular/repeats:2/threads:2\",$", + MR_Next}, + {"\"run_type\": \"aggregate\",$", MR_Next}, + {"\"repetitions\": 2,$", MR_Next}, + {"\"threads\": 2,$", MR_Next}, + {"\"aggregate_name\": \"cv\",$", MR_Next}, + {"\"aggregate_unit\": \"percentage\",$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:1\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:1\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:1_mean\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:1_median\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:1_stddev\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:1_cv\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:2\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:2\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:2_mean\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:2_median\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:2_stddev\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_Tabular/repeats:2/threads:2_cv\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +// VS2013 does not allow this function to be passed as a lambda argument +// to CHECK_BENCHMARK_RESULTS() +void CheckTabular(Results const& e) { + CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 1); + CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 2); + CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 4); + CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 8); + CHECK_COUNTER_VALUE(e, int, "Frob", EQ, 16); + CHECK_COUNTER_VALUE(e, int, "Lob", EQ, 32); +} +CHECK_BENCHMARK_RESULTS("BM_Counters_Tabular/repeats:2/threads:1$", + &CheckTabular); +CHECK_BENCHMARK_RESULTS("BM_Counters_Tabular/repeats:2/threads:2$", + &CheckTabular); + +// ========================================================================= // +// -------------------- Tabular+Rate Counters Output ----------------------- // +// ========================================================================= // + +void BM_CounterRates_Tabular(benchmark::State& state) { + for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); + } + namespace bm = benchmark; + state.counters.insert({ + {"Foo", {1, bm::Counter::kAvgThreadsRate}}, + {"Bar", {2, bm::Counter::kAvgThreadsRate}}, + {"Baz", {4, bm::Counter::kAvgThreadsRate}}, + {"Bat", {8, bm::Counter::kAvgThreadsRate}}, + {"Frob", {16, bm::Counter::kAvgThreadsRate}}, + {"Lob", {32, bm::Counter::kAvgThreadsRate}}, + }); +} +BENCHMARK(BM_CounterRates_Tabular)->ThreadRange(1, 16); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_CounterRates_Tabular/threads:%int\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_CounterRates_Tabular/threads:%int\",$", + MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float,$", MR_Next}, + {"\"Frob\": %float,$", MR_Next}, + {"\"Lob\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_CounterRates_Tabular/threads:%int\",%csv_report," + "%float,%float,%float,%float,%float,%float$"}}); +// VS2013 does not allow this function to be passed as a lambda argument +// to CHECK_BENCHMARK_RESULTS() +void CheckTabularRate(Results const& e) { + double t = e.DurationCPUTime(); + CHECK_FLOAT_COUNTER_VALUE(e, "Foo", EQ, 1. / t, 0.001); + CHECK_FLOAT_COUNTER_VALUE(e, "Bar", EQ, 2. / t, 0.001); + CHECK_FLOAT_COUNTER_VALUE(e, "Baz", EQ, 4. / t, 0.001); + CHECK_FLOAT_COUNTER_VALUE(e, "Bat", EQ, 8. / t, 0.001); + CHECK_FLOAT_COUNTER_VALUE(e, "Frob", EQ, 16. / t, 0.001); + CHECK_FLOAT_COUNTER_VALUE(e, "Lob", EQ, 32. / t, 0.001); +} +CHECK_BENCHMARK_RESULTS("BM_CounterRates_Tabular/threads:%int", + &CheckTabularRate); + +// ========================================================================= // +// ------------------------- Tabular Counters Output ----------------------- // +// ========================================================================= // + +// set only some of the counters +void BM_CounterSet0_Tabular(benchmark::State& state) { + for (auto _ : state) { + } + namespace bm = benchmark; + state.counters.insert({ + {"Foo", {10, bm::Counter::kAvgThreads}}, + {"Bar", {20, bm::Counter::kAvgThreads}}, + {"Baz", {40, bm::Counter::kAvgThreads}}, + }); +} +BENCHMARK(BM_CounterSet0_Tabular)->ThreadRange(1, 16); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_CounterSet0_Tabular/threads:%int\",$"}, + {"\"family_index\": 2,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_CounterSet0_Tabular/threads:%int\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet0_Tabular/threads:%int\",%csv_report," + "%float,,%float,%float,,"}}); +// VS2013 does not allow this function to be passed as a lambda argument +// to CHECK_BENCHMARK_RESULTS() +void CheckSet0(Results const& e) { + CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); + CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 20); + CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); +} +CHECK_BENCHMARK_RESULTS("BM_CounterSet0_Tabular", &CheckSet0); + +// again. +void BM_CounterSet1_Tabular(benchmark::State& state) { + for (auto _ : state) { + } + namespace bm = benchmark; + state.counters.insert({ + {"Foo", {15, bm::Counter::kAvgThreads}}, + {"Bar", {25, bm::Counter::kAvgThreads}}, + {"Baz", {45, bm::Counter::kAvgThreads}}, + }); +} +BENCHMARK(BM_CounterSet1_Tabular)->ThreadRange(1, 16); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_CounterSet1_Tabular/threads:%int\",$"}, + {"\"family_index\": 3,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_CounterSet1_Tabular/threads:%int\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bar\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet1_Tabular/threads:%int\",%csv_report," + "%float,,%float,%float,,"}}); +// VS2013 does not allow this function to be passed as a lambda argument +// to CHECK_BENCHMARK_RESULTS() +void CheckSet1(Results const& e) { + CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 15); + CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 25); + CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 45); +} +CHECK_BENCHMARK_RESULTS("BM_CounterSet1_Tabular/threads:%int", &CheckSet1); + +// ========================================================================= // +// ------------------------- Tabular Counters Output ----------------------- // +// ========================================================================= // + +// set only some of the counters, different set now. +void BM_CounterSet2_Tabular(benchmark::State& state) { + for (auto _ : state) { + } + namespace bm = benchmark; + state.counters.insert({ + {"Foo", {10, bm::Counter::kAvgThreads}}, + {"Bat", {30, bm::Counter::kAvgThreads}}, + {"Baz", {40, bm::Counter::kAvgThreads}}, + }); +} +BENCHMARK(BM_CounterSet2_Tabular)->ThreadRange(1, 16); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_CounterSet2_Tabular/threads:%int\",$"}, + {"\"family_index\": 4,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_CounterSet2_Tabular/threads:%int\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"Bat\": %float,$", MR_Next}, + {"\"Baz\": %float,$", MR_Next}, + {"\"Foo\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet2_Tabular/threads:%int\",%csv_report," + ",%float,%float,%float,,"}}); +// VS2013 does not allow this function to be passed as a lambda argument +// to CHECK_BENCHMARK_RESULTS() +void CheckSet2(Results const& e) { + CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); + CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 30); + CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); +} +CHECK_BENCHMARK_RESULTS("BM_CounterSet2_Tabular", &CheckSet2); + +// ========================================================================= // +// --------------------------- TEST CASES END ------------------------------ // +// ========================================================================= // + +int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/thirdparty_builtin/benchmark-1.5.0/test/user_counters_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/user_counters_test.cc similarity index 74% rename from thirdparty_builtin/benchmark-1.5.0/test/user_counters_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/user_counters_test.cc index 0775bc01f..4cd8ee373 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/user_counters_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/user_counters_test.cc @@ -26,15 +26,17 @@ void BM_Counters_Simple(benchmark::State& state) { for (auto _ : state) { } state.counters["foo"] = 1; - state.counters["bar"] = 2 * (double)state.iterations(); + state.counters["bar"] = 2 * static_cast(state.iterations()); } BENCHMARK(BM_Counters_Simple); ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_Simple %console_report bar=%hrfloat foo=%hrfloat$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Simple\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Simple\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -64,6 +66,9 @@ int num_calls1 = 0; } void BM_Counters_WithBytesAndItemsPSec(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } state.counters["foo"] = 1; state.counters["bar"] = ++num_calls1; @@ -76,9 +81,11 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_WithBytesAndItemsPSec %console_report " "foo=%hrfloat items_per_second=%hrfloat/s$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_WithBytesAndItemsPSec\",$"}, + {"\"family_index\": 1,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_WithBytesAndItemsPSec\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -111,6 +118,9 @@ CHECK_BENCHMARK_RESULTS("BM_Counters_WithBytesAndItemsPSec", void BM_Counters_Rate(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } namespace bm = benchmark; state.counters["foo"] = bm::Counter{1, bm::Counter::kIsRate}; @@ -121,9 +131,11 @@ ADD_CASES( TC_ConsoleOut, {{"^BM_Counters_Rate %console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Rate\",$"}, + {"\"family_index\": 2,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Rate\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -144,6 +156,94 @@ void CheckRate(Results const& e) { } CHECK_BENCHMARK_RESULTS("BM_Counters_Rate", &CheckRate); +// ========================================================================= // +// ----------------------- Inverted Counters Output ------------------------ // +// ========================================================================= // + +void BM_Invert(benchmark::State& state) { + for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); + } + namespace bm = benchmark; + state.counters["foo"] = bm::Counter{0.0001, bm::Counter::kInvert}; + state.counters["bar"] = bm::Counter{10000, bm::Counter::kInvert}; +} +BENCHMARK(BM_Invert); +ADD_CASES(TC_ConsoleOut, + {{"^BM_Invert %console_report bar=%hrfloatu foo=%hrfloatk$"}}); +ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Invert\",$"}, + {"\"family_index\": 3,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Invert\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"bar\": %float,$", MR_Next}, + {"\"foo\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, {{"^\"BM_Invert\",%csv_report,%float,%float$"}}); +// VS2013 does not allow this function to be passed as a lambda argument +// to CHECK_BENCHMARK_RESULTS() +void CheckInvert(Results const& e) { + CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, 10000, 0.0001); + CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 0.0001, 0.0001); +} +CHECK_BENCHMARK_RESULTS("BM_Invert", &CheckInvert); + +// ========================================================================= // +// --------------------- InvertedRate Counters Output ---------------------- // +// ========================================================================= // + +void BM_Counters_InvertedRate(benchmark::State& state) { + for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); + } + namespace bm = benchmark; + state.counters["foo"] = + bm::Counter{1, bm::Counter::kIsRate | bm::Counter::kInvert}; + state.counters["bar"] = + bm::Counter{8192, bm::Counter::kIsRate | bm::Counter::kInvert}; +} +BENCHMARK(BM_Counters_InvertedRate); +ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_InvertedRate %console_report " + "bar=%hrfloats foo=%hrfloats$"}}); +ADD_CASES(TC_JSONOut, + {{"\"name\": \"BM_Counters_InvertedRate\",$"}, + {"\"family_index\": 4,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, + {"\"run_name\": \"BM_Counters_InvertedRate\",$", MR_Next}, + {"\"run_type\": \"iteration\",$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, + {"\"repetition_index\": 0,$", MR_Next}, + {"\"threads\": 1,$", MR_Next}, + {"\"iterations\": %int,$", MR_Next}, + {"\"real_time\": %float,$", MR_Next}, + {"\"cpu_time\": %float,$", MR_Next}, + {"\"time_unit\": \"ns\",$", MR_Next}, + {"\"bar\": %float,$", MR_Next}, + {"\"foo\": %float$", MR_Next}, + {"}", MR_Next}}); +ADD_CASES(TC_CSVOut, + {{"^\"BM_Counters_InvertedRate\",%csv_report,%float,%float$"}}); +// VS2013 does not allow this function to be passed as a lambda argument +// to CHECK_BENCHMARK_RESULTS() +void CheckInvertedRate(Results const& e) { + double t = e.DurationCPUTime(); // this (and not real time) is the time used + // check that the values are within 0.1% of the expected values + CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, t, 0.001); + CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, t / 8192.0, 0.001); +} +CHECK_BENCHMARK_RESULTS("BM_Counters_InvertedRate", &CheckInvertedRate); + // ========================================================================= // // ------------------------- Thread Counters Output ------------------------ // // ========================================================================= // @@ -159,9 +259,11 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_Threads/threads:%int %console_report " "bar=%hrfloat foo=%hrfloat$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Threads/threads:%int\",$"}, + {"\"family_index\": 5,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Threads/threads:%int\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -198,9 +300,11 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgThreads/threads:%int " "%console_report bar=%hrfloat foo=%hrfloat$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_AvgThreads/threads:%int\",$"}, + {"\"family_index\": 6,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_AvgThreads/threads:%int\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -228,6 +332,9 @@ CHECK_BENCHMARK_RESULTS("BM_Counters_AvgThreads/threads:%int", void BM_Counters_AvgThreadsRate(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } namespace bm = benchmark; state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgThreadsRate}; @@ -238,10 +345,12 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgThreadsRate/threads:%int " "%console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_AvgThreadsRate/threads:%int\",$"}, + {"\"family_index\": 7,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_AvgThreadsRate/threads:%int\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -278,9 +387,11 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_IterationInvariant %console_report " "bar=%hrfloat foo=%hrfloat$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_IterationInvariant\",$"}, + {"\"family_index\": 8,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_IterationInvariant\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -309,6 +420,9 @@ CHECK_BENCHMARK_RESULTS("BM_Counters_IterationInvariant", void BM_Counters_kIsIterationInvariantRate(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } namespace bm = benchmark; state.counters["foo"] = @@ -321,10 +435,12 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_kIsIterationInvariantRate " "%console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_kIsIterationInvariantRate\",$"}, + {"\"family_index\": 9,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_kIsIterationInvariantRate\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -349,7 +465,7 @@ CHECK_BENCHMARK_RESULTS("BM_Counters_kIsIterationInvariantRate", &CheckIsIterationInvariantRate); // ========================================================================= // -// ------------------- AvgIterations Counters Output ------------------ // +// --------------------- AvgIterations Counters Output --------------------- // // ========================================================================= // void BM_Counters_AvgIterations(benchmark::State& state) { @@ -364,9 +480,11 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgIterations %console_report " "bar=%hrfloat foo=%hrfloat$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_AvgIterations\",$"}, + {"\"family_index\": 10,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_AvgIterations\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, @@ -389,11 +507,14 @@ void CheckAvgIterations(Results const& e) { CHECK_BENCHMARK_RESULTS("BM_Counters_AvgIterations", &CheckAvgIterations); // ========================================================================= // -// ----------------- AvgIterationsRate Counters Output ---------------- // +// ------------------- AvgIterationsRate Counters Output ------------------- // // ========================================================================= // void BM_Counters_kAvgIterationsRate(benchmark::State& state) { for (auto _ : state) { + // This test requires a non-zero CPU time to avoid divide-by-zero + auto iterations = state.iterations(); + benchmark::DoNotOptimize(iterations); } namespace bm = benchmark; state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgIterationsRate}; @@ -405,9 +526,11 @@ ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_kAvgIterationsRate " "%console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_kAvgIterationsRate\",$"}, + {"\"family_index\": 11,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_kAvgIterationsRate\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, + {"\"repetitions\": 1,$", MR_Next}, {"\"repetition_index\": 0,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"iterations\": %int,$", MR_Next}, diff --git a/thirdparty_builtin/benchmark-1.5.0/test/user_counters_thousands_test.cc b/thirdparty_builtin/benchmark-1.8.0/test/user_counters_thousands_test.cc similarity index 92% rename from thirdparty_builtin/benchmark-1.5.0/test/user_counters_thousands_test.cc rename to thirdparty_builtin/benchmark-1.8.0/test/user_counters_thousands_test.cc index 21d8285de..a42683b32 100644 --- a/thirdparty_builtin/benchmark-1.5.0/test/user_counters_thousands_test.cc +++ b/thirdparty_builtin/benchmark-1.8.0/test/user_counters_thousands_test.cc @@ -51,6 +51,8 @@ ADD_CASES( }); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Thousands/repeats:2\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, @@ -68,6 +70,8 @@ ADD_CASES(TC_JSONOut, {"}", MR_Next}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Thousands/repeats:2\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, {"\"run_type\": \"iteration\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, @@ -85,11 +89,14 @@ ADD_CASES(TC_JSONOut, {"}", MR_Next}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Thousands/repeats:2_mean\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"mean\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}, {"\"real_time\": %float,$", MR_Next}, {"\"cpu_time\": %float,$", MR_Next}, @@ -102,11 +109,14 @@ ADD_CASES(TC_JSONOut, {"}", MR_Next}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Thousands/repeats:2_median\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"median\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}, {"\"real_time\": %float,$", MR_Next}, {"\"cpu_time\": %float,$", MR_Next}, @@ -119,11 +129,14 @@ ADD_CASES(TC_JSONOut, {"}", MR_Next}}); ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Thousands/repeats:2_stddev\",$"}, + {"\"family_index\": 0,$", MR_Next}, + {"\"per_family_instance_index\": 0,$", MR_Next}, {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, {"\"run_type\": \"aggregate\",$", MR_Next}, {"\"repetitions\": 2,$", MR_Next}, {"\"threads\": 1,$", MR_Next}, {"\"aggregate_name\": \"stddev\",$", MR_Next}, + {"\"aggregate_unit\": \"time\",$", MR_Next}, {"\"iterations\": 2,$", MR_Next}, {"\"real_time\": %float,$", MR_Next}, {"\"cpu_time\": %float,$", MR_Next}, diff --git a/thirdparty_builtin/benchmark-1.8.0/tools/BUILD.bazel b/thirdparty_builtin/benchmark-1.8.0/tools/BUILD.bazel new file mode 100644 index 000000000..5895883a2 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/tools/BUILD.bazel @@ -0,0 +1,19 @@ +load("@py_deps//:requirements.bzl", "requirement") + +py_library( + name = "gbench", + srcs = glob(["gbench/*.py"]), + deps = [ + requirement("numpy"), + requirement("scipy"), + ], +) + +py_binary( + name = "compare", + srcs = ["compare.py"], + python_version = "PY2", + deps = [ + ":gbench", + ], +) diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/compare.py b/thirdparty_builtin/benchmark-1.8.0/tools/compare.py similarity index 89% rename from thirdparty_builtin/benchmark-1.5.0/tools/compare.py rename to thirdparty_builtin/benchmark-1.8.0/tools/compare.py index 539ace6fb..e5eeb247e 100755 --- a/thirdparty_builtin/benchmark-1.5.0/tools/compare.py +++ b/thirdparty_builtin/benchmark-1.8.0/tools/compare.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import unittest """ @@ -7,26 +7,30 @@ import argparse from argparse import ArgumentParser +import json import sys +import os import gbench from gbench import util, report -from gbench.util import * def check_inputs(in1, in2, flags): """ Perform checking on the user provided inputs and diagnose any abnormalities """ - in1_kind, in1_err = classify_input_file(in1) - in2_kind, in2_err = classify_input_file(in2) - output_file = find_benchmark_flag('--benchmark_out=', flags) - output_type = find_benchmark_flag('--benchmark_out_format=', flags) - if in1_kind == IT_Executable and in2_kind == IT_Executable and output_file: + in1_kind, in1_err = util.classify_input_file(in1) + in2_kind, in2_err = util.classify_input_file(in2) + output_file = util.find_benchmark_flag('--benchmark_out=', flags) + output_type = util.find_benchmark_flag('--benchmark_out_format=', flags) + if in1_kind == util.IT_Executable and in2_kind == util.IT_Executable and output_file: print(("WARNING: '--benchmark_out=%s' will be passed to both " "benchmarks causing it to be overwritten") % output_file) - if in1_kind == IT_JSON and in2_kind == IT_JSON and len(flags) > 0: - print("WARNING: passing optional flags has no effect since both " - "inputs are JSON") + if in1_kind == util.IT_JSON and in2_kind == util.IT_JSON: + # When both sides are JSON the only supported flag is + # --benchmark_filter= + for flag in util.remove_benchmark_flags('--benchmark_filter=', flags): + print("WARNING: passing %s has no effect since both " + "inputs are JSON" % flag) if output_type is not None and output_type != 'json': print(("ERROR: passing '--benchmark_out_format=%s' to 'compare.py`" " is not supported.") % output_type) @@ -48,6 +52,20 @@ def create_parser(): "of repetitions. Do note that only the display is affected. " "Internally, all the actual runs are still used, e.g. for U test.") + parser.add_argument( + '--no-color', + dest='color', + default=True, + action="store_false", + help="Do not use colors in the terminal output" + ) + + parser.add_argument( + '-d', + '--dump_to_json', + dest='dump_to_json', + help="Additionally, dump benchmark comparison output to this file in JSON format.") + utest = parser.add_argument_group() utest.add_argument( '--no-utest', @@ -223,10 +241,10 @@ def main(): options_contender = ['--benchmark_filter=%s' % filter_contender] # Run the benchmarks and report the results - json1 = json1_orig = gbench.util.run_or_load_benchmark( - test_baseline, benchmark_options + options_baseline) - json2 = json2_orig = gbench.util.run_or_load_benchmark( - test_contender, benchmark_options + options_contender) + json1 = json1_orig = gbench.util.sort_benchmark_results(gbench.util.run_or_load_benchmark( + test_baseline, benchmark_options + options_baseline)) + json2 = json2_orig = gbench.util.sort_benchmark_results(gbench.util.run_or_load_benchmark( + test_contender, benchmark_options + options_contender)) # Now, filter the benchmarks so that the difference report can work if filter_baseline and filter_contender: @@ -236,14 +254,20 @@ def main(): json2 = gbench.report.filter_benchmark( json2_orig, filter_contender, replacement) - # Diff and output - output_lines = gbench.report.generate_difference_report( - json1, json2, args.display_aggregates_only, - args.utest, args.utest_alpha) + diff_report = gbench.report.get_difference_report( + json1, json2, args.utest) + output_lines = gbench.report.print_difference_report( + diff_report, + args.display_aggregates_only, + args.utest, args.utest_alpha, args.color) print(description) for ln in output_lines: print(ln) + # Optionally, diff and output to JSON + if args.dump_to_json is not None: + with open(args.dump_to_json, 'w') as f_json: + json.dump(diff_report, f_json) class TestParser(unittest.TestCase): def setUp(self): diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test1_run1.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test1_run1.json similarity index 94% rename from thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test1_run1.json rename to thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test1_run1.json index 601e327ae..9daed0bcc 100644 --- a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test1_run1.json +++ b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test1_run1.json @@ -114,6 +114,14 @@ "real_time": 1, "cpu_time": 1, "time_unit": "s" + }, + { + "name": "BM_hasLabel", + "label": "a label", + "iterations": 1, + "real_time": 1, + "cpu_time": 1, + "time_unit": "s" } ] } diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test1_run2.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test1_run2.json similarity index 94% rename from thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test1_run2.json rename to thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test1_run2.json index 3cbcf39b0..dc52970ab 100644 --- a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test1_run2.json +++ b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test1_run2.json @@ -114,6 +114,14 @@ "real_time": 1, "cpu_time": 1, "time_unit": "ns" + }, + { + "name": "BM_hasLabel", + "label": "a label", + "iterations": 1, + "real_time": 1, + "cpu_time": 1, + "time_unit": "s" } ] } diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test2_run.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test2_run.json similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test2_run.json rename to thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test2_run.json diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test3_run0.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test3_run0.json similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test3_run0.json rename to thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test3_run0.json diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test3_run1.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test3_run1.json similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/tools/gbench/Inputs/test3_run1.json rename to thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test3_run1.json diff --git a/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run.json new file mode 100644 index 000000000..eaa005f3a --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run.json @@ -0,0 +1,96 @@ +{ + "benchmarks": [ + { + "name": "99 family 0 instance 0 repetition 0", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 0, + "repetition_index": 0 + }, + { + "name": "98 family 0 instance 0 repetition 1", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 0, + "repetition_index": 1 + }, + { + "name": "97 family 0 instance 0 aggregate", + "run_type": "aggregate", + "family_index": 0, + "per_family_instance_index": 0, + "aggregate_name": "9 aggregate" + }, + + + { + "name": "96 family 0 instance 1 repetition 0", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 1, + "repetition_index": 0 + }, + { + "name": "95 family 0 instance 1 repetition 1", + "run_type": "iteration", + "family_index": 0, + "per_family_instance_index": 1, + "repetition_index": 1 + }, + { + "name": "94 family 0 instance 1 aggregate", + "run_type": "aggregate", + "family_index": 0, + "per_family_instance_index": 1, + "aggregate_name": "9 aggregate" + }, + + + + + { + "name": "93 family 1 instance 0 repetition 0", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 0, + "repetition_index": 0 + }, + { + "name": "92 family 1 instance 0 repetition 1", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 0, + "repetition_index": 1 + }, + { + "name": "91 family 1 instance 0 aggregate", + "run_type": "aggregate", + "family_index": 1, + "per_family_instance_index": 0, + "aggregate_name": "9 aggregate" + }, + + + { + "name": "90 family 1 instance 1 repetition 0", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 1, + "repetition_index": 0 + }, + { + "name": "89 family 1 instance 1 repetition 1", + "run_type": "iteration", + "family_index": 1, + "per_family_instance_index": 1, + "repetition_index": 1 + }, + { + "name": "88 family 1 instance 1 aggregate", + "run_type": "aggregate", + "family_index": 1, + "per_family_instance_index": 1, + "aggregate_name": "9 aggregate" + } + ] +} diff --git a/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run0.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run0.json new file mode 100644 index 000000000..54cf12758 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run0.json @@ -0,0 +1,21 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "whocares", + "run_type": "aggregate", + "aggregate_name": "zz", + "aggregate_unit": "percentage", + "iterations": 1000, + "real_time": 0.01, + "cpu_time": 0.10, + "time_unit": "ns" + } + ] +} diff --git a/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run1.json b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run1.json new file mode 100644 index 000000000..25d56050c --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/Inputs/test4_run1.json @@ -0,0 +1,21 @@ +{ + "context": { + "date": "2016-08-02 17:44:46", + "num_cpus": 4, + "mhz_per_cpu": 4228, + "cpu_scaling_enabled": false, + "library_build_type": "release" + }, + "benchmarks": [ + { + "name": "whocares", + "run_type": "aggregate", + "aggregate_name": "zz", + "aggregate_unit": "percentage", + "iterations": 1000, + "real_time": 0.005, + "cpu_time": 0.15, + "time_unit": "ns" + } + ] +} diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/__init__.py b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/__init__.py similarity index 100% rename from thirdparty_builtin/benchmark-1.5.0/tools/gbench/__init__.py rename to thirdparty_builtin/benchmark-1.8.0/tools/gbench/__init__.py diff --git a/thirdparty_builtin/benchmark-1.8.0/tools/gbench/report.py b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/report.py new file mode 100644 index 000000000..b2bbfb9f6 --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/report.py @@ -0,0 +1,1201 @@ +"""report.py - Utilities for reporting statistics about benchmark results +""" + +import unittest +import os +import re +import copy +import random + +from scipy.stats import mannwhitneyu, gmean +from numpy import array + + +class BenchmarkColor(object): + def __init__(self, name, code): + self.name = name + self.code = code + + def __repr__(self): + return '%s%r' % (self.__class__.__name__, + (self.name, self.code)) + + def __format__(self, format): + return self.code + + +# Benchmark Colors Enumeration +BC_NONE = BenchmarkColor('NONE', '') +BC_MAGENTA = BenchmarkColor('MAGENTA', '\033[95m') +BC_CYAN = BenchmarkColor('CYAN', '\033[96m') +BC_OKBLUE = BenchmarkColor('OKBLUE', '\033[94m') +BC_OKGREEN = BenchmarkColor('OKGREEN', '\033[32m') +BC_HEADER = BenchmarkColor('HEADER', '\033[92m') +BC_WARNING = BenchmarkColor('WARNING', '\033[93m') +BC_WHITE = BenchmarkColor('WHITE', '\033[97m') +BC_FAIL = BenchmarkColor('FAIL', '\033[91m') +BC_ENDC = BenchmarkColor('ENDC', '\033[0m') +BC_BOLD = BenchmarkColor('BOLD', '\033[1m') +BC_UNDERLINE = BenchmarkColor('UNDERLINE', '\033[4m') + +UTEST_MIN_REPETITIONS = 2 +UTEST_OPTIMAL_REPETITIONS = 9 # Lowest reasonable number, More is better. +UTEST_COL_NAME = "_pvalue" + +_TIME_UNIT_TO_SECONDS_MULTIPLIER = { + "s": 1.0, + "ms": 1e-3, + "us": 1e-6, + "ns": 1e-9, +} + + +def color_format(use_color, fmt_str, *args, **kwargs): + """ + Return the result of 'fmt_str.format(*args, **kwargs)' after transforming + 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' + is False then all color codes in 'args' and 'kwargs' are replaced with + the empty string. + """ + assert use_color is True or use_color is False + if not use_color: + args = [arg if not isinstance(arg, BenchmarkColor) else BC_NONE + for arg in args] + kwargs = {key: arg if not isinstance(arg, BenchmarkColor) else BC_NONE + for key, arg in kwargs.items()} + return fmt_str.format(*args, **kwargs) + + +def find_longest_name(benchmark_list): + """ + Return the length of the longest benchmark name in a given list of + benchmark JSON objects + """ + longest_name = 1 + for bc in benchmark_list: + if len(bc['name']) > longest_name: + longest_name = len(bc['name']) + return longest_name + + +def calculate_change(old_val, new_val): + """ + Return a float representing the decimal change between old_val and new_val. + """ + if old_val == 0 and new_val == 0: + return 0.0 + if old_val == 0: + return float(new_val - old_val) / (float(old_val + new_val) / 2) + return float(new_val - old_val) / abs(old_val) + + +def filter_benchmark(json_orig, family, replacement=""): + """ + Apply a filter to the json, and only leave the 'family' of benchmarks. + """ + regex = re.compile(family) + filtered = {} + filtered['benchmarks'] = [] + for be in json_orig['benchmarks']: + if not regex.search(be['name']): + continue + filteredbench = copy.deepcopy(be) # Do NOT modify the old name! + filteredbench['name'] = regex.sub(replacement, filteredbench['name']) + filtered['benchmarks'].append(filteredbench) + return filtered + + +def get_unique_benchmark_names(json): + """ + While *keeping* the order, give all the unique 'names' used for benchmarks. + """ + seen = set() + uniqued = [x['name'] for x in json['benchmarks'] + if x['name'] not in seen and + (seen.add(x['name']) or True)] + return uniqued + + +def intersect(list1, list2): + """ + Given two lists, get a new list consisting of the elements only contained + in *both of the input lists*, while preserving the ordering. + """ + return [x for x in list1 if x in list2] + + +def is_potentially_comparable_benchmark(x): + return ('time_unit' in x and 'real_time' in x and 'cpu_time' in x) + + +def partition_benchmarks(json1, json2): + """ + While preserving the ordering, find benchmarks with the same names in + both of the inputs, and group them. + (i.e. partition/filter into groups with common name) + """ + json1_unique_names = get_unique_benchmark_names(json1) + json2_unique_names = get_unique_benchmark_names(json2) + names = intersect(json1_unique_names, json2_unique_names) + partitions = [] + for name in names: + time_unit = None + # Pick the time unit from the first entry of the lhs benchmark. + # We should be careful not to crash with unexpected input. + for x in json1['benchmarks']: + if (x['name'] == name and is_potentially_comparable_benchmark(x)): + time_unit = x['time_unit'] + break + if time_unit is None: + continue + # Filter by name and time unit. + # All the repetitions are assumed to be comparable. + lhs = [x for x in json1['benchmarks'] if x['name'] == name and + x['time_unit'] == time_unit] + rhs = [x for x in json2['benchmarks'] if x['name'] == name and + x['time_unit'] == time_unit] + partitions.append([lhs, rhs]) + return partitions + + +def get_timedelta_field_as_seconds(benchmark, field_name): + """ + Get value of field_name field of benchmark, which is time with time unit + time_unit, as time in seconds. + """ + timedelta = benchmark[field_name] + time_unit = benchmark.get('time_unit', 's') + return timedelta * _TIME_UNIT_TO_SECONDS_MULTIPLIER.get(time_unit) + + +def calculate_geomean(json): + """ + Extract all real/cpu times from all the benchmarks as seconds, + and calculate their geomean. + """ + times = [] + for benchmark in json['benchmarks']: + if 'run_type' in benchmark and benchmark['run_type'] == 'aggregate': + continue + times.append([get_timedelta_field_as_seconds(benchmark, 'real_time'), + get_timedelta_field_as_seconds(benchmark, 'cpu_time')]) + return gmean(times) if times else array([]) + + +def extract_field(partition, field_name): + # The count of elements may be different. We want *all* of them. + lhs = [x[field_name] for x in partition[0]] + rhs = [x[field_name] for x in partition[1]] + return [lhs, rhs] + + +def calc_utest(timings_cpu, timings_time): + min_rep_cnt = min(len(timings_time[0]), + len(timings_time[1]), + len(timings_cpu[0]), + len(timings_cpu[1])) + + # Does *everything* has at least UTEST_MIN_REPETITIONS repetitions? + if min_rep_cnt < UTEST_MIN_REPETITIONS: + return False, None, None + + time_pvalue = mannwhitneyu( + timings_time[0], timings_time[1], alternative='two-sided').pvalue + cpu_pvalue = mannwhitneyu( + timings_cpu[0], timings_cpu[1], alternative='two-sided').pvalue + + return (min_rep_cnt >= UTEST_OPTIMAL_REPETITIONS), cpu_pvalue, time_pvalue + + +def print_utest(bc_name, utest, utest_alpha, first_col_width, use_color=True): + def get_utest_color(pval): + return BC_FAIL if pval >= utest_alpha else BC_OKGREEN + + # Check if we failed miserably with minimum required repetitions for utest + if not utest['have_optimal_repetitions'] and utest['cpu_pvalue'] is None and utest['time_pvalue'] is None: + return [] + + dsc = "U Test, Repetitions: {} vs {}".format( + utest['nr_of_repetitions'], utest['nr_of_repetitions_other']) + dsc_color = BC_OKGREEN + + # We still got some results to show but issue a warning about it. + if not utest['have_optimal_repetitions']: + dsc_color = BC_WARNING + dsc += ". WARNING: Results unreliable! {}+ repetitions recommended.".format( + UTEST_OPTIMAL_REPETITIONS) + + special_str = "{}{:<{}s}{endc}{}{:16.4f}{endc}{}{:16.4f}{endc}{} {}" + + return [color_format(use_color, + special_str, + BC_HEADER, + "{}{}".format(bc_name, UTEST_COL_NAME), + first_col_width, + get_utest_color( + utest['time_pvalue']), utest['time_pvalue'], + get_utest_color( + utest['cpu_pvalue']), utest['cpu_pvalue'], + dsc_color, dsc, + endc=BC_ENDC)] + + +def get_difference_report( + json1, + json2, + utest=False): + """ + Calculate and report the difference between each test of two benchmarks + runs specified as 'json1' and 'json2'. Output is another json containing + relevant details for each test run. + """ + assert utest is True or utest is False + + diff_report = [] + partitions = partition_benchmarks(json1, json2) + for partition in partitions: + benchmark_name = partition[0][0]['name'] + label = partition[0][0]['label'] if 'label' in partition[0][0] else '' + time_unit = partition[0][0]['time_unit'] + measurements = [] + utest_results = {} + # Careful, we may have different repetition count. + for i in range(min(len(partition[0]), len(partition[1]))): + bn = partition[0][i] + other_bench = partition[1][i] + measurements.append({ + 'real_time': bn['real_time'], + 'cpu_time': bn['cpu_time'], + 'real_time_other': other_bench['real_time'], + 'cpu_time_other': other_bench['cpu_time'], + 'time': calculate_change(bn['real_time'], other_bench['real_time']), + 'cpu': calculate_change(bn['cpu_time'], other_bench['cpu_time']) + }) + + # After processing the whole partition, if requested, do the U test. + if utest: + timings_cpu = extract_field(partition, 'cpu_time') + timings_time = extract_field(partition, 'real_time') + have_optimal_repetitions, cpu_pvalue, time_pvalue = calc_utest( + timings_cpu, timings_time) + if cpu_pvalue and time_pvalue: + utest_results = { + 'have_optimal_repetitions': have_optimal_repetitions, + 'cpu_pvalue': cpu_pvalue, + 'time_pvalue': time_pvalue, + 'nr_of_repetitions': len(timings_cpu[0]), + 'nr_of_repetitions_other': len(timings_cpu[1]) + } + + # Store only if we had any measurements for given benchmark. + # E.g. partition_benchmarks will filter out the benchmarks having + # time units which are not compatible with other time units in the + # benchmark suite. + if measurements: + run_type = partition[0][0]['run_type'] if 'run_type' in partition[0][0] else '' + aggregate_name = partition[0][0]['aggregate_name'] if run_type == 'aggregate' and 'aggregate_name' in partition[0][0] else '' + diff_report.append({ + 'name': benchmark_name, + 'label': label, + 'measurements': measurements, + 'time_unit': time_unit, + 'run_type': run_type, + 'aggregate_name': aggregate_name, + 'utest': utest_results + }) + + lhs_gmean = calculate_geomean(json1) + rhs_gmean = calculate_geomean(json2) + if lhs_gmean.any() and rhs_gmean.any(): + diff_report.append({ + 'name': 'OVERALL_GEOMEAN', + 'label': '', + 'measurements': [{ + 'real_time': lhs_gmean[0], + 'cpu_time': lhs_gmean[1], + 'real_time_other': rhs_gmean[0], + 'cpu_time_other': rhs_gmean[1], + 'time': calculate_change(lhs_gmean[0], rhs_gmean[0]), + 'cpu': calculate_change(lhs_gmean[1], rhs_gmean[1]) + }], + 'time_unit': 's', + 'run_type': 'aggregate', + 'aggregate_name': 'geomean', + 'utest': {} + }) + + return diff_report + + +def print_difference_report( + json_diff_report, + include_aggregates_only=False, + utest=False, + utest_alpha=0.05, + use_color=True): + """ + Calculate and report the difference between each test of two benchmarks + runs specified as 'json1' and 'json2'. + """ + assert utest is True or utest is False + + def get_color(res): + if res > 0.05: + return BC_FAIL + elif res > -0.07: + return BC_WHITE + else: + return BC_CYAN + + first_col_width = find_longest_name(json_diff_report) + first_col_width = max( + first_col_width, + len('Benchmark')) + first_col_width += len(UTEST_COL_NAME) + first_line = "{:<{}s}Time CPU Time Old Time New CPU Old CPU New".format( + 'Benchmark', 12 + first_col_width) + output_strs = [first_line, '-' * len(first_line)] + + fmt_str = "{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}" + for benchmark in json_diff_report: + # *If* we were asked to only include aggregates, + # and if it is non-aggregate, then don't print it. + if not include_aggregates_only or not 'run_type' in benchmark or benchmark['run_type'] == 'aggregate': + for measurement in benchmark['measurements']: + output_strs += [color_format(use_color, + fmt_str, + BC_HEADER, + benchmark['name'], + first_col_width, + get_color(measurement['time']), + measurement['time'], + get_color(measurement['cpu']), + measurement['cpu'], + measurement['real_time'], + measurement['real_time_other'], + measurement['cpu_time'], + measurement['cpu_time_other'], + endc=BC_ENDC)] + + # After processing the measurements, if requested and + # if applicable (e.g. u-test exists for given benchmark), + # print the U test. + if utest and benchmark['utest']: + output_strs += print_utest(benchmark['name'], + benchmark['utest'], + utest_alpha=utest_alpha, + first_col_width=first_col_width, + use_color=use_color) + + return output_strs + + +############################################################################### +# Unit tests + + +class TestGetUniqueBenchmarkNames(unittest.TestCase): + def load_results(self): + import json + testInputs = os.path.join( + os.path.dirname( + os.path.realpath(__file__)), + 'Inputs') + testOutput = os.path.join(testInputs, 'test3_run0.json') + with open(testOutput, 'r') as f: + json = json.load(f) + return json + + def test_basic(self): + expect_lines = [ + 'BM_One', + 'BM_Two', + 'short', # These two are not sorted + 'medium', # These two are not sorted + ] + json = self.load_results() + output_lines = get_unique_benchmark_names(json) + print("\n") + print("\n".join(output_lines)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + self.assertEqual(expect_lines[i], output_lines[i]) + + +class TestReportDifference(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_results(): + import json + testInputs = os.path.join( + os.path.dirname( + os.path.realpath(__file__)), + 'Inputs') + testOutput1 = os.path.join(testInputs, 'test1_run1.json') + testOutput2 = os.path.join(testInputs, 'test1_run2.json') + with open(testOutput1, 'r') as f: + json1 = json.load(f) + with open(testOutput2, 'r') as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report(json1, json2) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ['BM_SameTimes', '+0.0000', '+0.0000', '10', '10', '10', '10'], + ['BM_2xFaster', '-0.5000', '-0.5000', '50', '25', '50', '25'], + ['BM_2xSlower', '+1.0000', '+1.0000', '50', '100', '50', '100'], + ['BM_1PercentFaster', '-0.0100', '-0.0100', '100', '99', '100', '99'], + ['BM_1PercentSlower', '+0.0100', '+0.0100', '100', '101', '100', '101'], + ['BM_10PercentFaster', '-0.1000', '-0.1000', '100', '90', '100', '90'], + ['BM_10PercentSlower', '+0.1000', '+0.1000', '100', '110', '100', '110'], + ['BM_100xSlower', '+99.0000', '+99.0000', + '100', '10000', '100', '10000'], + ['BM_100xFaster', '-0.9900', '-0.9900', + '10000', '100', '10000', '100'], + ['BM_10PercentCPUToTime', '+0.1000', + '-0.1000', '100', '110', '100', '90'], + ['BM_ThirdFaster', '-0.3333', '-0.3334', '100', '67', '100', '67'], + ['BM_NotBadTimeUnit', '-0.9000', '+0.2000', '0', '0', '0', '1'], + ['BM_hasLabel', '+0.0000', '+0.0000', '1', '1', '1', '1'], + ['OVERALL_GEOMEAN', '-0.8113', '-0.7779', '0', '0', '0', '0'] + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, use_color=False) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(' ') if x] + self.assertEqual(len(parts), 7) + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report_output(self): + expected_output = [ + { + 'name': 'BM_SameTimes', + 'label': '', + 'measurements': [{'time': 0.0000, 'cpu': 0.0000, + 'real_time': 10, 'real_time_other': 10, + 'cpu_time': 10, 'cpu_time_other': 10}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_2xFaster', + 'label': '', + 'measurements': [{'time': -0.5000, 'cpu': -0.5000, + 'real_time': 50, 'real_time_other': 25, + 'cpu_time': 50, 'cpu_time_other': 25}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_2xSlower', + 'label': '', + 'measurements': [{'time': 1.0000, 'cpu': 1.0000, + 'real_time': 50, 'real_time_other': 100, + 'cpu_time': 50, 'cpu_time_other': 100}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_1PercentFaster', + 'label': '', + 'measurements': [{'time': -0.0100, 'cpu': -0.0100, + 'real_time': 100, 'real_time_other': 98.9999999, + 'cpu_time': 100, 'cpu_time_other': 98.9999999}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_1PercentSlower', + 'label': '', + 'measurements': [{'time': 0.0100, 'cpu': 0.0100, + 'real_time': 100, 'real_time_other': 101, + 'cpu_time': 100, 'cpu_time_other': 101}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_10PercentFaster', + 'label': '', + 'measurements': [{'time': -0.1000, 'cpu': -0.1000, + 'real_time': 100, 'real_time_other': 90, + 'cpu_time': 100, 'cpu_time_other': 90}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_10PercentSlower', + 'label': '', + 'measurements': [{'time': 0.1000, 'cpu': 0.1000, + 'real_time': 100, 'real_time_other': 110, + 'cpu_time': 100, 'cpu_time_other': 110}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_100xSlower', + 'label': '', + 'measurements': [{'time': 99.0000, 'cpu': 99.0000, + 'real_time': 100, 'real_time_other': 10000, + 'cpu_time': 100, 'cpu_time_other': 10000}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_100xFaster', + 'label': '', + 'measurements': [{'time': -0.9900, 'cpu': -0.9900, + 'real_time': 10000, 'real_time_other': 100, + 'cpu_time': 10000, 'cpu_time_other': 100}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_10PercentCPUToTime', + 'label': '', + 'measurements': [{'time': 0.1000, 'cpu': -0.1000, + 'real_time': 100, 'real_time_other': 110, + 'cpu_time': 100, 'cpu_time_other': 90}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_ThirdFaster', + 'label': '', + 'measurements': [{'time': -0.3333, 'cpu': -0.3334, + 'real_time': 100, 'real_time_other': 67, + 'cpu_time': 100, 'cpu_time_other': 67}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'BM_NotBadTimeUnit', + 'label': '', + 'measurements': [{'time': -0.9000, 'cpu': 0.2000, + 'real_time': 0.4, 'real_time_other': 0.04, + 'cpu_time': 0.5, 'cpu_time_other': 0.6}], + 'time_unit': 's', + 'utest': {} + }, + { + 'name': 'BM_hasLabel', + 'label': 'a label', + 'measurements': [{'time': 0.0000, 'cpu': 0.0000, + 'real_time': 1, 'real_time_other': 1, + 'cpu_time': 1, 'cpu_time_other': 1}], + 'time_unit': 's', + 'utest': {} + }, + { + 'name': 'OVERALL_GEOMEAN', + 'label': '', + 'measurements': [{'real_time': 3.1622776601683826e-06, 'cpu_time': 3.2130844755623912e-06, + 'real_time_other': 1.9768988699420897e-07, 'cpu_time_other': 2.397447755209533e-07, + 'time': -0.8112976497120911, 'cpu': -0.7778551721181174}], + 'time_unit': 's', + 'run_type': 'aggregate', + 'aggregate_name': 'geomean', 'utest': {} + }, + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip( + self.json_diff_report, expected_output): + self.assertEqual(out['name'], expected['name']) + self.assertEqual(out['label'], expected['label']) + self.assertEqual(out['time_unit'], expected['time_unit']) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceBetweenFamilies(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_result(): + import json + testInputs = os.path.join( + os.path.dirname( + os.path.realpath(__file__)), + 'Inputs') + testOutput = os.path.join(testInputs, 'test2_run.json') + with open(testOutput, 'r') as f: + json = json.load(f) + return json + + json = load_result() + json1 = filter_benchmark(json, "BM_Z.ro", ".") + json2 = filter_benchmark(json, "BM_O.e", ".") + cls.json_diff_report = get_difference_report(json1, json2) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ['.', '-0.5000', '-0.5000', '10', '5', '10', '5'], + ['./4', '-0.5000', '-0.5000', '40', '20', '40', '20'], + ['Prefix/.', '-0.5000', '-0.5000', '20', '10', '20', '10'], + ['Prefix/./3', '-0.5000', '-0.5000', '30', '15', '30', '15'], + ['OVERALL_GEOMEAN', '-0.5000', '-0.5000', '0', '0', '0', '0'] + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, use_color=False) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(' ') if x] + self.assertEqual(len(parts), 7) + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + 'name': u'.', + 'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 10, 'real_time_other': 5, 'cpu_time': 10, 'cpu_time_other': 5}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': u'./4', + 'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 40, 'real_time_other': 20, 'cpu_time': 40, 'cpu_time_other': 20}], + 'time_unit': 'ns', + 'utest': {}, + }, + { + 'name': u'Prefix/.', + 'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 20, 'real_time_other': 10, 'cpu_time': 20, 'cpu_time_other': 10}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': u'Prefix/./3', + 'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 30, 'real_time_other': 15, 'cpu_time': 30, 'cpu_time_other': 15}], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'OVERALL_GEOMEAN', + 'measurements': [{'real_time': 2.213363839400641e-08, 'cpu_time': 2.213363839400641e-08, + 'real_time_other': 1.1066819197003185e-08, 'cpu_time_other': 1.1066819197003185e-08, + 'time': -0.5000000000000009, 'cpu': -0.5000000000000009}], + 'time_unit': 's', + 'run_type': 'aggregate', + 'aggregate_name': 'geomean', + 'utest': {} + } + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip( + self.json_diff_report, expected_output): + self.assertEqual(out['name'], expected['name']) + self.assertEqual(out['time_unit'], expected['time_unit']) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceWithUTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_results(): + import json + testInputs = os.path.join( + os.path.dirname( + os.path.realpath(__file__)), + 'Inputs') + testOutput1 = os.path.join(testInputs, 'test3_run0.json') + testOutput2 = os.path.join(testInputs, 'test3_run1.json') + with open(testOutput1, 'r') as f: + json1 = json.load(f) + with open(testOutput2, 'r') as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report( + json1, json2, utest=True) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'], + ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'], + ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'], + ['BM_Two_pvalue', + '1.0000', + '0.6667', + 'U', + 'Test,', + 'Repetitions:', + '2', + 'vs', + '2.', + 'WARNING:', + 'Results', + 'unreliable!', + '9+', + 'repetitions', + 'recommended.'], + ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'], + ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'], + ['short_pvalue', + '0.7671', + '0.2000', + 'U', + 'Test,', + 'Repetitions:', + '2', + 'vs', + '3.', + 'WARNING:', + 'Results', + 'unreliable!', + '9+', + 'repetitions', + 'recommended.'], + ['medium', '-0.3750', '-0.3375', '8', '5', '80', '53'], + ['OVERALL_GEOMEAN', '+1.6405', '-0.6985', '0', '0', '0', '0'] + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, utest=True, utest_alpha=0.05, use_color=False) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(' ') if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report_pretty_printing_aggregates_only(self): + expect_lines = [ + ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'], + ['BM_Two_pvalue', + '1.0000', + '0.6667', + 'U', + 'Test,', + 'Repetitions:', + '2', + 'vs', + '2.', + 'WARNING:', + 'Results', + 'unreliable!', + '9+', + 'repetitions', + 'recommended.'], + ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'], + ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'], + ['short_pvalue', + '0.7671', + '0.2000', + 'U', + 'Test,', + 'Repetitions:', + '2', + 'vs', + '3.', + 'WARNING:', + 'Results', + 'unreliable!', + '9+', + 'repetitions', + 'recommended.'], + ['OVERALL_GEOMEAN', '+1.6405', '-0.6985', '0', '0', '0', '0'] + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, include_aggregates_only=True, utest=True, utest_alpha=0.05, use_color=False) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(' ') if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + 'name': u'BM_One', + 'measurements': [ + {'time': -0.1, + 'cpu': 0.1, + 'real_time': 10, + 'real_time_other': 9, + 'cpu_time': 100, + 'cpu_time_other': 110} + ], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': u'BM_Two', + 'measurements': [ + {'time': 0.1111111111111111, + 'cpu': -0.011111111111111112, + 'real_time': 9, + 'real_time_other': 10, + 'cpu_time': 90, + 'cpu_time_other': 89}, + {'time': -0.125, 'cpu': -0.16279069767441862, 'real_time': 8, + 'real_time_other': 7, 'cpu_time': 86, 'cpu_time_other': 72} + ], + 'time_unit': 'ns', + 'utest': { + 'have_optimal_repetitions': False, 'cpu_pvalue': 0.6666666666666666, 'time_pvalue': 1.0 + } + }, + { + 'name': u'short', + 'measurements': [ + {'time': -0.125, + 'cpu': -0.0625, + 'real_time': 8, + 'real_time_other': 7, + 'cpu_time': 80, + 'cpu_time_other': 75}, + {'time': -0.4325, + 'cpu': -0.13506493506493514, + 'real_time': 8, + 'real_time_other': 4.54, + 'cpu_time': 77, + 'cpu_time_other': 66.6} + ], + 'time_unit': 'ns', + 'utest': { + 'have_optimal_repetitions': False, 'cpu_pvalue': 0.2, 'time_pvalue': 0.7670968684102772 + } + }, + { + 'name': u'medium', + 'measurements': [ + {'time': -0.375, + 'cpu': -0.3375, + 'real_time': 8, + 'real_time_other': 5, + 'cpu_time': 80, + 'cpu_time_other': 53} + ], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': 'OVERALL_GEOMEAN', + 'measurements': [{'real_time': 8.48528137423858e-09, 'cpu_time': 8.441336246629233e-08, + 'real_time_other': 2.2405267593145244e-08, 'cpu_time_other': 2.5453661413660466e-08, + 'time': 1.6404861082353634, 'cpu': -0.6984640740519662}], + 'time_unit': 's', + 'run_type': 'aggregate', + 'aggregate_name': 'geomean', + 'utest': {} + } + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip( + self.json_diff_report, expected_output): + self.assertEqual(out['name'], expected['name']) + self.assertEqual(out['time_unit'], expected['time_unit']) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceWithUTestWhileDisplayingAggregatesOnly( + unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_results(): + import json + testInputs = os.path.join( + os.path.dirname( + os.path.realpath(__file__)), + 'Inputs') + testOutput1 = os.path.join(testInputs, 'test3_run0.json') + testOutput2 = os.path.join(testInputs, 'test3_run1.json') + with open(testOutput1, 'r') as f: + json1 = json.load(f) + with open(testOutput2, 'r') as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report( + json1, json2, utest=True) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'], + ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'], + ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'], + ['BM_Two_pvalue', + '1.0000', + '0.6667', + 'U', + 'Test,', + 'Repetitions:', + '2', + 'vs', + '2.', + 'WARNING:', + 'Results', + 'unreliable!', + '9+', + 'repetitions', + 'recommended.'], + ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'], + ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'], + ['short_pvalue', + '0.7671', + '0.2000', + 'U', + 'Test,', + 'Repetitions:', + '2', + 'vs', + '3.', + 'WARNING:', + 'Results', + 'unreliable!', + '9+', + 'repetitions', + 'recommended.'], + ['medium', '-0.3750', '-0.3375', '8', '5', '80', '53'], + ['OVERALL_GEOMEAN', '+1.6405', '-0.6985', '0', '0', '0', '0'] + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, + utest=True, utest_alpha=0.05, use_color=False) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(' ') if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + 'name': u'BM_One', + 'measurements': [ + {'time': -0.1, + 'cpu': 0.1, + 'real_time': 10, + 'real_time_other': 9, + 'cpu_time': 100, + 'cpu_time_other': 110} + ], + 'time_unit': 'ns', + 'utest': {} + }, + { + 'name': u'BM_Two', + 'measurements': [ + {'time': 0.1111111111111111, + 'cpu': -0.011111111111111112, + 'real_time': 9, + 'real_time_other': 10, + 'cpu_time': 90, + 'cpu_time_other': 89}, + {'time': -0.125, 'cpu': -0.16279069767441862, 'real_time': 8, + 'real_time_other': 7, 'cpu_time': 86, 'cpu_time_other': 72} + ], + 'time_unit': 'ns', + 'utest': { + 'have_optimal_repetitions': False, 'cpu_pvalue': 0.6666666666666666, 'time_pvalue': 1.0 + } + }, + { + 'name': u'short', + 'measurements': [ + {'time': -0.125, + 'cpu': -0.0625, + 'real_time': 8, + 'real_time_other': 7, + 'cpu_time': 80, + 'cpu_time_other': 75}, + {'time': -0.4325, + 'cpu': -0.13506493506493514, + 'real_time': 8, + 'real_time_other': 4.54, + 'cpu_time': 77, + 'cpu_time_other': 66.6} + ], + 'time_unit': 'ns', + 'utest': { + 'have_optimal_repetitions': False, 'cpu_pvalue': 0.2, 'time_pvalue': 0.7670968684102772 + } + }, + { + 'name': u'medium', + 'measurements': [ + {'real_time_other': 5, + 'cpu_time': 80, + 'time': -0.375, + 'real_time': 8, + 'cpu_time_other': 53, + 'cpu': -0.3375 + } + ], + 'utest': {}, + 'time_unit': u'ns', + 'aggregate_name': '' + }, + { + 'name': 'OVERALL_GEOMEAN', + 'measurements': [{'real_time': 8.48528137423858e-09, 'cpu_time': 8.441336246629233e-08, + 'real_time_other': 2.2405267593145244e-08, 'cpu_time_other': 2.5453661413660466e-08, + 'time': 1.6404861082353634, 'cpu': -0.6984640740519662}], + 'time_unit': 's', + 'run_type': 'aggregate', + 'aggregate_name': 'geomean', + 'utest': {} + } + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip( + self.json_diff_report, expected_output): + self.assertEqual(out['name'], expected['name']) + self.assertEqual(out['time_unit'], expected['time_unit']) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportDifferenceForPercentageAggregates( + unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_results(): + import json + testInputs = os.path.join( + os.path.dirname( + os.path.realpath(__file__)), + 'Inputs') + testOutput1 = os.path.join(testInputs, 'test4_run0.json') + testOutput2 = os.path.join(testInputs, 'test4_run1.json') + with open(testOutput1, 'r') as f: + json1 = json.load(f) + with open(testOutput2, 'r') as f: + json2 = json.load(f) + return json1, json2 + + json1, json2 = load_results() + cls.json_diff_report = get_difference_report( + json1, json2, utest=True) + + def test_json_diff_report_pretty_printing(self): + expect_lines = [ + ['whocares', '-0.5000', '+0.5000', '0', '0', '0', '0'] + ] + output_lines_with_header = print_difference_report( + self.json_diff_report, + utest=True, utest_alpha=0.05, use_color=False) + output_lines = output_lines_with_header[2:] + print("\n") + print("\n".join(output_lines_with_header)) + self.assertEqual(len(output_lines), len(expect_lines)) + for i in range(0, len(output_lines)): + parts = [x for x in output_lines[i].split(' ') if x] + self.assertEqual(expect_lines[i], parts) + + def test_json_diff_report(self): + expected_output = [ + { + 'name': u'whocares', + 'measurements': [ + {'time': -0.5, + 'cpu': 0.5, + 'real_time': 0.01, + 'real_time_other': 0.005, + 'cpu_time': 0.10, + 'cpu_time_other': 0.15} + ], + 'time_unit': 'ns', + 'utest': {} + } + ] + self.assertEqual(len(self.json_diff_report), len(expected_output)) + for out, expected in zip( + self.json_diff_report, expected_output): + self.assertEqual(out['name'], expected['name']) + self.assertEqual(out['time_unit'], expected['time_unit']) + assert_utest(self, out, expected) + assert_measurements(self, out, expected) + + +class TestReportSorting(unittest.TestCase): + @classmethod + def setUpClass(cls): + def load_result(): + import json + testInputs = os.path.join( + os.path.dirname( + os.path.realpath(__file__)), + 'Inputs') + testOutput = os.path.join(testInputs, 'test4_run.json') + with open(testOutput, 'r') as f: + json = json.load(f) + return json + + cls.json = load_result() + + def test_json_diff_report_pretty_printing(self): + import util + + expected_names = [ + "99 family 0 instance 0 repetition 0", + "98 family 0 instance 0 repetition 1", + "97 family 0 instance 0 aggregate", + "96 family 0 instance 1 repetition 0", + "95 family 0 instance 1 repetition 1", + "94 family 0 instance 1 aggregate", + "93 family 1 instance 0 repetition 0", + "92 family 1 instance 0 repetition 1", + "91 family 1 instance 0 aggregate", + "90 family 1 instance 1 repetition 0", + "89 family 1 instance 1 repetition 1", + "88 family 1 instance 1 aggregate" + ] + + for n in range(len(self.json['benchmarks']) ** 2): + random.shuffle(self.json['benchmarks']) + sorted_benchmarks = util.sort_benchmark_results(self.json)[ + 'benchmarks'] + self.assertEqual(len(expected_names), len(sorted_benchmarks)) + for out, expected in zip(sorted_benchmarks, expected_names): + self.assertEqual(out['name'], expected) + + +def assert_utest(unittest_instance, lhs, rhs): + if lhs['utest']: + unittest_instance.assertAlmostEqual( + lhs['utest']['cpu_pvalue'], + rhs['utest']['cpu_pvalue']) + unittest_instance.assertAlmostEqual( + lhs['utest']['time_pvalue'], + rhs['utest']['time_pvalue']) + unittest_instance.assertEqual( + lhs['utest']['have_optimal_repetitions'], + rhs['utest']['have_optimal_repetitions']) + else: + # lhs is empty. assert if rhs is not. + unittest_instance.assertEqual(lhs['utest'], rhs['utest']) + + +def assert_measurements(unittest_instance, lhs, rhs): + for m1, m2 in zip(lhs['measurements'], rhs['measurements']): + unittest_instance.assertEqual(m1['real_time'], m2['real_time']) + unittest_instance.assertEqual(m1['cpu_time'], m2['cpu_time']) + # m1['time'] and m1['cpu'] hold values which are being calculated, + # and therefore we must use almost-equal pattern. + unittest_instance.assertAlmostEqual(m1['time'], m2['time'], places=4) + unittest_instance.assertAlmostEqual(m1['cpu'], m2['cpu'], places=4) + + +if __name__ == '__main__': + unittest.main() + +# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 +# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; +# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/util.py b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/util.py similarity index 71% rename from thirdparty_builtin/benchmark-1.5.0/tools/gbench/util.py rename to thirdparty_builtin/benchmark-1.8.0/tools/gbench/util.py index 1f8e8e2c4..5e79da8f0 100644 --- a/thirdparty_builtin/benchmark-1.5.0/tools/gbench/util.py +++ b/thirdparty_builtin/benchmark-1.8.0/tools/gbench/util.py @@ -2,9 +2,11 @@ """ import json import os -import tempfile +import re import subprocess import sys +import tempfile + # Input file type enumeration IT_Invalid = 0 @@ -57,7 +59,7 @@ def classify_input_file(filename): """ Return a tuple (type, msg) where 'type' specifies the classified type of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable - string represeting the error. + string representing the error. """ ftype = IT_Invalid err_msg = None @@ -110,13 +112,49 @@ def remove_benchmark_flags(prefix, benchmark_flags): return [f for f in benchmark_flags if not f.startswith(prefix)] -def load_benchmark_results(fname): +def load_benchmark_results(fname, benchmark_filter): """ Read benchmark output from a file and return the JSON object. + + Apply benchmark_filter, a regular expression, with nearly the same + semantics of the --benchmark_filter argument. May be None. + Note: the Python regular expression engine is used instead of the + one used by the C++ code, which may produce different results + in complex cases. + REQUIRES: 'fname' names a file containing JSON benchmark output. """ + def benchmark_wanted(benchmark): + if benchmark_filter is None: + return True + name = benchmark.get('run_name', None) or benchmark['name'] + if re.search(benchmark_filter, name): + return True + return False + with open(fname, 'r') as f: - return json.load(f) + results = json.load(f) + if 'benchmarks' in results: + results['benchmarks'] = list(filter(benchmark_wanted, + results['benchmarks'])) + return results + + +def sort_benchmark_results(result): + benchmarks = result['benchmarks'] + + # From inner key to the outer key! + benchmarks = sorted( + benchmarks, key=lambda benchmark: benchmark['repetition_index'] if 'repetition_index' in benchmark else -1) + benchmarks = sorted( + benchmarks, key=lambda benchmark: 1 if 'run_type' in benchmark and benchmark['run_type'] == "aggregate" else 0) + benchmarks = sorted( + benchmarks, key=lambda benchmark: benchmark['per_family_instance_index'] if 'per_family_instance_index' in benchmark else -1) + benchmarks = sorted( + benchmarks, key=lambda benchmark: benchmark['family_index'] if 'family_index' in benchmark else -1) + + result['benchmarks'] = benchmarks + return result def run_benchmark(exe_name, benchmark_flags): @@ -142,7 +180,7 @@ def run_benchmark(exe_name, benchmark_flags): if exitCode != 0: print('TEST FAILED...') sys.exit(exitCode) - json_res = load_benchmark_results(output_name) + json_res = load_benchmark_results(output_name, None) if is_temp_output: os.unlink(output_name) return json_res @@ -157,8 +195,9 @@ def run_or_load_benchmark(filename, benchmark_flags): """ ftype = check_input_file(filename) if ftype == IT_JSON: - return load_benchmark_results(filename) - elif ftype == IT_Executable: + benchmark_filter = find_benchmark_flag('--benchmark_filter=', + benchmark_flags) + return load_benchmark_results(filename, benchmark_filter) + if ftype == IT_Executable: return run_benchmark(filename, benchmark_flags) - else: - assert False # This branch is unreachable + raise ValueError('Unknown file type %s' % ftype) diff --git a/thirdparty_builtin/benchmark-1.8.0/tools/libpfm.BUILD.bazel b/thirdparty_builtin/benchmark-1.8.0/tools/libpfm.BUILD.bazel new file mode 100644 index 000000000..62695342a --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/tools/libpfm.BUILD.bazel @@ -0,0 +1,22 @@ +# Build rule for libpfm, which is required to collect performance counters for +# BENCHMARK_ENABLE_LIBPFM builds. + +load("@rules_foreign_cc//foreign_cc:defs.bzl", "make") + +filegroup( + name = "pfm_srcs", + srcs = glob(["**"]), +) + +make( + name = "libpfm", + lib_source = ":pfm_srcs", + lib_name = "libpfm", + copts = [ + "-Wno-format-truncation", + "-Wno-use-after-free", + ], + visibility = [ + "//visibility:public", + ], +) diff --git a/thirdparty_builtin/benchmark-1.8.0/tools/requirements.txt b/thirdparty_builtin/benchmark-1.8.0/tools/requirements.txt new file mode 100644 index 000000000..3b3331b5a --- /dev/null +++ b/thirdparty_builtin/benchmark-1.8.0/tools/requirements.txt @@ -0,0 +1 @@ +scipy>=1.5.0 \ No newline at end of file diff --git a/thirdparty_builtin/benchmark-1.5.0/tools/strip_asm.py b/thirdparty_builtin/benchmark-1.8.0/tools/strip_asm.py similarity index 99% rename from thirdparty_builtin/benchmark-1.5.0/tools/strip_asm.py rename to thirdparty_builtin/benchmark-1.8.0/tools/strip_asm.py index 9030550b4..d131dc719 100755 --- a/thirdparty_builtin/benchmark-1.5.0/tools/strip_asm.py +++ b/thirdparty_builtin/benchmark-1.8.0/tools/strip_asm.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ strip_asm.py - Cleanup ASM output for the specified file diff --git a/thirdparty_builtin/googletest-master-2020-01-07/.gitignore b/thirdparty_builtin/googletest-master-2020-01-07/.gitignore deleted file mode 100755 index ce310bc35..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Ignore CI build directory -build/ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/.travis.yml b/thirdparty_builtin/googletest-master-2020-01-07/.travis.yml deleted file mode 100755 index 3204dfac1..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/.travis.yml +++ /dev/null @@ -1,46 +0,0 @@ -# Build matrix / environment variable are explained on: -# http://about.travis-ci.org/docs/user/build-configuration/ -# This file can be validated on: -# http://lint.travis-ci.org/ - -install: -# /usr/bin/gcc is 4.6 always, but gcc-X.Y is available. -- if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi -# /usr/bin/clang is 3.4, lets override with modern one. -- if [ "$CXX" = "clang++" ] && [ "$TRAVIS_OS_NAME" = "linux" ]; then export CXX="clang++-3.7" CC="clang-3.7"; fi -- echo ${PATH} -- echo ${CXX} -- ${CXX} --version -- ${CXX} -v -addons: - apt: - # List of whitelisted in travis packages for ubuntu-precise can be found here: - # https://github.com/travis-ci/apt-package-whitelist/blob/master/ubuntu-precise - # List of whitelisted in travis apt-sources: - # https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-precise-3.7 - packages: - - gcc-4.9 - - g++-4.9 - - clang-3.7 - - valgrind -os: - - linux - - osx -language: cpp -compiler: - - gcc - - clang -script: ./travis.sh -env: - matrix: - - GTEST_TARGET=googletest SHARED_LIB=OFF STATIC_LIB=ON CMAKE_PKG=OFF BUILD_TYPE=debug VERBOSE_MAKE=true VERBOSE - - GTEST_TARGET=googlemock SHARED_LIB=OFF STATIC_LIB=ON CMAKE_PKG=OFF BUILD_TYPE=debug VERBOSE_MAKE=true VERBOSE - - GTEST_TARGET=googlemock SHARED_LIB=OFF STATIC_LIB=ON CMAKE_PKG=OFF BUILD_TYPE=debug CXX_FLAGS=-std=c++11 VERBOSE_MAKE=true VERBOSE -# - GTEST_TARGET=googletest SHARED_LIB=ON STATIC_LIB=ON CMAKE_PKG=ON BUILD_TYPE=release VERBOSE_MAKE=false -# - GTEST_TARGET=googlemock SHARED_LIB=ON STATIC_LIB=ON CMAKE_PKG=ON BUILD_TYPE=release VERBOSE_MAKE=false -notifications: - email: false -sudo: false diff --git a/thirdparty_builtin/googletest-master-2020-01-07/README.md b/thirdparty_builtin/googletest-master-2020-01-07/README.md deleted file mode 100644 index e332e9a21..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/README.md +++ /dev/null @@ -1,136 +0,0 @@ -# Google Test - -#### OSS Builds Status: - -[![Build Status](https://api.travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest) -[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) - -### Announcements: - -#### Release 1.10.x - -[Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0) -is now available. - -#### Coming Soon - -* Post 1.10.x googletest will follow - [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) -* We are also planning to take a dependency on - [Abseil](https://github.com/abseil/abseil-cpp). - -## Welcome to **Google Test**, Google's C++ test framework! - -This repository is a merger of the formerly separate GoogleTest and GoogleMock -projects. These were so closely related that it makes sense to maintain and -release them together. - -Please subscribe to the mailing list at googletestframework@googlegroups.com for -questions, discussions, and development. - -### Getting started: - -The information for **Google Test** is available in the -[Google Test Primer](googletest/docs/primer.md) documentation. - -**Google Mock** is an extension to Google Test for writing and using C++ mock -classes. See the separate [Google Mock documentation](googlemock/README.md). - -More detailed documentation for googletest is in its interior -[googletest/README.md](googletest/README.md) file. - -## Features - -* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework. -* Test discovery. -* A rich set of assertions. -* User-defined assertions. -* Death tests. -* Fatal and non-fatal failures. -* Value-parameterized tests. -* Type-parameterized tests. -* Various options for running the tests. -* XML test report generation. - -## Platforms - -Google test has been used on a variety of platforms: - -* Linux -* Mac OS X -* Windows -* Cygwin -* MinGW -* Windows Mobile -* Symbian -* PlatformIO - -## Who Is Using Google Test? - -In addition to many internal projects at Google, Google Test is also used by the -following notable projects: - -* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser - and Chrome OS). -* The [LLVM](http://llvm.org/) compiler. -* [Protocol Buffers](https://github.com/google/protobuf), Google's data - interchange format. -* The [OpenCV](http://opencv.org/) computer vision library. -* [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only, - dependency-free deep learning framework in C++11. - -## Related Open Source Projects - -[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based -automated test-runner and Graphical User Interface with powerful features for -Windows and Linux platforms. - -[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that -runs your test binary, allows you to track its progress via a progress bar, and -displays a list of test failures. Clicking on one shows failure text. Google -Test UI is written in C#. - -[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event -listener for Google Test that implements the -[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test -result output. If your test runner understands TAP, you may find it useful. - -[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that -runs tests from your binary in parallel to provide significant speed-up. - -[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) -is a VS Code extension allowing to view Google Tests in a tree view, and -run/debug your tests. - -[Catch2 and Google Test Explorer](https://github.com/matepek/vscode-catch2-test-adapter) -is a VS Code extension allowing to view Google Tests in a tree view, and -run/debug your tests. - -[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser -that generates stub code for Google Test. - -## Requirements - -Google Test is designed to have fairly minimal requirements to build and use -with your projects, but there are some. If you notice any problems on your -platform, please notify -[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework). -Patches for fixing them are welcome! - -### Build Requirements - -These are the base requirements to build and use Google Test from a source -package: - -* [Bazel](https://bazel.build/) or [CMake](https://cmake.org/). NOTE: Bazel is - the build system that googletest is using internally and tests against. - CMake is community-supported. - -* a C++11-standard-compliant compiler - -## Contributing change - -Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on how to -contribute to this project. - -Happy testing! diff --git a/thirdparty_builtin/googletest-master-2020-01-07/WORKSPACE b/thirdparty_builtin/googletest-master-2020-01-07/WORKSPACE deleted file mode 100644 index 2289bdb7e..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/WORKSPACE +++ /dev/null @@ -1,23 +0,0 @@ -workspace(name = "com_google_googletest") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -# Abseil -http_archive( - name = "com_google_absl", - urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"], - strip_prefix = "abseil-cpp-master", -) - -http_archive( - name = "rules_cc", - strip_prefix = "rules_cc-master", - urls = ["https://github.com/bazelbuild/rules_cc/archive/master.zip"], -) - -http_archive( - name = "rules_python", - strip_prefix = "rules_python-master", - urls = ["https://github.com/bazelbuild/rules_python/archive/master.zip"], -) - diff --git a/thirdparty_builtin/googletest-master-2020-01-07/appveyor.yml b/thirdparty_builtin/googletest-master-2020-01-07/appveyor.yml deleted file mode 100644 index ec155a76a..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/appveyor.yml +++ /dev/null @@ -1,156 +0,0 @@ -version: '{build}' - -os: Visual Studio 2015 - -environment: - matrix: - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017" - build_system: cmake - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - enabled_on_pr: yes - - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017 Win64" - build_system: cmake - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - enabled_on_pr: yes - - - compiler: msvc-15-seh - build_system: bazel - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - enabled_on_pr: yes - - - compiler: msvc-14-seh - build_system: cmake - generator: "Visual Studio 14 2015" - enabled_on_pr: yes - - - compiler: msvc-14-seh - build_system: cmake - generator: "Visual Studio 14 2015 Win64" - enabled_on_pr: yes - - - compiler: gcc-6.3.0-posix - build_system: cmake - generator: "MinGW Makefiles" - cxx_path: 'C:\mingw-w64\i686-6.3.0-posix-dwarf-rt_v5-rev1\mingw32\bin' - enabled_on_pr: yes - -configuration: - - Debug - -build: - verbosity: minimal - -install: -- ps: | - Write-Output "Compiler: $env:compiler" - Write-Output "Generator: $env:generator" - Write-Output "Env:Configuation: $env:configuration" - Write-Output "Env: $env" - if (-not (Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER)) { - Write-Output "This is *NOT* a pull request build" - } else { - Write-Output "This is a pull request build" - if (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes") { - Write-Output "PR builds are *NOT* explicitly enabled" - } - } - - # install Bazel - if ($env:build_system -eq "bazel") { - appveyor DownloadFile https://github.com/bazelbuild/bazel/releases/download/0.28.1/bazel-0.28.1-windows-x86_64.exe -FileName bazel.exe - } - - if ($env:build_system -eq "cmake") { - # git bash conflicts with MinGW makefiles - if ($env:generator -eq "MinGW Makefiles") { - $env:path = $env:path.replace("C:\Program Files\Git\usr\bin;", "") - if ($env:cxx_path -ne "") { - $env:path += ";$env:cxx_path" - } - } - } - -before_build: -- ps: | - $env:root=$env:APPVEYOR_BUILD_FOLDER - Write-Output "env:root: $env:root" - -build_script: -- ps: | - # Only enable some builds for pull requests, the AppVeyor queue is too long. - if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) { - return - } else { - # special case - build with Bazel - if ($env:build_system -eq "bazel") { - & $env:root\bazel.exe build -c opt //:gtest_samples - if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error - $host.SetShouldExit(0) - } else { # a real error - throw "Exec: $ErrorMessage" - } - return - } - } - # by default build with CMake - md _build -Force | Out-Null - cd _build - - $conf = if ($env:generator -eq "MinGW Makefiles") {"-DCMAKE_BUILD_TYPE=$env:configuration"} else {"-DCMAKE_CONFIGURATION_TYPES=Debug;Release"} - # Disable test for MinGW (gtest tests fail, gmock tests can not build) - $gtest_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgtest_build_tests=OFF"} else {"-Dgtest_build_tests=ON"} - $gmock_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgmock_build_tests=OFF"} else {"-Dgmock_build_tests=ON"} - & cmake -G "$env:generator" $conf -Dgtest_build_samples=ON $gtest_build_tests $gmock_build_tests .. - if ($LastExitCode -ne 0) { - throw "Exec: $ErrorMessage" - } - $cmake_parallel = if ($env:generator -eq "MinGW Makefiles") {"-j2"} else {"/m"} - & cmake --build . --config $env:configuration -- $cmake_parallel - if ($LastExitCode -ne 0) { - throw "Exec: $ErrorMessage" - } - - -skip_commits: - files: - - '**/*.md' - -test_script: -- ps: | - # Only enable some builds for pull requests, the AppVeyor queue is too long. - if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) { - return - } - if ($env:build_system -eq "bazel") { - # special case - testing with Bazel - & $env:root\bazel.exe test //:gtest_samples - if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error - $host.SetShouldExit(0) - } else { # a real error - throw "Exec: $ErrorMessage" - } - } - if ($env:build_system -eq "cmake") { - # built with CMake - test with CTest - if ($env:generator -eq "MinGW Makefiles") { - return # No test available for MinGW - } - - & ctest -C $env:configuration --timeout 600 --output-on-failure - if ($LastExitCode -ne 0) { - throw "Exec: $ErrorMessage" - } - } - -artifacts: - - path: '_build/CMakeFiles/*.log' - name: logs - - path: '_build/Testing/**/*.xml' - name: test_results - - path: 'bazel-testlogs/**/test.log' - name: test_logs - - path: 'bazel-testlogs/**/test.xml' - name: test_results diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/CONTRIBUTORS b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/CONTRIBUTORS deleted file mode 100644 index 6e9ae362b..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/CONTRIBUTORS +++ /dev/null @@ -1,40 +0,0 @@ -# This file contains a list of people who've made non-trivial -# contribution to the Google C++ Mocking Framework project. People -# who commit code to the project are encouraged to add their names -# here. Please keep the list sorted by first names. - -Benoit Sigoure -Bogdan Piloca -Chandler Carruth -Dave MacLachlan -David Anderson -Dean Sturtevant -Gene Volovich -Hal Burch -Jeffrey Yasskin -Jim Keller -Joe Walnes -Jon Wray -Keir Mierle -Keith Ray -Kostya Serebryany -Lev Makhlis -Manuel Klimek -Mario Tanev -Mark Paskin -Markus Heule -Matthew Simmons -Mike Bland -Neal Norwitz -Nermin Ozkiranartli -Owen Carlsen -Paneendra Ba -Paul Menage -Piotr Kaminski -Russ Rufer -Sverre Sundsdal -Takeshi Yoshino -Vadim Berman -Vlad Losev -Wolfgang Klier -Zhanyong Wan diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/LICENSE b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/LICENSE deleted file mode 100644 index 1941a11f8..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2008, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/README.md b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/README.md deleted file mode 100644 index 183fdb81d..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Googletest Mocking (gMock) Framework - -### Overview - -Google's framework for writing and using C++ mock classes. It can help you -derive better designs of your system and write better tests. - -It is inspired by: - -* [jMock](http://www.jmock.org/), -* [EasyMock](http://www.easymock.org/), and -* [Hamcrest](http://code.google.com/p/hamcrest/), - -and designed with C++'s specifics in mind. - -gMock: - -- provides a declarative syntax for defining mocks, -- can define partial (hybrid) mocks, which are a cross of real and mock - objects, -- handles functions of arbitrary types and overloaded functions, -- comes with a rich set of matchers for validating function arguments, -- uses an intuitive syntax for controlling the behavior of a mock, -- does automatic verification of expectations (no record-and-replay needed), -- allows arbitrary (partial) ordering constraints on function calls to be - expressed, -- lets a user extend it by defining new matchers and actions. -- does not use exceptions, and -- is easy to learn and use. - -Details and examples can be found here: - -* [gMock for Dummies](docs/for_dummies.md) -* [Legacy gMock FAQ](docs/gmock_faq.md) -* [gMock Cookbook](docs/cook_book.md) -* [gMock Cheat Sheet](docs/cheat_sheet.md) - -Please note that code under scripts/generator/ is from the [cppclean -project](http://code.google.com/p/cppclean/) and under the Apache -License, which is different from Google Mock's license. - -Google Mock is a part of -[Google Test C++ testing framework](http://github.com/google/googletest/) and a -subject to the same requirements. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/cheat_sheet.md b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/cheat_sheet.md deleted file mode 100644 index b425e0a0e..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/cheat_sheet.md +++ /dev/null @@ -1,776 +0,0 @@ -## gMock Cheat Sheet - - - - - -### Defining a Mock Class - -#### Mocking a Normal Class {#MockClass} - -Given - -```cpp -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` - -(note that `~Foo()` **must** be virtual) we can define its mock as - -```cpp -#include "gmock/gmock.h" - -class MockFoo : public Foo { - ... - MOCK_METHOD(int, GetSize, (), (const, override)); - MOCK_METHOD(string, Describe, (const char* name), (override)); - MOCK_METHOD(string, Describe, (int type), (override)); - MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); -}; -``` - -To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, -which warns on all uninteresting calls, or a "strict" mock, which treats them as -failures: - -```cpp -using ::testing::NiceMock; -using ::testing::NaggyMock; -using ::testing::StrictMock; - -NiceMock nice_foo; // The type is a subclass of MockFoo. -NaggyMock naggy_foo; // The type is a subclass of MockFoo. -StrictMock strict_foo; // The type is a subclass of MockFoo. -``` - -**Note:** A mock object is currently naggy by default. We may make it nice by -default in the future. - -#### Mocking a Class Template {#MockTemplate} - -Class templates can be mocked just like any class. - -To mock - -```cpp -template -class StackInterface { - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` - -(note that all member functions that are mocked, including `~StackInterface()` -**must** be virtual). - -```cpp -template -class MockStack : public StackInterface { - ... - MOCK_METHOD(int, GetSize, (), (const, override)); - MOCK_METHOD(void, Push, (const Elem& x), (override)); -}; -``` - -#### Specifying Calling Conventions for Mock Functions - -If your mock function doesn't use the default calling convention, you can -specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. -For example, - -```cpp - MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); - MOCK_METHOD(int, Bar, (double x, double y), - (const, Calltype(STDMETHODCALLTYPE))); -``` - -where `STDMETHODCALLTYPE` is defined by `` on Windows. - -### Using Mocks in Tests {#UsingMocks} - -The typical work flow is: - -1. Import the gMock names you need to use. All gMock symbols are in the - `testing` namespace unless they are macros or otherwise noted. -2. Create the mock objects. -3. Optionally, set the default actions of the mock objects. -4. Set your expectations on the mock objects (How will they be called? What - will they do?). -5. Exercise code that uses the mock objects; if necessary, check the result - using googletest assertions. -6. When a mock object is destructed, gMock automatically verifies that all - expectations on it have been satisfied. - -Here's an example: - -```cpp -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -### Setting Default Actions {#OnCall} - -gMock has a **built-in default action** for any function that returns `void`, -`bool`, a numeric value, or a pointer. In C++11, it will additionally returns -the default-constructed value, if one exists for the given type. - -To customize the default action for functions with return type *`T`*: - -```cpp -using ::testing::DefaultValue; - -// Sets the default value to be returned. T must be CopyConstructible. -DefaultValue::Set(value); -// Sets a factory. Will be invoked on demand. T must be MoveConstructible. -// T MakeT(); -DefaultValue::SetFactory(&MakeT); -// ... use the mocks ... -// Resets the default value. -DefaultValue::Clear(); -``` - -Example usage: - -```cpp - // Sets the default action for return type std::unique_ptr to - // creating a new Buzz every time. - DefaultValue>::SetFactory( - [] { return MakeUnique(AccessLevel::kInternal); }); - - // When this fires, the default action of MakeBuzz() will run, which - // will return a new Buzz object. - EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); - - auto buzz1 = mock_buzzer_.MakeBuzz("hello"); - auto buzz2 = mock_buzzer_.MakeBuzz("hello"); - EXPECT_NE(nullptr, buzz1); - EXPECT_NE(nullptr, buzz2); - EXPECT_NE(buzz1, buzz2); - - // Resets the default action for return type std::unique_ptr, - // to avoid interfere with other tests. - DefaultValue>::Clear(); -``` - -To customize the default action for a particular method of a specific mock -object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`, -but it is used for setting default behaviors (when you do not require that the -mock method is called). See [here](cook_book.md#UseOnCall) for a more detailed -discussion. - -```cpp -ON_CALL(mock-object, method(matchers)) - .With(multi-argument-matcher) ? - .WillByDefault(action); -``` - -### Setting Expectations {#ExpectCall} - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be called? -What will it do?): - -```cpp -EXPECT_CALL(mock-object, method (matchers)?) - .With(multi-argument-matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -For each item above, `?` means it can be used at most once, while `*` means it -can be used any number of times. - -In order to pass, `EXPECT_CALL` must be used before the calls are actually made. - -The `(matchers)` is a comma-separated list of matchers that correspond to each -of the arguments of `method`, and sets the expectation only for calls of -`method` that matches all of the matchers. - -If `(matchers)` is omitted, the expectation is the same as if the matchers were -set to anything matchers (for example, `(_, _, _, _)` for a four-arg method). - -If `Times()` is omitted, the cardinality is assumed to be: - -* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; -* `Times(n)` when there are `n` `WillOnce()`s but no `WillRepeatedly()`, where - `n` >= 1; or -* `Times(AtLeast(n))` when there are `n` `WillOnce()`s and a - `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked *any number of times*, -and the default action will be taken each time. - -### Matchers {#MatcherList} - - - -A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or -`EXPECT_CALL()`, or use it to validate a value directly using two macros: - - -| Macro | Description | -| :----------------------------------- | :------------------------------------ | -| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | -| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | - - -Built-in matchers (where `argument` is the function argument, e.g. -`actual_value` in the example above, or when used in the context of -`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are -divided into several categories: - -#### Wildcard - -Matcher | Description -:-------------------------- | :----------------------------------------------- -`_` | `argument` can be any value of the correct type. -`A()` or `An()` | `argument` can be any value of type `type`. - -#### Generic Comparison - - -| Matcher | Description | -| :--------------------- | :-------------------------------------------------- | -| `Eq(value)` or `value` | `argument == value` | -| `Ge(value)` | `argument >= value` | -| `Gt(value)` | `argument > value` | -| `Le(value)` | `argument <= value` | -| `Lt(value)` | `argument < value` | -| `Ne(value)` | `argument != value` | -| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | -| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | -| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | -| `NotNull()` | `argument` is a non-null pointer (raw or smart). | -| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| -| `VariantWith(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | -| `Ref(variable)` | `argument` is a reference to `variable`. | -| `TypedEq(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | - - -Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or -destructed later. If the compiler complains that `value` doesn't have a public -copy constructor, try wrap it in `ByRef()`, e.g. -`Eq(ByRef(non_copyable_value))`. If you do that, make sure `non_copyable_value` -is not changed afterwards, or the meaning of your matcher will be changed. - -`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types -that can be explicitly converted to Boolean, but are not implicitly converted to -Boolean. In other cases, you can use the basic -[`EXPECT_TRUE` and `EXPECT_FALSE`](../../googletest/docs/primer#basic-assertions) -assertions. - -#### Floating-Point Matchers {#FpMatchers} - - -| Matcher | Description | -| :------------------------------- | :--------------------------------- | -| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | -| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | -| `IsNan()` | `argument` is any floating-point type with a NaN value. | - - -The above matchers use ULP-based comparison (the same as used in googletest). -They automatically pick a reasonable error bound based on the absolute value of -the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard, -which requires comparing two NaNs for equality to return false. The -`NanSensitive*` version instead treats two NaNs as equal, which is often what a -user wants. - - -| Matcher | Description | -| :------------------------------------------------ | :----------------------- | -| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | -| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | -| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | -| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | - - -#### String Matchers - -The `argument` can be either a C string or a C++ string object: - - -| Matcher | Description | -| :---------------------- | :------------------------------------------------- | -| `ContainsRegex(string)` | `argument` matches the given regular expression. | -| `EndsWith(suffix)` | `argument` ends with string `suffix`. | -| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | -| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. | -| `StartsWith(prefix)` | `argument` starts with string `prefix`. | -| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | -| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | -| `StrEq(string)` | `argument` is equal to `string`. | -| `StrNe(string)` | `argument` is not equal to `string`. | - - -`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They -use the regular expression syntax defined -[here](../../googletest/docs/advanced.md#regular-expression-syntax). All of -these matchers, except `ContainsRegex()` and `MatchesRegex()` work for wide -strings as well. - -#### Container Matchers - -Most STL-style containers support `==`, so you can use `Eq(expected_container)` -or simply `expected_container` to match a container exactly. If you want to -write the elements in-line, match them more flexibly, or get more informative -messages, you can use: - - -| Matcher | Description | -| :---------------------------------------- | :------------------------------- | -| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | -| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | -| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | -| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | -| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | -| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | -| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | -| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | -| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | -| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | -| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. | -| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. | -| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | - - -**Notes:** - -* These matchers can also match: - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), - and - 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, - int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). -* The array being matched may be multi-dimensional (i.e. its elements can be - arrays). -* `m` in `Pointwise(m, ...)` should be a matcher for `::std::tuple` - where `T` and `U` are the element type of the actual container and the - expected container, respectively. For example, to compare two `Foo` - containers where `Foo` doesn't support `operator==`, one might write: - - ```cpp - using ::std::get; - MATCHER(FooEq, "") { - return std::get<0>(arg).Equals(std::get<1>(arg)); - } - ... - EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); - ``` - -#### Member Matchers - - -| Matcher | Description | -| :------------------------------ | :----------------------------------------- | -| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | -| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. | -| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | -| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | - - -#### Matching the Result of a Function, Functor, or Callback - - -| Matcher | Description | -| :--------------- | :------------------------------------------------ | -| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | - - -#### Pointer Matchers - - -| Matcher | Description | -| :------------------------ | :---------------------------------------------- | -| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. | -| `WhenDynamicCastTo(m)` | when `argument` is passed through `dynamic_cast()`, it matches matcher `m`. | - - - - - - -#### Multi-argument Matchers {#MultiArgMatchers} - -Technically, all matchers match a *single* value. A "multi-argument" matcher is -just one that matches a *tuple*. The following matchers can be used to match a -tuple `(x, y)`: - -Matcher | Description -:------ | :---------- -`Eq()` | `x == y` -`Ge()` | `x >= y` -`Gt()` | `x > y` -`Le()` | `x <= y` -`Lt()` | `x < y` -`Ne()` | `x != y` - -You can use the following selectors to pick a subset of the arguments (or -reorder them) to participate in the matching: - - -| Matcher | Description | -| :------------------------- | :---------------------------------------------- | -| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. | -| `Args(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. | - - -#### Composite Matchers - -You can make a matcher from one or more other matchers: - - -| Matcher | Description | -| :------------------------------- | :-------------------------------------- | -| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. | -| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | -| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | -| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | -| `Not(m)` | `argument` doesn't match matcher `m`. | - - - - -#### Adapters for Matchers - - -| Matcher | Description | -| :---------------------- | :------------------------------------ | -| `MatcherCast(m)` | casts matcher `m` to type `Matcher`. | -| `SafeMatcherCast(m)` | [safely casts](cook_book.md#casting-matchers) matcher `m` to type `Matcher`. | -| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. | - - -`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, -which must be a permanent callback. - -#### Using Matchers as Predicates {#MatchersAsPredicatesCheat} - - -| Matcher | Description | -| :---------------------------- | :------------------------------------------ | -| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | -| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | -| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | - - -#### Defining Matchers - - -| Matcher | Description | -| :----------------------------------- | :------------------------------------ | -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - - -**Notes:** - -1. The `MATCHER*` macros cannot be used inside a function or class. -2. The matcher body must be *purely functional* (i.e. it cannot have any side - effect, and the result must not depend on anything other than the value - being matched and the matcher parameters). -3. You can use `PrintToString(x)` to convert a value `x` of any type to a - string. - -### Actions {#ActionList} - -**Actions** specify what a mock function should do when invoked. - -#### Returning a Value - - -| | | -| :-------------------------------- | :-------------------------------------------- | -| `Return()` | Return from a `void` mock function. | -| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | -| `ReturnArg()` | Return the `N`-th (0-based) argument. | -| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | -| `ReturnNull()` | Return a null pointer. | -| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | -| `ReturnRef(variable)` | Return a reference to `variable`. | -| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | -| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | - - -#### Side Effects - - -| | | -| :--------------------------------- | :-------------------------------------- | -| `Assign(&variable, value)` | Assign `value` to variable. | -| `DeleteArg()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SaveArgPointee(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -| `SetArgPointee(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | -| `SetArgumentPointee(value)` | Same as `SetArgPointee(value)`. Deprecated. Will be removed in v1.7.0. | -| `SetArrayArgument(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. | -| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | -| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | - - -#### Using a Function, Functor, or Lambda as an Action - -In the following, by "callable" we mean a free function, `std::function`, -functor, or lambda. - - -| | | -| :---------------------------------- | :------------------------------------- | -| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. | -| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | -| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | -| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | -| `InvokeArgument(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. | - - -The return value of the invoked function is used as the return value of the -action. - -When defining a callable to be used with `Invoke*()`, you can declare any unused -parameters as `Unused`: - -```cpp -using ::testing::Invoke; -double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } -... -EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of -`callback`, which must be permanent. The type of `callback` must be a base -callback type instead of a derived one, e.g. - -```cpp - BlockingClosure* done = new BlockingClosure; - ... Invoke(done) ...; // This won't compile! - - Closure* done2 = new BlockingClosure; - ... Invoke(done2) ...; // This works. -``` - -In `InvokeArgument(...)`, if an argument needs to be passed by reference, -wrap it inside `ByRef()`. For example, - -```cpp -using ::testing::ByRef; -using ::testing::InvokeArgument; -... -InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` - -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by -value, and `foo` by reference. - -#### Default Action - - -| Matcher | Description | -| :------------ | :----------------------------------------------------- | -| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | - - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a -composite action - trying to do so will result in a run-time error. - - - -#### Composite Actions - - -| | | -| :----------------------------- | :------------------------------------------ | -| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | -| `WithArg(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -| `WithArgs(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -| `WithoutArgs(a)` | Perform action `a` without any arguments. | - - -#### Defining Actions - - -| | | -| :--------------------------------- | :-------------------------------------- | -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - - -The `ACTION*` macros cannot be used inside a function or class. - -### Cardinalities {#CardinalityList} - -These are used in `Times()` to specify how many times a mock function will be -called: - - -| | | -| :---------------- | :----------------------------------------------------- | -| `AnyNumber()` | The function can be called any number of times. | -| `AtLeast(n)` | The call is expected at least `n` times. | -| `AtMost(n)` | The call is expected at most `n` times. | -| `Between(m, n)` | The call is expected between `m` and `n` (inclusive) times. | -| `Exactly(n) or n` | The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0. | - - -### Expectation Order - -By default, the expectations can be matched in *any* order. If some or all -expectations must be matched in a given order, there are two ways to specify it. -They can be used either independently or together. - -#### The After Clause {#AfterClause} - -```cpp -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` - -says that `Bar()` can be called only after both `InitX()` and `InitY()` have -been called. - -If you don't know how many pre-requisites an expectation has when you write it, -you can use an `ExpectationSet` to collect them: - -```cpp -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` - -says that `Bar()` can be called only after all elements have been initialized -(but we don't care about which elements get initialized before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the -meaning of the `.After()`. - -#### Sequences {#UsingSequences} - -When you have a long chain of sequential expectations, it's easier to specify -the order using **sequences**, which don't require you to given each expectation -in the chain a different name. *All expected calls* in the same sequence must -occur in the order they are specified. - -```cpp -using ::testing::Return; -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` - -says that `Reset()` must be called before *both* `GetSize()` *and* `Describe()`, -and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: - -```cpp -using ::testing::InSequence; -{ - InSequence seq; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` - -says that all expected calls in the scope of `seq` must occur in strict order. -The name `seq` is irrelevant. - -### Verifying and Resetting a Mock - -gMock will verify the expectations on a mock object when it is destructed, or -you can do it earlier: - -```cpp -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true if and only if successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true if and only if successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell gMock that a mock object can be leaked and doesn't need to be -verified: - -```cpp -Mock::AllowLeak(&mock_obj); -``` - -### Mock Classes - -gMock defines a convenient mock class template - -```cpp -class MockFunction { - public: - MOCK_METHOD(R, Call, (A1, ..., An)); -}; -``` - -See this [recipe](cook_book.md#using-check-points) for one application of it. - -### Flags - - -| Flag | Description | -| :----------------------------- | :---------------------------------------- | -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | - diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/pump_manual.md b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/pump_manual.md deleted file mode 100644 index cdf7c57da..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/pump_manual.md +++ /dev/null @@ -1,187 +0,0 @@ -Pump is Useful for Meta Programming. - -# The Problem - -Template and macro libraries often need to define many classes, functions, or -macros that vary only (or almost only) in the number of arguments they take. -It's a lot of repetitive, mechanical, and error-prone work. - -Our experience is that it's tedious to write custom scripts, which tend to -reflect the structure of the generated code poorly and are often hard to read -and edit. For example, a small change needed in the generated code may require -some non-intuitive, non-trivial changes in the script. This is especially -painful when experimenting with the code. - -This script may be useful for generating meta code, for example a series of -macros of FOO1, FOO2, etc. Nevertheless, please make it your last resort -technique by favouring C++ template metaprogramming or variadic macros. - -# Our Solution - -Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta -Programming, or Practical Utility for Meta Programming, whichever you prefer) is -a simple meta-programming tool for C++. The idea is that a programmer writes a -`foo.pump` file which contains C++ code plus meta code that manipulates the C++ -code. The meta code can handle iterations over a range, nested iterations, local -meta variable definitions, simple arithmetic, and conditional expressions. You -can view it as a small Domain-Specific Language. The meta language is designed -to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, for example) and -concise, making Pump code intuitive and easy to maintain. - -## Highlights - -* The implementation is in a single Python script and thus ultra portable: no - build or installation is needed and it works cross platforms. -* Pump tries to be smart with respect to - [Google's style guide](https://github.com/google/styleguide): it breaks long - lines (easy to have when they are generated) at acceptable places to fit - within 80 columns and indent the continuation lines correctly. -* The format is human-readable and more concise than XML. -* The format works relatively well with Emacs' C++ mode. - -## Examples - -The following Pump code (where meta keywords start with `$`, `[[` and `]]` are -meta brackets, and `$$` starts a meta comment that ends with the line): - -``` -$var n = 3 $$ Defines a meta variable n. -$range i 0..n $$ Declares the range of meta iterator i (inclusive). -$for i [[ - $$ Meta loop. -// Foo$i does blah for $i-ary predicates. -$range j 1..i -template -class Foo$i { -$if i == 0 [[ - blah a; -]] $elif i <= 2 [[ - blah b; -]] $else [[ - blah c; -]] -}; - -]] -``` - -will be translated by the Pump compiler to: - -```cpp -// Foo0 does blah for 0-ary predicates. -template -class Foo0 { - blah a; -}; - -// Foo1 does blah for 1-ary predicates. -template -class Foo1 { - blah b; -}; - -// Foo2 does blah for 2-ary predicates. -template -class Foo2 { - blah b; -}; - -// Foo3 does blah for 3-ary predicates. -template -class Foo3 { - blah c; -}; -``` - -In another example, - -``` -$range i 1..n -Func($for i + [[a$i]]); -$$ The text between i and [[ is the separator between iterations. -``` - -will generate one of the following lines (without the comments), depending on -the value of `n`: - -```cpp -Func(); // If n is 0. -Func(a1); // If n is 1. -Func(a1 + a2); // If n is 2. -Func(a1 + a2 + a3); // If n is 3. -// And so on... -``` - -## Constructs - -We support the following meta programming constructs: - -| `$var id = exp` | Defines a named constant value. `$id` is | -: : valid util the end of the current meta : -: : lexical block. : -| :------------------------------- | :--------------------------------------- | -| `$range id exp..exp` | Sets the range of an iteration variable, | -: : which can be reused in multiple loops : -: : later. : -| `$for id sep [[ code ]]` | Iteration. The range of `id` must have | -: : been defined earlier. `$id` is valid in : -: : `code`. : -| `$($)` | Generates a single `$` character. | -| `$id` | Value of the named constant or iteration | -: : variable. : -| `$(exp)` | Value of the expression. | -| `$if exp [[ code ]] else_branch` | Conditional. | -| `[[ code ]]` | Meta lexical block. | -| `cpp_code` | Raw C++ code. | -| `$$ comment` | Meta comment. | - -**Note:** To give the user some freedom in formatting the Pump source code, Pump -ignores a new-line character if it's right after `$for foo` or next to `[[` or -`]]`. Without this rule you'll often be forced to write very long lines to get -the desired output. Therefore sometimes you may need to insert an extra new-line -in such places for a new-line to show up in your output. - -## Grammar - -```ebnf -code ::= atomic_code* -atomic_code ::= $var id = exp - | $var id = [[ code ]] - | $range id exp..exp - | $for id sep [[ code ]] - | $($) - | $id - | $(exp) - | $if exp [[ code ]] else_branch - | [[ code ]] - | cpp_code -sep ::= cpp_code | empty_string -else_branch ::= $else [[ code ]] - | $elif exp [[ code ]] else_branch - | empty_string -exp ::= simple_expression_in_Python_syntax -``` - -## Code - -You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). -It is still very unpolished and lacks automated tests, although it has been -successfully used many times. If you find a chance to use it in your project, -please let us know what you think! We also welcome help on improving Pump. - -## Real Examples - -You can find real-world applications of Pump in -[Google Test](https://github.com/google/googletest/tree/master/googletest) and -[Google Mock](https://github.com/google/googletest/tree/master/googlemock). The -source file `foo.h.pump` generates `foo.h`. - -## Tips - -* If a meta variable is followed by a letter or digit, you can separate them - using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` - generate `Foo1Helper` when `j` is 1. -* To avoid extra-long Pump source lines, you can break a line anywhere you - want by inserting `[[]]` followed by a new line. Since any new-line - character next to `[[` or `]]` is ignored, the generated code won't contain - this new line. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-actions.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-actions.h deleted file mode 100644 index 4b8dcebb9..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-actions.h +++ /dev/null @@ -1,1234 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used actions. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ - -#ifndef _WIN32_WCE -# include -#endif - -#include -#include -#include -#include -#include -#include - -#include "gmock/internal/gmock-internal-utils.h" -#include "gmock/internal/gmock-port.h" - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -#endif - -namespace testing { - -// To implement an action Foo, define: -// 1. a class FooAction that implements the ActionInterface interface, and -// 2. a factory function that creates an Action object from a -// const FooAction*. -// -// The two-level delegation design follows that of Matcher, providing -// consistency for extension developers. It also eases ownership -// management as Action objects can now be copied like plain values. - -namespace internal { - -// BuiltInDefaultValueGetter::Get() returns a -// default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. -// -// This primary template is used when kDefaultConstructible is true. -template -struct BuiltInDefaultValueGetter { - static T Get() { return T(); } -}; -template -struct BuiltInDefaultValueGetter { - static T Get() { - Assert(false, __FILE__, __LINE__, - "Default action undefined for the function return type."); - return internal::Invalid(); - // The above statement will never be reached, but is required in - // order for this function to compile. - } -}; - -// BuiltInDefaultValue::Get() returns the "built-in" default value -// for type T, which is NULL when T is a raw pointer type, 0 when T is -// a numeric type, false when T is bool, or "" when T is string or -// std::string. In addition, in C++11 and above, it turns a -// default-constructed T value if T is default constructible. For any -// other type T, the built-in default T value is undefined, and the -// function will abort the process. -template -class BuiltInDefaultValue { - public: - // This function returns true if and only if type T has a built-in default - // value. - static bool Exists() { - return ::std::is_default_constructible::value; - } - - static T Get() { - return BuiltInDefaultValueGetter< - T, ::std::is_default_constructible::value>::Get(); - } -}; - -// This partial specialization says that we use the same built-in -// default value for T and const T. -template -class BuiltInDefaultValue { - public: - static bool Exists() { return BuiltInDefaultValue::Exists(); } - static T Get() { return BuiltInDefaultValue::Get(); } -}; - -// This partial specialization defines the default values for pointer -// types. -template -class BuiltInDefaultValue { - public: - static bool Exists() { return true; } - static T* Get() { return nullptr; } -}; - -// The following specializations define the default values for -// specific types we care about. -#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ - template <> \ - class BuiltInDefaultValue { \ - public: \ - static bool Exists() { return true; } \ - static type Get() { return value; } \ - } - -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); - -// There's no need for a default action for signed wchar_t, as that -// type is the same as wchar_t for gcc, and invalid for MSVC. -// -// There's also no need for a default action for unsigned wchar_t, as -// that type is the same as unsigned int for gcc, and invalid for -// MSVC. -#if GMOCK_WCHAR_T_IS_NATIVE_ -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT -#endif - -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); - -#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ - -} // namespace internal - -// When an unexpected function call is encountered, Google Mock will -// let it return a default value if the user has specified one for its -// return type, or if the return type has a built-in default value; -// otherwise Google Mock won't know what value to return and will have -// to abort the process. -// -// The DefaultValue class allows a user to specify the -// default value for a type T that is both copyable and publicly -// destructible (i.e. anything that can be used as a function return -// type). The usage is: -// -// // Sets the default value for type T to be foo. -// DefaultValue::Set(foo); -template -class DefaultValue { - public: - // Sets the default value for type T; requires T to be - // copy-constructable and have a public destructor. - static void Set(T x) { - delete producer_; - producer_ = new FixedValueProducer(x); - } - - // Provides a factory function to be called to generate the default value. - // This method can be used even if T is only move-constructible, but it is not - // limited to that case. - typedef T (*FactoryFunction)(); - static void SetFactory(FactoryFunction factory) { - delete producer_; - producer_ = new FactoryValueProducer(factory); - } - - // Unsets the default value for type T. - static void Clear() { - delete producer_; - producer_ = nullptr; - } - - // Returns true if and only if the user has set the default value for type T. - static bool IsSet() { return producer_ != nullptr; } - - // Returns true if T has a default return value set by the user or there - // exists a built-in default value. - static bool Exists() { - return IsSet() || internal::BuiltInDefaultValue::Exists(); - } - - // Returns the default value for type T if the user has set one; - // otherwise returns the built-in default value. Requires that Exists() - // is true, which ensures that the return value is well-defined. - static T Get() { - return producer_ == nullptr ? internal::BuiltInDefaultValue::Get() - : producer_->Produce(); - } - - private: - class ValueProducer { - public: - virtual ~ValueProducer() {} - virtual T Produce() = 0; - }; - - class FixedValueProducer : public ValueProducer { - public: - explicit FixedValueProducer(T value) : value_(value) {} - T Produce() override { return value_; } - - private: - const T value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); - }; - - class FactoryValueProducer : public ValueProducer { - public: - explicit FactoryValueProducer(FactoryFunction factory) - : factory_(factory) {} - T Produce() override { return factory_(); } - - private: - const FactoryFunction factory_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); - }; - - static ValueProducer* producer_; -}; - -// This partial specialization allows a user to set default values for -// reference types. -template -class DefaultValue { - public: - // Sets the default value for type T&. - static void Set(T& x) { // NOLINT - address_ = &x; - } - - // Unsets the default value for type T&. - static void Clear() { address_ = nullptr; } - - // Returns true if and only if the user has set the default value for type T&. - static bool IsSet() { return address_ != nullptr; } - - // Returns true if T has a default return value set by the user or there - // exists a built-in default value. - static bool Exists() { - return IsSet() || internal::BuiltInDefaultValue::Exists(); - } - - // Returns the default value for type T& if the user has set one; - // otherwise returns the built-in default value if there is one; - // otherwise aborts the process. - static T& Get() { - return address_ == nullptr ? internal::BuiltInDefaultValue::Get() - : *address_; - } - - private: - static T* address_; -}; - -// This specialization allows DefaultValue::Get() to -// compile. -template <> -class DefaultValue { - public: - static bool Exists() { return true; } - static void Get() {} -}; - -// Points to the user-set default value for type T. -template -typename DefaultValue::ValueProducer* DefaultValue::producer_ = nullptr; - -// Points to the user-set default value for type T&. -template -T* DefaultValue::address_ = nullptr; - -// Implement this interface to define an action for function type F. -template -class ActionInterface { - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - ActionInterface() {} - virtual ~ActionInterface() {} - - // Performs the action. This method is not const, as in general an - // action can have side effects and be stateful. For example, a - // get-the-next-element-from-the-collection action will need to - // remember the current element. - virtual Result Perform(const ArgumentTuple& args) = 0; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); -}; - -// An Action is a copyable and IMMUTABLE (except by assignment) -// object that represents an action to be taken when a mock function -// of type F is called. The implementation of Action is just a -// std::shared_ptr to const ActionInterface. Don't inherit from Action! -// You can view an object implementing ActionInterface as a -// concrete action (including its current state), and an Action -// object as a handle to it. -template -class Action { - // Adapter class to allow constructing Action from a legacy ActionInterface. - // New code should create Actions from functors instead. - struct ActionAdapter { - // Adapter must be copyable to satisfy std::function requirements. - ::std::shared_ptr> impl_; - - template - typename internal::Function::Result operator()(Args&&... args) { - return impl_->Perform( - ::std::forward_as_tuple(::std::forward(args)...)); - } - }; - - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - // Constructs a null Action. Needed for storing Action objects in - // STL containers. - Action() {} - - // Construct an Action from a specified callable. - // This cannot take std::function directly, because then Action would not be - // directly constructible from lambda (it would require two conversions). - template , G>::value>::type> - Action(G&& fun) : fun_(::std::forward(fun)) {} // NOLINT - - // Constructs an Action from its implementation. - explicit Action(ActionInterface* impl) - : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} - - // This constructor allows us to turn an Action object into an - // Action, as long as F's arguments can be implicitly converted - // to Func's and Func's return type can be implicitly converted to F's. - template - explicit Action(const Action& action) : fun_(action.fun_) {} - - // Returns true if and only if this is the DoDefault() action. - bool IsDoDefault() const { return fun_ == nullptr; } - - // Performs the action. Note that this method is const even though - // the corresponding method in ActionInterface is not. The reason - // is that a const Action means that it cannot be re-bound to - // another concrete action, not that the concrete action it binds to - // cannot change state. (Think of the difference between a const - // pointer and a pointer to const.) - Result Perform(ArgumentTuple args) const { - if (IsDoDefault()) { - internal::IllegalDoDefault(__FILE__, __LINE__); - } - return internal::Apply(fun_, ::std::move(args)); - } - - private: - template - friend class Action; - - // fun_ is an empty function if and only if this is the DoDefault() action. - ::std::function fun_; -}; - -// The PolymorphicAction class template makes it easy to implement a -// polymorphic action (i.e. an action that can be used in mock -// functions of than one type, e.g. Return()). -// -// To define a polymorphic action, a user first provides a COPYABLE -// implementation class that has a Perform() method template: -// -// class FooAction { -// public: -// template -// Result Perform(const ArgumentTuple& args) const { -// // Processes the arguments and returns a result, using -// // std::get(args) to get the N-th (0-based) argument in the tuple. -// } -// ... -// }; -// -// Then the user creates the polymorphic action using -// MakePolymorphicAction(object) where object has type FooAction. See -// the definition of Return(void) and SetArgumentPointee(value) for -// complete examples. -template -class PolymorphicAction { - public: - explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} - - template - operator Action() const { - return Action(new MonomorphicImpl(impl_)); - } - - private: - template - class MonomorphicImpl : public ActionInterface { - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} - - Result Perform(const ArgumentTuple& args) override { - return impl_.template Perform(args); - } - - private: - Impl impl_; - - GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); - }; - - Impl impl_; - - GTEST_DISALLOW_ASSIGN_(PolymorphicAction); -}; - -// Creates an Action from its implementation and returns it. The -// created Action object owns the implementation. -template -Action MakeAction(ActionInterface* impl) { - return Action(impl); -} - -// Creates a polymorphic action from its implementation. This is -// easier to use than the PolymorphicAction constructor as it -// doesn't require you to explicitly write the template argument, e.g. -// -// MakePolymorphicAction(foo); -// vs -// PolymorphicAction(foo); -template -inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { - return PolymorphicAction(impl); -} - -namespace internal { - -// Helper struct to specialize ReturnAction to execute a move instead of a copy -// on return. Useful for move-only types, but could be used on any type. -template -struct ByMoveWrapper { - explicit ByMoveWrapper(T value) : payload(std::move(value)) {} - T payload; -}; - -// Implements the polymorphic Return(x) action, which can be used in -// any function that returns the type of x, regardless of the argument -// types. -// -// Note: The value passed into Return must be converted into -// Function::Result when this action is cast to Action rather than -// when that action is performed. This is important in scenarios like -// -// MOCK_METHOD1(Method, T(U)); -// ... -// { -// Foo foo; -// X x(&foo); -// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x)); -// } -// -// In the example above the variable x holds reference to foo which leaves -// scope and gets destroyed. If copying X just copies a reference to foo, -// that copy will be left with a hanging reference. If conversion to T -// makes a copy of foo, the above code is safe. To support that scenario, we -// need to make sure that the type conversion happens inside the EXPECT_CALL -// statement, and conversion of the result of Return to Action is a -// good place for that. -// -// The real life example of the above scenario happens when an invocation -// of gtl::Container() is passed into Return. -// -template -class ReturnAction { - public: - // Constructs a ReturnAction object from the value to be returned. - // 'value' is passed by value instead of by const reference in order - // to allow Return("string literal") to compile. - explicit ReturnAction(R value) : value_(new R(std::move(value))) {} - - // This template type conversion operator allows Return(x) to be - // used in ANY function that returns x's type. - template - operator Action() const { // NOLINT - // Assert statement belongs here because this is the best place to verify - // conditions on F. It produces the clearest error messages - // in most compilers. - // Impl really belongs in this scope as a local class but can't - // because MSVC produces duplicate symbols in different translation units - // in this case. Until MS fixes that bug we put Impl into the class scope - // and put the typedef both here (for use in assert statement) and - // in the Impl class. But both definitions must be the same. - typedef typename Function::Result Result; - GTEST_COMPILE_ASSERT_( - !std::is_reference::value, - use_ReturnRef_instead_of_Return_to_return_a_reference); - static_assert(!std::is_void::value, - "Can't use Return() on an action expected to return `void`."); - return Action(new Impl(value_)); - } - - private: - // Implements the Return(x) action for a particular function type F. - template - class Impl : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - // The implicit cast is necessary when Result has more than one - // single-argument constructor (e.g. Result is std::vector) and R - // has a type conversion operator template. In that case, value_(value) - // won't compile as the compiler doesn't known which constructor of - // Result to call. ImplicitCast_ forces the compiler to convert R to - // Result without considering explicit constructors, thus resolving the - // ambiguity. value_ is then initialized using its copy constructor. - explicit Impl(const std::shared_ptr& value) - : value_before_cast_(*value), - value_(ImplicitCast_(value_before_cast_)) {} - - Result Perform(const ArgumentTuple&) override { return value_; } - - private: - GTEST_COMPILE_ASSERT_(!std::is_reference::value, - Result_cannot_be_a_reference_type); - // We save the value before casting just in case it is being cast to a - // wrapper type. - R value_before_cast_; - Result value_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); - }; - - // Partially specialize for ByMoveWrapper. This version of ReturnAction will - // move its contents instead. - template - class Impl, F> : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - explicit Impl(const std::shared_ptr& wrapper) - : performed_(false), wrapper_(wrapper) {} - - Result Perform(const ArgumentTuple&) override { - GTEST_CHECK_(!performed_) - << "A ByMove() action should only be performed once."; - performed_ = true; - return std::move(wrapper_->payload); - } - - private: - bool performed_; - const std::shared_ptr wrapper_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - const std::shared_ptr value_; - - GTEST_DISALLOW_ASSIGN_(ReturnAction); -}; - -// Implements the ReturnNull() action. -class ReturnNullAction { - public: - // Allows ReturnNull() to be used in any pointer-returning function. In C++11 - // this is enforced by returning nullptr, and in non-C++11 by asserting a - // pointer type on compile time. - template - static Result Perform(const ArgumentTuple&) { - return nullptr; - } -}; - -// Implements the Return() action. -class ReturnVoidAction { - public: - // Allows Return() to be used in any void-returning function. - template - static void Perform(const ArgumentTuple&) { - static_assert(std::is_void::value, "Result should be void."); - } -}; - -// Implements the polymorphic ReturnRef(x) action, which can be used -// in any function that returns a reference to the type of x, -// regardless of the argument types. -template -class ReturnRefAction { - public: - // Constructs a ReturnRefAction object from the reference to be returned. - explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT - - // This template type conversion operator allows ReturnRef(x) to be - // used in ANY function that returns a reference to x's type. - template - operator Action() const { - typedef typename Function::Result Result; - // Asserts that the function return type is a reference. This - // catches the user error of using ReturnRef(x) when Return(x) - // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_(std::is_reference::value, - use_Return_instead_of_ReturnRef_to_return_a_value); - return Action(new Impl(ref_)); - } - - private: - // Implements the ReturnRef(x) action for a particular function type F. - template - class Impl : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - explicit Impl(T& ref) : ref_(ref) {} // NOLINT - - Result Perform(const ArgumentTuple&) override { return ref_; } - - private: - T& ref_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - T& ref_; - - GTEST_DISALLOW_ASSIGN_(ReturnRefAction); -}; - -// Implements the polymorphic ReturnRefOfCopy(x) action, which can be -// used in any function that returns a reference to the type of x, -// regardless of the argument types. -template -class ReturnRefOfCopyAction { - public: - // Constructs a ReturnRefOfCopyAction object from the reference to - // be returned. - explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT - - // This template type conversion operator allows ReturnRefOfCopy(x) to be - // used in ANY function that returns a reference to x's type. - template - operator Action() const { - typedef typename Function::Result Result; - // Asserts that the function return type is a reference. This - // catches the user error of using ReturnRefOfCopy(x) when Return(x) - // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_( - std::is_reference::value, - use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); - return Action(new Impl(value_)); - } - - private: - // Implements the ReturnRefOfCopy(x) action for a particular function type F. - template - class Impl : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - explicit Impl(const T& value) : value_(value) {} // NOLINT - - Result Perform(const ArgumentTuple&) override { return value_; } - - private: - T value_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - const T value_; - - GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); -}; - -// Implements the polymorphic ReturnRoundRobin(v) action, which can be -// used in any function that returns the element_type of v. -template -class ReturnRoundRobinAction { - public: - explicit ReturnRoundRobinAction(std::vector values) { - GTEST_CHECK_(!values.empty()) - << "ReturnRoundRobin requires at least one element."; - state_->values = std::move(values); - } - - template - T operator()(Args&&...) const { - return state_->Next(); - } - - private: - struct State { - T Next() { - T ret_val = values[i++]; - if (i == values.size()) i = 0; - return ret_val; - } - - std::vector values; - size_t i = 0; - }; - std::shared_ptr state_ = std::make_shared(); -}; - -// Implements the polymorphic DoDefault() action. -class DoDefaultAction { - public: - // This template type conversion operator allows DoDefault() to be - // used in any function. - template - operator Action() const { return Action(); } // NOLINT -}; - -// Implements the Assign action to set a given pointer referent to a -// particular value. -template -class AssignAction { - public: - AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} - - template - void Perform(const ArgumentTuple& /* args */) const { - *ptr_ = value_; - } - - private: - T1* const ptr_; - const T2 value_; - - GTEST_DISALLOW_ASSIGN_(AssignAction); -}; - -#if !GTEST_OS_WINDOWS_MOBILE - -// Implements the SetErrnoAndReturn action to simulate return from -// various system calls and libc functions. -template -class SetErrnoAndReturnAction { - public: - SetErrnoAndReturnAction(int errno_value, T result) - : errno_(errno_value), - result_(result) {} - template - Result Perform(const ArgumentTuple& /* args */) const { - errno = errno_; - return result_; - } - - private: - const int errno_; - const T result_; - - GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction); -}; - -#endif // !GTEST_OS_WINDOWS_MOBILE - -// Implements the SetArgumentPointee(x) action for any function -// whose N-th argument (0-based) is a pointer to x's type. -template -struct SetArgumentPointeeAction { - A value; - - template - void operator()(const Args&... args) const { - *::std::get(std::tie(args...)) = value; - } -}; - -// Implements the Invoke(object_ptr, &Class::Method) action. -template -struct InvokeMethodAction { - Class* const obj_ptr; - const MethodPtr method_ptr; - - template - auto operator()(Args&&... args) const - -> decltype((obj_ptr->*method_ptr)(std::forward(args)...)) { - return (obj_ptr->*method_ptr)(std::forward(args)...); - } -}; - -// Implements the InvokeWithoutArgs(f) action. The template argument -// FunctionImpl is the implementation type of f, which can be either a -// function pointer or a functor. InvokeWithoutArgs(f) can be used as an -// Action as long as f's type is compatible with F. -template -struct InvokeWithoutArgsAction { - FunctionImpl function_impl; - - // Allows InvokeWithoutArgs(f) to be used as any action whose type is - // compatible with f. - template - auto operator()(const Args&...) -> decltype(function_impl()) { - return function_impl(); - } -}; - -// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. -template -struct InvokeMethodWithoutArgsAction { - Class* const obj_ptr; - const MethodPtr method_ptr; - - using ReturnType = typename std::result_of::type; - - template - ReturnType operator()(const Args&...) const { - return (obj_ptr->*method_ptr)(); - } -}; - -// Implements the IgnoreResult(action) action. -template -class IgnoreResultAction { - public: - explicit IgnoreResultAction(const A& action) : action_(action) {} - - template - operator Action() const { - // Assert statement belongs here because this is the best place to verify - // conditions on F. It produces the clearest error messages - // in most compilers. - // Impl really belongs in this scope as a local class but can't - // because MSVC produces duplicate symbols in different translation units - // in this case. Until MS fixes that bug we put Impl into the class scope - // and put the typedef both here (for use in assert statement) and - // in the Impl class. But both definitions must be the same. - typedef typename internal::Function::Result Result; - - // Asserts at compile time that F returns void. - static_assert(std::is_void::value, "Result type should be void."); - - return Action(new Impl(action_)); - } - - private: - template - class Impl : public ActionInterface { - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - explicit Impl(const A& action) : action_(action) {} - - void Perform(const ArgumentTuple& args) override { - // Performs the action and ignores its result. - action_.Perform(args); - } - - private: - // Type OriginalFunction is the same as F except that its return - // type is IgnoredValue. - typedef typename internal::Function::MakeResultIgnoredValue - OriginalFunction; - - const Action action_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - const A action_; - - GTEST_DISALLOW_ASSIGN_(IgnoreResultAction); -}; - -template -struct WithArgsAction { - InnerAction action; - - // The inner action could be anything convertible to Action. - // We use the conversion operator to detect the signature of the inner Action. - template - operator Action() const { // NOLINT - using TupleType = std::tuple; - Action::type...)> - converted(action); - - return [converted](Args... args) -> R { - return converted.Perform(std::forward_as_tuple( - std::get(std::forward_as_tuple(std::forward(args)...))...)); - }; - } -}; - -template -struct DoAllAction { - private: - template - std::vector> Convert(IndexSequence) const { - return {std::get(actions)...}; - } - - public: - std::tuple actions; - - template - operator Action() const { // NOLINT - struct Op { - std::vector> converted; - Action last; - R operator()(Args... args) const { - auto tuple_args = std::forward_as_tuple(std::forward(args)...); - for (auto& a : converted) { - a.Perform(tuple_args); - } - return last.Perform(tuple_args); - } - }; - return Op{Convert(MakeIndexSequence()), - std::get(actions)}; - } -}; - -} // namespace internal - -// An Unused object can be implicitly constructed from ANY value. -// This is handy when defining actions that ignore some or all of the -// mock function arguments. For example, given -// -// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); -// MOCK_METHOD3(Bar, double(int index, double x, double y)); -// -// instead of -// -// double DistanceToOriginWithLabel(const string& label, double x, double y) { -// return sqrt(x*x + y*y); -// } -// double DistanceToOriginWithIndex(int index, double x, double y) { -// return sqrt(x*x + y*y); -// } -// ... -// EXPECT_CALL(mock, Foo("abc", _, _)) -// .WillOnce(Invoke(DistanceToOriginWithLabel)); -// EXPECT_CALL(mock, Bar(5, _, _)) -// .WillOnce(Invoke(DistanceToOriginWithIndex)); -// -// you could write -// -// // We can declare any uninteresting argument as Unused. -// double DistanceToOrigin(Unused, double x, double y) { -// return sqrt(x*x + y*y); -// } -// ... -// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); -// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); -typedef internal::IgnoredValue Unused; - -// Creates an action that does actions a1, a2, ..., sequentially in -// each invocation. -template -internal::DoAllAction::type...> DoAll( - Action&&... action) { - return {std::forward_as_tuple(std::forward(action)...)}; -} - -// WithArg(an_action) creates an action that passes the k-th -// (0-based) argument of the mock function to an_action and performs -// it. It adapts an action accepting one argument to one that accepts -// multiple arguments. For convenience, we also provide -// WithArgs(an_action) (defined below) as a synonym. -template -internal::WithArgsAction::type, k> -WithArg(InnerAction&& action) { - return {std::forward(action)}; -} - -// WithArgs(an_action) creates an action that passes -// the selected arguments of the mock function to an_action and -// performs it. It serves as an adaptor between actions with -// different argument lists. -template -internal::WithArgsAction::type, k, ks...> -WithArgs(InnerAction&& action) { - return {std::forward(action)}; -} - -// WithoutArgs(inner_action) can be used in a mock function with a -// non-empty argument list to perform inner_action, which takes no -// argument. In other words, it adapts an action accepting no -// argument to one that accepts (and ignores) arguments. -template -internal::WithArgsAction::type> -WithoutArgs(InnerAction&& action) { - return {std::forward(action)}; -} - -// Creates an action that returns 'value'. 'value' is passed by value -// instead of const reference - otherwise Return("string literal") -// will trigger a compiler error about using array as initializer. -template -internal::ReturnAction Return(R value) { - return internal::ReturnAction(std::move(value)); -} - -// Creates an action that returns NULL. -inline PolymorphicAction ReturnNull() { - return MakePolymorphicAction(internal::ReturnNullAction()); -} - -// Creates an action that returns from a void function. -inline PolymorphicAction Return() { - return MakePolymorphicAction(internal::ReturnVoidAction()); -} - -// Creates an action that returns the reference to a variable. -template -inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT - return internal::ReturnRefAction(x); -} - -// Prevent using ReturnRef on reference to temporary. -template -internal::ReturnRefAction ReturnRef(R&&) = delete; - -// Creates an action that returns the reference to a copy of the -// argument. The copy is created when the action is constructed and -// lives as long as the action. -template -inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { - return internal::ReturnRefOfCopyAction(x); -} - -// Modifies the parent action (a Return() action) to perform a move of the -// argument instead of a copy. -// Return(ByMove()) actions can only be executed once and will assert this -// invariant. -template -internal::ByMoveWrapper ByMove(R x) { - return internal::ByMoveWrapper(std::move(x)); -} - -// Creates an action that returns an element of `vals`. Calling this action will -// repeatedly return the next value from `vals` until it reaches the end and -// will restart from the beginning. -template -internal::ReturnRoundRobinAction ReturnRoundRobin(std::vector vals) { - return internal::ReturnRoundRobinAction(std::move(vals)); -} - -// Creates an action that returns an element of `vals`. Calling this action will -// repeatedly return the next value from `vals` until it reaches the end and -// will restart from the beginning. -template -internal::ReturnRoundRobinAction ReturnRoundRobin( - std::initializer_list vals) { - return internal::ReturnRoundRobinAction(std::vector(vals)); -} - -// Creates an action that does the default action for the give mock function. -inline internal::DoDefaultAction DoDefault() { - return internal::DoDefaultAction(); -} - -// Creates an action that sets the variable pointed by the N-th -// (0-based) function argument to 'value'. -template -internal::SetArgumentPointeeAction SetArgPointee(T value) { - return {std::move(value)}; -} - -// The following version is DEPRECATED. -template -internal::SetArgumentPointeeAction SetArgumentPointee(T value) { - return {std::move(value)}; -} - -// Creates an action that sets a pointer referent to a given value. -template -PolymorphicAction > Assign(T1* ptr, T2 val) { - return MakePolymorphicAction(internal::AssignAction(ptr, val)); -} - -#if !GTEST_OS_WINDOWS_MOBILE - -// Creates an action that sets errno and returns the appropriate error. -template -PolymorphicAction > -SetErrnoAndReturn(int errval, T result) { - return MakePolymorphicAction( - internal::SetErrnoAndReturnAction(errval, result)); -} - -#endif // !GTEST_OS_WINDOWS_MOBILE - -// Various overloads for Invoke(). - -// Legacy function. -// Actions can now be implicitly constructed from callables. No need to create -// wrapper objects. -// This function exists for backwards compatibility. -template -typename std::decay::type Invoke(FunctionImpl&& function_impl) { - return std::forward(function_impl); -} - -// Creates an action that invokes the given method on the given object -// with the mock function's arguments. -template -internal::InvokeMethodAction Invoke(Class* obj_ptr, - MethodPtr method_ptr) { - return {obj_ptr, method_ptr}; -} - -// Creates an action that invokes 'function_impl' with no argument. -template -internal::InvokeWithoutArgsAction::type> -InvokeWithoutArgs(FunctionImpl function_impl) { - return {std::move(function_impl)}; -} - -// Creates an action that invokes the given method on the given object -// with no argument. -template -internal::InvokeMethodWithoutArgsAction InvokeWithoutArgs( - Class* obj_ptr, MethodPtr method_ptr) { - return {obj_ptr, method_ptr}; -} - -// Creates an action that performs an_action and throws away its -// result. In other words, it changes the return type of an_action to -// void. an_action MUST NOT return void, or the code won't compile. -template -inline internal::IgnoreResultAction IgnoreResult(const A& an_action) { - return internal::IgnoreResultAction(an_action); -} - -// Creates a reference wrapper for the given L-value. If necessary, -// you can explicitly specify the type of the reference. For example, -// suppose 'derived' is an object of type Derived, ByRef(derived) -// would wrap a Derived&. If you want to wrap a const Base& instead, -// where Base is a base class of Derived, just write: -// -// ByRef(derived) -// -// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. -// However, it may still be used for consistency with ByMove(). -template -inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT - return ::std::reference_wrapper(l_value); -} - -namespace internal { - -// A macro from the ACTION* family (defined later in gmock-generated-actions.h) -// defines an action that can be used in a mock function. Typically, -// these actions only care about a subset of the arguments of the mock -// function. For example, if such an action only uses the second -// argument, it can be used in any mock function that takes >= 2 -// arguments where the type of the second argument is compatible. -// -// Therefore, the action implementation must be prepared to take more -// arguments than it needs. The ExcessiveArg type is used to -// represent those excessive arguments. In order to keep the compiler -// error messages tractable, we define it in the testing namespace -// instead of testing::internal. However, this is an INTERNAL TYPE -// and subject to change without notice, so a user MUST NOT USE THIS -// TYPE DIRECTLY. -struct ExcessiveArg {}; - -// A helper class needed for implementing the ACTION* macros. -template -class ActionHelper { - public: - template - static Result Perform(Impl* impl, const std::tuple& args) { - return Apply(impl, args, MakeIndexSequence{}, - MakeIndexSequence<10 - sizeof...(Ts)>{}); - } - - private: - template - static Result Apply(Impl* impl, const std::tuple& args, - IndexSequence, IndexSequence) { - return impl->template gmock_PerformImpl( - args, std::get(args)..., - ((void)rest_ids, ExcessiveArg())...); - } -}; - -} // namespace internal - -} // namespace testing - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-function-mocker.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-function-mocker.h deleted file mode 100644 index c5291412b..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-function-mocker.h +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements MOCK_METHOD. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT -#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT - -#include "gmock/gmock-generated-function-mockers.h" // NOLINT -#include "gmock/internal/gmock-pp.h" - -namespace testing { -namespace internal { -template -using identity_t = T; -} // namespace internal -} // namespace testing - -#define MOCK_METHOD(...) \ - GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ - GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ - GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ - GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ - GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ - GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ - GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ - GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ - GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ - GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ - GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ - GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \ - (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_WRONG_ARITY(...) \ - static_assert( \ - false, \ - "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ - "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ - "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ - "it must also be enclosed in parentheses.") - -#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ - static_assert( \ - GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ - GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") - -#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ - static_assert( \ - std::is_function<__VA_ARGS__>::value, \ - "Signature must be a function type, maybe return type contains " \ - "unprotected comma."); \ - static_assert( \ - ::testing::tuple_size::ArgumentTuple>::value == _N, \ - "This method does not take " GMOCK_PP_STRINGIZE( \ - _N) " arguments. Parenthesize all types with unproctected commas.") - -#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) - -#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ - _Override, _Final, _NoexceptSpec, \ - _CallType, _Signature) \ - typename ::testing::internal::Function::Result \ - GMOCK_INTERNAL_EXPAND(_CallType) \ - _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ - GMOCK_PP_IF(_Constness, const, ) _NoexceptSpec \ - GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \ - GMOCK_MOCKER_(_N, _Constness, _MethodName) \ - .SetOwnerAndName(this, #_MethodName); \ - return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ - .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ - } \ - ::testing::MockSpec gmock_##_MethodName( \ - GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ - GMOCK_PP_IF(_Constness, const, ) { \ - GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ - return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ - .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ - } \ - ::testing::MockSpec gmock_##_MethodName( \ - const ::testing::internal::WithoutMatchers&, \ - GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ - GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _NoexceptSpec { \ - return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \ - GMOCK_PP_IF(_Constness, const, ))(this) \ - ->gmock_##_MethodName(GMOCK_PP_REPEAT( \ - GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ - } \ - mutable ::testing::FunctionMocker \ - GMOCK_MOCKER_(_N, _Constness, _MethodName) - -#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ - -// Five Valid modifiers. -#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ - GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) - -#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ - GMOCK_PP_HAS_COMMA( \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) - -#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ - GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) - -#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) - -#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ - GMOCK_PP_IF( \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ - _elem, ) - -#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple) - -#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ - static_assert( \ - (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ - GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \ - GMOCK_PP_STRINGIZE( \ - _elem) " cannot be recognized as a valid specification modifier."); - -// Modifiers implementation. -#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_CONST_I_const , - -#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , - -#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_FINAL_I_final , - -#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , - -#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \ - GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \ - GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \ - (_elem) - -// TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and -// GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows -// maybe they can be simplified somehow. -#define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \ - GMOCK_INTERNAL_IS_CALLTYPE_I( \ - GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg)) -#define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg) - -#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \ - GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \ - GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg)) -#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \ - GMOCK_PP_CAT(GMOCK_PP_IDENTITY, _arg) - -#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype - -// Note: The use of `identity_t` here allows _Ret to represent return types that -// would normally need to be specified in a different way. For example, a method -// returning a function pointer must be written as -// -// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...) -// -// But we only support placing the return type at the beginning. To handle this, -// we wrap all calls in identity_t, so that a declaration will be expanded to -// -// identity_t method(method_args_t...) -// -// This allows us to work around the syntactic oddities of function/method -// types. -#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ - ::testing::internal::identity_t( \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) - -#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ - GMOCK_PP_COMMA_IF(_i) \ - GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ - GMOCK_PP_IDENTITY) \ - (_elem) - -#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ - GMOCK_PP_REMOVE_PARENS(_Signature)) \ - gmock_a##_i - -#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - ::std::forward( \ - gmock_a##_i) - -#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - GMOCK_INTERNAL_MATCHER_O(typename, GMOCK_PP_INC(_i), \ - GMOCK_PP_REMOVE_PARENS(_Signature)) \ - gmock_a##_i - -#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ - GMOCK_PP_COMMA_IF(_i) \ - gmock_a##_i - -#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - ::testing::A() - -#define GMOCK_INTERNAL_ARG_O(_tn, _i, ...) GMOCK_ARG_(_tn, _i, __VA_ARGS__) - -#define GMOCK_INTERNAL_MATCHER_O(_tn, _i, ...) \ - GMOCK_MATCHER_(_tn, _i, __VA_ARGS__) - -#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-actions.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-actions.h deleted file mode 100644 index 20b78cd43..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-actions.h +++ /dev/null @@ -1,1757 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-actions.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic actions. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ - -#include -#include - -#include "gmock/gmock-actions.h" -#include "gmock/internal/gmock-port.h" - -// The ACTION* family of macros can be used in a namespace scope to -// define custom actions easily. The syntax: -// -// ACTION(name) { statements; } -// -// will define an action with the given name that executes the -// statements. The value returned by the statements will be used as -// the return value of the action. Inside the statements, you can -// refer to the K-th (0-based) argument of the mock function by -// 'argK', and refer to its type by 'argK_type'. For example: -// -// ACTION(IncrementArg1) { -// arg1_type temp = arg1; -// return ++(*temp); -// } -// -// allows you to write -// -// ...WillOnce(IncrementArg1()); -// -// You can also refer to the entire argument tuple and its type by -// 'args' and 'args_type', and refer to the mock function type and its -// return type by 'function_type' and 'return_type'. -// -// Note that you don't need to specify the types of the mock function -// arguments. However rest assured that your code is still type-safe: -// you'll get a compiler error if *arg1 doesn't support the ++ -// operator, or if the type of ++(*arg1) isn't compatible with the -// mock function's return type, for example. -// -// Sometimes you'll want to parameterize the action. For that you can use -// another macro: -// -// ACTION_P(name, param_name) { statements; } -// -// For example: -// -// ACTION_P(Add, n) { return arg0 + n; } -// -// will allow you to write: -// -// ...WillOnce(Add(5)); -// -// Note that you don't need to provide the type of the parameter -// either. If you need to reference the type of a parameter named -// 'foo', you can write 'foo_type'. For example, in the body of -// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type -// of 'n'. -// -// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support -// multi-parameter actions. -// -// For the purpose of typing, you can view -// -// ACTION_Pk(Foo, p1, ..., pk) { ... } -// -// as shorthand for -// -// template -// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } -// -// In particular, you can provide the template type arguments -// explicitly when invoking Foo(), as in Foo(5, false); -// although usually you can rely on the compiler to infer the types -// for you automatically. You can assign the result of expression -// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. -// -// You can also overload actions with different numbers of parameters: -// -// ACTION_P(Plus, a) { ... } -// ACTION_P2(Plus, a, b) { ... } -// -// While it's tempting to always use the ACTION* macros when defining -// a new action, you should also consider implementing ActionInterface -// or using MakePolymorphicAction() instead, especially if you need to -// use the action a lot. While these approaches require more work, -// they give you more control on the types of the mock function -// arguments and the action parameters, which in general leads to -// better compiler error messages that pay off in the long run. They -// also allow overloading actions based on parameter types (as opposed -// to just based on the number of parameters). -// -// CAVEAT: -// -// ACTION*() can only be used in a namespace scope as templates cannot be -// declared inside of a local class. -// Users can, however, define any local functors (e.g. a lambda) that -// can be used as actions. -// -// MORE INFORMATION: -// -// To learn more about using these macros, please search for 'ACTION' on -// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md - -// An internal macro needed for implementing ACTION*(). -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ - const args_type& args GTEST_ATTRIBUTE_UNUSED_, \ - const arg0_type& arg0 GTEST_ATTRIBUTE_UNUSED_, \ - const arg1_type& arg1 GTEST_ATTRIBUTE_UNUSED_, \ - const arg2_type& arg2 GTEST_ATTRIBUTE_UNUSED_, \ - const arg3_type& arg3 GTEST_ATTRIBUTE_UNUSED_, \ - const arg4_type& arg4 GTEST_ATTRIBUTE_UNUSED_, \ - const arg5_type& arg5 GTEST_ATTRIBUTE_UNUSED_, \ - const arg6_type& arg6 GTEST_ATTRIBUTE_UNUSED_, \ - const arg7_type& arg7 GTEST_ATTRIBUTE_UNUSED_, \ - const arg8_type& arg8 GTEST_ATTRIBUTE_UNUSED_, \ - const arg9_type& arg9 GTEST_ATTRIBUTE_UNUSED_ - -// Sometimes you want to give an action explicit template parameters -// that cannot be inferred from its value parameters. ACTION() and -// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that -// and can be viewed as an extension to ACTION() and ACTION_P*(). -// -// The syntax: -// -// ACTION_TEMPLATE(ActionName, -// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), -// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -// -// defines an action template that takes m explicit template -// parameters and n value parameters. name_i is the name of the i-th -// template parameter, and kind_i specifies whether it's a typename, -// an integral constant, or a template. p_i is the name of the i-th -// value parameter. -// -// Example: -// -// // DuplicateArg(output) converts the k-th argument of the mock -// // function to type T and copies it to *output. -// ACTION_TEMPLATE(DuplicateArg, -// HAS_2_TEMPLATE_PARAMS(int, k, typename, T), -// AND_1_VALUE_PARAMS(output)) { -// *output = T(::std::get(args)); -// } -// ... -// int n; -// EXPECT_CALL(mock, Foo(_, _)) -// .WillOnce(DuplicateArg<1, unsigned char>(&n)); -// -// To create an instance of an action template, write: -// -// ActionName(v1, ..., v_n) -// -// where the ts are the template arguments and the vs are the value -// arguments. The value argument types are inferred by the compiler. -// If you want to explicitly specify the value argument types, you can -// provide additional template arguments: -// -// ActionName(v1, ..., v_n) -// -// where u_i is the desired type of v_i. -// -// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the -// number of value parameters, but not on the number of template -// parameters. Without the restriction, the meaning of the following -// is unclear: -// -// OverloadedAction(x); -// -// Are we using a single-template-parameter action where 'bool' refers -// to the type of x, or are we using a two-template-parameter action -// where the compiler is asked to infer the type of x? -// -// Implementation notes: -// -// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and -// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for -// implementing ACTION_TEMPLATE. The main trick we use is to create -// new macro invocations when expanding a macro. For example, we have -// -// #define ACTION_TEMPLATE(name, template_params, value_params) -// ... GMOCK_INTERNAL_DECL_##template_params ... -// -// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...) -// to expand to -// -// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ... -// -// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the -// preprocessor will continue to expand it to -// -// ... typename T ... -// -// This technique conforms to the C++ standard and is portable. It -// allows us to implement action templates using O(N) code, where N is -// the maximum number of template/value parameters supported. Without -// using it, we'd have to devote O(N^2) amount of code to implement all -// combinations of m and n. - -// Declares the template parameters. -#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 -#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) kind0 name0, kind1 name1 -#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) kind0 name0, kind1 name1, kind2 name2 -#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3 -#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ - kind2 name2, kind3 name3, kind4 name4 -#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 -#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ - kind5 name5, kind6 name6 -#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ - kind4 name4, kind5 name5, kind6 name6, kind7 name7 -#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ - kind8 name8 -#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ - kind6 name6, kind7 name7, kind8 name8, kind9 name9 - -// Lists the template parameters. -#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 -#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) name0, name1 -#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) name0, name1, name2 -#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) name0, name1, name2, name3 -#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ - name4 -#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ - name2, name3, name4, name5 -#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) name0, name1, name2, name3, name4, name5, name6 -#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 -#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ - name6, name7, name8 -#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ - name3, name4, name5, name6, name7, name8, name9 - -// Declares the types of value parameters. -#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ - typename p0##_type, typename p1##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ - typename p0##_type, typename p1##_type, typename p2##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type, typename p8##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \ - typename p2##_type, typename p3##_type, typename p4##_type, \ - typename p5##_type, typename p6##_type, typename p7##_type, \ - typename p8##_type, typename p9##_type - -// Initializes the value parameters. -#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ - () -#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ - (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) -#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ - (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)) -#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ - (p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) -#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)) -#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) -#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)) -#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) -#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)) -#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) -#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \ - p9(::std::move(gmock_p9)) - -// Declares the fields for storing the value parameters. -#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; -#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ - p1##_type p1; -#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ - p1##_type p1; p2##_type p2; -#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ - p1##_type p1; p2##_type p2; p3##_type p3; -#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; -#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; -#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; -#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; p7##_type p7; -#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; -#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ - p9##_type p9; - -// Lists the value parameters. -#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0 -#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 -#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 -#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 -#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \ - p2, p3, p4 -#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ - p1, p2, p3, p4, p5 -#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0, p1, p2, p3, p4, p5, p6 -#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0, p1, p2, p3, p4, p5, p6, p7 -#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 -#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 - -// Lists the value parameter types. -#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ - p1##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ - p1##_type, p2##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - p0##_type, p1##_type, p2##_type, p3##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ - p6##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type, p9##_type - -// Declares the value parameters. -#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 -#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ - p1##_type p1 -#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ - p1##_type p1, p2##_type p2 -#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3 -#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 -#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5 -#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6 -#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6, p7##_type p7 -#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 -#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9 - -// The suffix of the class template implementing the action template. -#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P -#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2 -#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3 -#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4 -#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5 -#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 -#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 -#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) P8 -#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) P9 -#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) P10 - -// The name of the class template implementing the action template. -#define GMOCK_ACTION_CLASS_(name, value_params)\ - GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) - -#define ACTION_TEMPLATE(name, template_params, value_params)\ - template \ - class GMOCK_ACTION_CLASS_(name, value_params) {\ - public:\ - explicit GMOCK_ACTION_CLASS_(name, value_params)\ - GMOCK_INTERNAL_INIT_##value_params {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(\ - new gmock_Impl(GMOCK_INTERNAL_LIST_##value_params));\ - }\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\ - };\ - template \ - inline GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\ - GMOCK_INTERNAL_DECL_##value_params) {\ - return GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>(\ - GMOCK_INTERNAL_LIST_##value_params);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::\ - gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION(name)\ - class name##Action {\ - public:\ - name##Action() {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl() {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl());\ - }\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##Action);\ - };\ - inline name##Action name() {\ - return name##Action();\ - }\ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##Action::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P(name, p0)\ - template \ - class name##ActionP {\ - public:\ - explicit name##ActionP(p0##_type gmock_p0) : \ - p0(::std::forward(gmock_p0)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl(p0##_type gmock_p0) : \ - p0(::std::forward(gmock_p0)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0));\ - }\ - p0##_type p0;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP);\ - };\ - template \ - inline name##ActionP name(p0##_type p0) {\ - return name##ActionP(p0);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P2(name, p0, p1)\ - template \ - class name##ActionP2 {\ - public:\ - name##ActionP2(p0##_type gmock_p0, \ - p1##_type gmock_p1) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, \ - p1##_type gmock_p1) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP2);\ - };\ - template \ - inline name##ActionP2 name(p0##_type p0, \ - p1##_type p1) {\ - return name##ActionP2(p0, p1);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP2::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P3(name, p0, p1, p2)\ - template \ - class name##ActionP3 {\ - public:\ - name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP3);\ - };\ - template \ - inline name##ActionP3 name(p0##_type p0, \ - p1##_type p1, p2##_type p2) {\ - return name##ActionP3(p0, p1, p2);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP3::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P4(name, p0, p1, p2, p3)\ - template \ - class name##ActionP4 {\ - public:\ - name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP4);\ - };\ - template \ - inline name##ActionP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3) {\ - return name##ActionP4(p0, p1, \ - p2, p3);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP4::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P5(name, p0, p1, p2, p3, p4)\ - template \ - class name##ActionP5 {\ - public:\ - name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP5);\ - };\ - template \ - inline name##ActionP5 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4) {\ - return name##ActionP5(p0, p1, p2, p3, p4);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP5::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\ - template \ - class name##ActionP6 {\ - public:\ - name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP6);\ - };\ - template \ - inline name##ActionP6 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3, p4##_type p4, p5##_type p5) {\ - return name##ActionP6(p0, p1, p2, p3, p4, p5);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP6::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\ - template \ - class name##ActionP7 {\ - public:\ - name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP7);\ - };\ - template \ - inline name##ActionP7 name(p0##_type p0, p1##_type p1, \ - p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6) {\ - return name##ActionP7(p0, p1, p2, p3, p4, p5, p6);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP7::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\ - template \ - class name##ActionP8 {\ - public:\ - name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP8);\ - };\ - template \ - inline name##ActionP8 name(p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6, p7##_type p7) {\ - return name##ActionP8(p0, p1, p2, p3, p4, p5, \ - p6, p7);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP8::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\ - template \ - class name##ActionP9 {\ - public:\ - name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP9);\ - };\ - template \ - inline name##ActionP9 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ - p8##_type p8) {\ - return name##ActionP9(p0, p1, p2, \ - p3, p4, p5, p6, p7, p8);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP9::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\ - template \ - class name##ActionP10 {\ - public:\ - name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)), \ - p9(::std::forward(gmock_p9)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)), \ - p9(::std::forward(gmock_p9)) {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP10);\ - };\ - template \ - inline name##ActionP10 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9) {\ - return name##ActionP10(p0, \ - p1, p2, p3, p4, p5, p6, p7, p8, p9);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP10::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -namespace testing { - - -// The ACTION*() macros trigger warning C4100 (unreferenced formal -// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in -// the macro definition, as the warnings are generated when the macro -// is expanded and macro expansion cannot contain #pragma. Therefore -// we suppress them here. -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -#endif - -// Various overloads for InvokeArgument(). -// -// The InvokeArgument(a1, a2, ..., a_k) action invokes the N-th -// (0-based) argument, which must be a k-ary callable, of the mock -// function, with arguments a1, a2, ..., a_k. -// -// Notes: -// -// 1. The arguments are passed by value by default. If you need to -// pass an argument by reference, wrap it inside ByRef(). For -// example, -// -// InvokeArgument<1>(5, string("Hello"), ByRef(foo)) -// -// passes 5 and string("Hello") by value, and passes foo by -// reference. -// -// 2. If the callable takes an argument by reference but ByRef() is -// not used, it will receive the reference to a copy of the value, -// instead of the original value. For example, when the 0-th -// argument of the mock function takes a const string&, the action -// -// InvokeArgument<0>(string("Hello")) -// -// makes a copy of the temporary string("Hello") object and passes a -// reference of the copy, instead of the original temporary object, -// to the callable. This makes it easy for a user to define an -// InvokeArgument action from temporary values and have it performed -// later. - -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/gmock-generated-actions.h header. - -template -R InvokeArgumentAdl(AdlTag, F f) { - return f(); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1) { - return f(a1); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) { - return f(a1, a2); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { - return f(a1, a2, a3); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { - return f(a1, a2, a3, a4); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { - return f(a1, a2, a3, a4, a5); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { - return f(a1, a2, a3, a4, a5, a6); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7) { - return f(a1, a2, a3, a4, a5, a6, a7); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8) { - return f(a1, a2, a3, a4, a5, a6, a7, a8); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9, A10 a10) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); -} -} // namespace invoke_argument -} // namespace internal - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args)); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(p0)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_2_VALUE_PARAMS(p0, p1)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_3_VALUE_PARAMS(p0, p1, p2)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); -} - -// Various overloads for ReturnNew(). -// -// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new -// instance of type T, constructed on the heap with constructor arguments -// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_0_VALUE_PARAMS()) { - return new T(); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_1_VALUE_PARAMS(p0)) { - return new T(p0); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_2_VALUE_PARAMS(p0, p1)) { - return new T(p0, p1); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_3_VALUE_PARAMS(p0, p1, p2)) { - return new T(p0, p1, p2); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { - return new T(p0, p1, p2, p3); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { - return new T(p0, p1, p2, p3, p4); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { - return new T(p0, p1, p2, p3, p4, p5); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { - return new T(p0, p1, p2, p3, p4, p5, p6); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { - return new T(p0, p1, p2, p3, p4, p5, p6, p7); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { - return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { - return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); -} - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -} // namespace testing - -// Include any custom callback actions added by the local installation. -// We must include this header at the end to make sure it can use the -// declarations from this file. -#include "gmock/internal/custom/gmock-generated-actions.h" - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-actions.h.pump b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-actions.h.pump deleted file mode 100644 index 1121fbdec..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-actions.h.pump +++ /dev/null @@ -1,579 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert it to -$$ gmock-generated-actions.h. -$$ -$var n = 10 $$ The maximum arity we support. -$$}} This meta comment fixes auto-indentation in editors. -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic actions. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ - -#include -#include - -#include "gmock/gmock-actions.h" -#include "gmock/internal/gmock-port.h" - -// The ACTION* family of macros can be used in a namespace scope to -// define custom actions easily. The syntax: -// -// ACTION(name) { statements; } -// -// will define an action with the given name that executes the -// statements. The value returned by the statements will be used as -// the return value of the action. Inside the statements, you can -// refer to the K-th (0-based) argument of the mock function by -// 'argK', and refer to its type by 'argK_type'. For example: -// -// ACTION(IncrementArg1) { -// arg1_type temp = arg1; -// return ++(*temp); -// } -// -// allows you to write -// -// ...WillOnce(IncrementArg1()); -// -// You can also refer to the entire argument tuple and its type by -// 'args' and 'args_type', and refer to the mock function type and its -// return type by 'function_type' and 'return_type'. -// -// Note that you don't need to specify the types of the mock function -// arguments. However rest assured that your code is still type-safe: -// you'll get a compiler error if *arg1 doesn't support the ++ -// operator, or if the type of ++(*arg1) isn't compatible with the -// mock function's return type, for example. -// -// Sometimes you'll want to parameterize the action. For that you can use -// another macro: -// -// ACTION_P(name, param_name) { statements; } -// -// For example: -// -// ACTION_P(Add, n) { return arg0 + n; } -// -// will allow you to write: -// -// ...WillOnce(Add(5)); -// -// Note that you don't need to provide the type of the parameter -// either. If you need to reference the type of a parameter named -// 'foo', you can write 'foo_type'. For example, in the body of -// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type -// of 'n'. -// -// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P$n to support -// multi-parameter actions. -// -// For the purpose of typing, you can view -// -// ACTION_Pk(Foo, p1, ..., pk) { ... } -// -// as shorthand for -// -// template -// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } -// -// In particular, you can provide the template type arguments -// explicitly when invoking Foo(), as in Foo(5, false); -// although usually you can rely on the compiler to infer the types -// for you automatically. You can assign the result of expression -// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. -// -// You can also overload actions with different numbers of parameters: -// -// ACTION_P(Plus, a) { ... } -// ACTION_P2(Plus, a, b) { ... } -// -// While it's tempting to always use the ACTION* macros when defining -// a new action, you should also consider implementing ActionInterface -// or using MakePolymorphicAction() instead, especially if you need to -// use the action a lot. While these approaches require more work, -// they give you more control on the types of the mock function -// arguments and the action parameters, which in general leads to -// better compiler error messages that pay off in the long run. They -// also allow overloading actions based on parameter types (as opposed -// to just based on the number of parameters). -// -// CAVEAT: -// -// ACTION*() can only be used in a namespace scope as templates cannot be -// declared inside of a local class. -// Users can, however, define any local functors (e.g. a lambda) that -// can be used as actions. -// -// MORE INFORMATION: -// -// To learn more about using these macros, please search for 'ACTION' on -// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md - -$range i 0..n -$range k 0..n-1 - -// An internal macro needed for implementing ACTION*(). -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ - const args_type& args GTEST_ATTRIBUTE_UNUSED_ -$for k [[, \ - const arg$k[[]]_type& arg$k GTEST_ATTRIBUTE_UNUSED_]] - - -// Sometimes you want to give an action explicit template parameters -// that cannot be inferred from its value parameters. ACTION() and -// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that -// and can be viewed as an extension to ACTION() and ACTION_P*(). -// -// The syntax: -// -// ACTION_TEMPLATE(ActionName, -// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), -// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -// -// defines an action template that takes m explicit template -// parameters and n value parameters. name_i is the name of the i-th -// template parameter, and kind_i specifies whether it's a typename, -// an integral constant, or a template. p_i is the name of the i-th -// value parameter. -// -// Example: -// -// // DuplicateArg(output) converts the k-th argument of the mock -// // function to type T and copies it to *output. -// ACTION_TEMPLATE(DuplicateArg, -// HAS_2_TEMPLATE_PARAMS(int, k, typename, T), -// AND_1_VALUE_PARAMS(output)) { -// *output = T(::std::get(args)); -// } -// ... -// int n; -// EXPECT_CALL(mock, Foo(_, _)) -// .WillOnce(DuplicateArg<1, unsigned char>(&n)); -// -// To create an instance of an action template, write: -// -// ActionName(v1, ..., v_n) -// -// where the ts are the template arguments and the vs are the value -// arguments. The value argument types are inferred by the compiler. -// If you want to explicitly specify the value argument types, you can -// provide additional template arguments: -// -// ActionName(v1, ..., v_n) -// -// where u_i is the desired type of v_i. -// -// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the -// number of value parameters, but not on the number of template -// parameters. Without the restriction, the meaning of the following -// is unclear: -// -// OverloadedAction(x); -// -// Are we using a single-template-parameter action where 'bool' refers -// to the type of x, or are we using a two-template-parameter action -// where the compiler is asked to infer the type of x? -// -// Implementation notes: -// -// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and -// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for -// implementing ACTION_TEMPLATE. The main trick we use is to create -// new macro invocations when expanding a macro. For example, we have -// -// #define ACTION_TEMPLATE(name, template_params, value_params) -// ... GMOCK_INTERNAL_DECL_##template_params ... -// -// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...) -// to expand to -// -// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ... -// -// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the -// preprocessor will continue to expand it to -// -// ... typename T ... -// -// This technique conforms to the C++ standard and is portable. It -// allows us to implement action templates using O(N) code, where N is -// the maximum number of template/value parameters supported. Without -// using it, we'd have to devote O(N^2) amount of code to implement all -// combinations of m and n. - -// Declares the template parameters. - -$range j 1..n -$for j [[ -$range m 0..j-1 -#define GMOCK_INTERNAL_DECL_HAS_$j[[]] -_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[kind$m name$m]] - - -]] - -// Lists the template parameters. - -$for j [[ -$range m 0..j-1 -#define GMOCK_INTERNAL_LIST_HAS_$j[[]] -_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[name$m]] - - -]] - -// Declares the types of value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_DECL_TYPE_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]] - - -]] - -// Initializes the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\ - ($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::std::move(gmock_p$j))]] - - -]] - -// Declares the fields for storing the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_DEFN_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j [[p$j##_type p$j; ]] - - -]] - -// Lists the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_LIST_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j, [[p$j]] - - -]] - -// Lists the value parameter types. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_LIST_TYPE_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j [[, p$j##_type]] - - -]] - -// Declares the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_DECL_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]] -$for j, [[p$j##_type p$j]] - - -]] - -// The suffix of the class template implementing the action template. -$for i [[ - - -$range j 0..i-1 -#define GMOCK_INTERNAL_COUNT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]] -$if i==1 [[P]] $elif i>=2 [[P$i]] -]] - - -// The name of the class template implementing the action template. -#define GMOCK_ACTION_CLASS_(name, value_params)\ - GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) - -$range k 0..n-1 - -#define ACTION_TEMPLATE(name, template_params, value_params)\ - template \ - class GMOCK_ACTION_CLASS_(name, value_params) {\ - public:\ - explicit GMOCK_ACTION_CLASS_(name, value_params)\ - GMOCK_INTERNAL_INIT_##value_params {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template <$for k, [[typename arg$k[[]]_type]]>\ - return_type gmock_PerformImpl(const args_type& args[[]] -$for k [[, const arg$k[[]]_type& arg$k]]) const;\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(\ - new gmock_Impl(GMOCK_INTERNAL_LIST_##value_params));\ - }\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\ - };\ - template \ - inline GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\ - GMOCK_INTERNAL_DECL_##value_params) {\ - return GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>(\ - GMOCK_INTERNAL_LIST_##value_params);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::\ - gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -$for i - -[[ -$var template = [[$if i==0 [[]] $else [[ -$range j 0..i-1 - - template <$for j, [[typename p$j##_type]]>\ -]]]] -$var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]] - $else [[P$i]]]]]] -$range j 0..i-1 -$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] -$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]] -$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::forward(gmock_p$j))]]]]]] -$var param_field_decls = [[$for j -[[ - - p$j##_type p$j;\ -]]]] -$var param_field_decls2 = [[$for j -[[ - - p$j##_type p$j;\ -]]]] -$var params = [[$for j, [[p$j]]]] -$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]] -$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]] -$var arg_types_and_names = [[$for k, [[const arg$k[[]]_type& arg$k]]]] -$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]] - $else [[ACTION_P$i]]]] - -#define $macro_name(name$for j [[, p$j]])\$template - class $class_name {\ - public:\ - [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - [[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\ - return_type Perform(const args_type& args) override {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template <$typename_arg_types>\ - return_type gmock_PerformImpl(const args_type& args, [[]] -$arg_types_and_names) const;\$param_field_decls - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl($params));\ - }\$param_field_decls2 - private:\ - GTEST_DISALLOW_ASSIGN_($class_name);\ - };\$template - inline $class_name$param_types name($param_types_and_names) {\ - return $class_name$param_types($params);\ - }\$template - template \ - template <$typename_arg_types>\ - typename ::testing::internal::Function::Result\ - $class_name$param_types::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const -]] -$$ } // This meta comment fixes auto-indentation in Emacs. It won't -$$ // show up in the generated code. - - -namespace testing { - - -// The ACTION*() macros trigger warning C4100 (unreferenced formal -// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in -// the macro definition, as the warnings are generated when the macro -// is expanded and macro expansion cannot contain #pragma. Therefore -// we suppress them here. -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -#endif - -// Various overloads for InvokeArgument(). -// -// The InvokeArgument(a1, a2, ..., a_k) action invokes the N-th -// (0-based) argument, which must be a k-ary callable, of the mock -// function, with arguments a1, a2, ..., a_k. -// -// Notes: -// -// 1. The arguments are passed by value by default. If you need to -// pass an argument by reference, wrap it inside ByRef(). For -// example, -// -// InvokeArgument<1>(5, string("Hello"), ByRef(foo)) -// -// passes 5 and string("Hello") by value, and passes foo by -// reference. -// -// 2. If the callable takes an argument by reference but ByRef() is -// not used, it will receive the reference to a copy of the value, -// instead of the original value. For example, when the 0-th -// argument of the mock function takes a const string&, the action -// -// InvokeArgument<0>(string("Hello")) -// -// makes a copy of the temporary string("Hello") object and passes a -// reference of the copy, instead of the original temporary object, -// to the callable. This makes it easy for a user to define an -// InvokeArgument action from temporary values and have it performed -// later. - -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/gmock-generated-actions.h header. - -$range i 0..n -$for i -[[ -$range j 1..i - -template -R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) { - return f([[$for j, [[a$j]]]]); -} -]] - -} // namespace invoke_argument -} // namespace internal - -$range i 0..n -$for i [[ -$range j 0..i-1 - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args)$for j [[, p$j]]); -} - -]] - -// Various overloads for ReturnNew(). -// -// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new -// instance of type T, constructed on the heap with constructor arguments -// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. -$range i 0..n -$for i [[ -$range j 0..i-1 -$var ps = [[$for j, [[p$j]]]] - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_$i[[]]_VALUE_PARAMS($ps)) { - return new T($ps); -} - -]] - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -} // namespace testing - -// Include any custom callback actions added by the local installation. -// We must include this header at the end to make sure it can use the -// declarations from this file. -#include "gmock/internal/custom/gmock-generated-actions.h" - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-function-mockers.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-function-mockers.h deleted file mode 100644 index cd9578178..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-function-mockers.h +++ /dev/null @@ -1,752 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-function-mockers.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements function mockers of various arities. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ - -#include -#include - -#include "gmock/gmock-spec-builders.h" -#include "gmock/internal/gmock-internal-utils.h" - -namespace testing { -namespace internal { -// Removes the given pointer; this is a helper for the expectation setter method -// for parameterless matchers. -// -// We want to make sure that the user cannot set a parameterless expectation on -// overloaded methods, including methods which are overloaded on const. Example: -// -// class MockClass { -// MOCK_METHOD0(GetName, string&()); -// MOCK_CONST_METHOD0(GetName, const string&()); -// }; -// -// TEST() { -// // This should be an error, as it's not clear which overload is expected. -// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value)); -// } -// -// Here are the generated expectation-setter methods: -// -// class MockClass { -// // Overload 1 -// MockSpec gmock_GetName() { ... } -// // Overload 2. Declared const so that the compiler will generate an -// // error when trying to resolve between this and overload 4 in -// // 'gmock_GetName(WithoutMatchers(), nullptr)'. -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Removes const from this, calls overload 1 -// return AdjustConstness_(this)->gmock_GetName(); -// } -// -// // Overload 3 -// const string& gmock_GetName() const { ... } -// // Overload 4 -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Does not remove const, calls overload 3 -// return AdjustConstness_const(this)->gmock_GetName(); -// } -// } -// -template -const MockType* AdjustConstness_const(const MockType* mock) { - return mock; -} - -// Removes const from and returns the given pointer; this is a helper for the -// expectation setter method for parameterless matchers. -template -MockType* AdjustConstness_(const MockType* mock) { - return const_cast(mock); -} - -} // namespace internal - -// The style guide prohibits "using" statements in a namespace scope -// inside a header file. However, the FunctionMocker class template -// is meant to be defined in the ::testing namespace. The following -// line is just a trick for working around a bug in MSVC 8.0, which -// cannot handle it if we define FunctionMocker in ::testing. -using internal::FunctionMocker; - -// GMOCK_RESULT_(tn, F) expands to the result type of function type F. -// We define this as a variadic macro in case F contains unprotected -// commas (the same reason that we use variadic macros in other places -// in this file). -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_RESULT_(tn, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::Result - -// The type of argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_ARG_(tn, N, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::template Arg::type - -// The matcher type for argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MATCHER_(tn, N, ...) \ - const ::testing::Matcher& - -// The variable for mocking the given method. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MOCKER_(arity, constness, Method) \ - GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \ - static_assert(0 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - ) constness { \ - GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(0, constness, Method).Invoke(); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method() constness { \ - GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(0, constness, Method).With(); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \ - static_assert(1 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ - GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(1, constness, \ - Method).Invoke(::std::forward(gmock_a1)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ - GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \ - static_assert(2 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2) constness { \ - GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(2, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ - GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \ - static_assert(3 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, \ - __VA_ARGS__) gmock_a3) constness { \ - GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(3, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ - GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \ - static_assert(4 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ - GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(4, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ - GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \ - static_assert(5 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5) constness { \ - GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(5, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ - GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \ - static_assert(6 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, \ - __VA_ARGS__) gmock_a6) constness { \ - GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(6, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ - GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \ - static_assert(7 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ - GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(7, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ - GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \ - static_assert(8 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ - __VA_ARGS__) gmock_a8) constness { \ - GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(8, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7), \ - ::std::forward(gmock_a8)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ - GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \ - static_assert(9 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ - __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, \ - __VA_ARGS__) gmock_a9) constness { \ - GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(9, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7), \ - ::std::forward(gmock_a8), \ - ::std::forward(gmock_a9)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ - GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ - gmock_a9); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \ - static_assert(10 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ - __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \ - GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ - GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(10, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7), \ - ::std::forward(gmock_a8), \ - ::std::forward(gmock_a9), \ - ::std::forward(gmock_a10)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \ - GMOCK_MATCHER_(tn, 10, \ - __VA_ARGS__) gmock_a10) constness { \ - GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ - gmock_a10); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \ - Method) - -#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__) -#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__) -#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__) -#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__) -#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__) -#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__) -#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__) -#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__) -#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__) -#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__) -#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__) - -#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_T(m, ...) \ - GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_T(m, ...) \ - GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_T(m, ...) \ - GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_T(m, ...) \ - GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_T(m, ...) \ - GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_T(m, ...) \ - GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_T(m, ...) \ - GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_T(m, ...) \ - GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_T(m, ...) \ - GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_T(m, ...) \ - GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_T(m, ...) \ - GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__) - -#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(, , ct, m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__) - -#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__) - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-function-mockers.h.pump deleted file mode 100644 index a56e132f3..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ /dev/null @@ -1,227 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert -$$ it to gmock-generated-function-mockers.h. -$$ -$var n = 10 $$ The maximum arity we support. -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements function mockers of various arities. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ - -#include -#include - -#include "gmock/gmock-spec-builders.h" -#include "gmock/internal/gmock-internal-utils.h" - -namespace testing { -namespace internal { - -$range i 0..n -// Removes the given pointer; this is a helper for the expectation setter method -// for parameterless matchers. -// -// We want to make sure that the user cannot set a parameterless expectation on -// overloaded methods, including methods which are overloaded on const. Example: -// -// class MockClass { -// MOCK_METHOD0(GetName, string&()); -// MOCK_CONST_METHOD0(GetName, const string&()); -// }; -// -// TEST() { -// // This should be an error, as it's not clear which overload is expected. -// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value)); -// } -// -// Here are the generated expectation-setter methods: -// -// class MockClass { -// // Overload 1 -// MockSpec gmock_GetName() { ... } -// // Overload 2. Declared const so that the compiler will generate an -// // error when trying to resolve between this and overload 4 in -// // 'gmock_GetName(WithoutMatchers(), nullptr)'. -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Removes const from this, calls overload 1 -// return AdjustConstness_(this)->gmock_GetName(); -// } -// -// // Overload 3 -// const string& gmock_GetName() const { ... } -// // Overload 4 -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Does not remove const, calls overload 3 -// return AdjustConstness_const(this)->gmock_GetName(); -// } -// } -// -template -const MockType* AdjustConstness_const(const MockType* mock) { - return mock; -} - -// Removes const from and returns the given pointer; this is a helper for the -// expectation setter method for parameterless matchers. -template -MockType* AdjustConstness_(const MockType* mock) { - return const_cast(mock); -} - -} // namespace internal - -// The style guide prohibits "using" statements in a namespace scope -// inside a header file. However, the FunctionMocker class template -// is meant to be defined in the ::testing namespace. The following -// line is just a trick for working around a bug in MSVC 8.0, which -// cannot handle it if we define FunctionMocker in ::testing. -using internal::FunctionMocker; - -// GMOCK_RESULT_(tn, F) expands to the result type of function type F. -// We define this as a variadic macro in case F contains unprotected -// commas (the same reason that we use variadic macros in other places -// in this file). -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_RESULT_(tn, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::Result - -// The type of argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_ARG_(tn, N, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::template Arg::type - -// The matcher type for argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MATCHER_(tn, N, ...) \ - const ::testing::Matcher& - -// The variable for mocking the given method. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MOCKER_(arity, constness, Method) \ - GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) - - -$for i [[ -$range j 1..i -$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]] -$var as = [[$for j, \ - [[::std::forward(gmock_a$j)]]]] -$var matcher_arg_as = [[$for j, \ - [[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]] -$var matcher_as = [[$for j, [[gmock_a$j]]]] -$var anything_matchers = [[$for j, \ - [[::testing::A()]]]] -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \ - static_assert($i == ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - $arg_as) constness { \ - GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method($matcher_arg_as) constness { \ - GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method($anything_matchers); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method) - - -]] -$for i [[ -#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \ - GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__) - -]] - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-matchers.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-matchers.h deleted file mode 100644 index 61892380c..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-matchers.h +++ /dev/null @@ -1,1097 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-matchers.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic matchers. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ - -#include -#include -#include -#include -#include -#include "gmock/gmock-matchers.h" - -// The MATCHER* family of macros can be used in a namespace scope to -// define custom matchers easily. -// -// Basic Usage -// =========== -// -// The syntax -// -// MATCHER(name, description_string) { statements; } -// -// defines a matcher with the given name that executes the statements, -// which must return a bool to indicate if the match succeeds. Inside -// the statements, you can refer to the value being matched by 'arg', -// and refer to its type by 'arg_type'. -// -// The description string documents what the matcher does, and is used -// to generate the failure message when the match fails. Since a -// MATCHER() is usually defined in a header file shared by multiple -// C++ source files, we require the description to be a C-string -// literal to avoid possible side effects. It can be empty, in which -// case we'll use the sequence of words in the matcher name as the -// description. -// -// For example: -// -// MATCHER(IsEven, "") { return (arg % 2) == 0; } -// -// allows you to write -// -// // Expects mock_foo.Bar(n) to be called where n is even. -// EXPECT_CALL(mock_foo, Bar(IsEven())); -// -// or, -// -// // Verifies that the value of some_expression is even. -// EXPECT_THAT(some_expression, IsEven()); -// -// If the above assertion fails, it will print something like: -// -// Value of: some_expression -// Expected: is even -// Actual: 7 -// -// where the description "is even" is automatically calculated from the -// matcher name IsEven. -// -// Argument Type -// ============= -// -// Note that the type of the value being matched (arg_type) is -// determined by the context in which you use the matcher and is -// supplied to you by the compiler, so you don't need to worry about -// declaring it (nor can you). This allows the matcher to be -// polymorphic. For example, IsEven() can be used to match any type -// where the value of "(arg % 2) == 0" can be implicitly converted to -// a bool. In the "Bar(IsEven())" example above, if method Bar() -// takes an int, 'arg_type' will be int; if it takes an unsigned long, -// 'arg_type' will be unsigned long; and so on. -// -// Parameterizing Matchers -// ======================= -// -// Sometimes you'll want to parameterize the matcher. For that you -// can use another macro: -// -// MATCHER_P(name, param_name, description_string) { statements; } -// -// For example: -// -// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -// -// will allow you to write: -// -// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -// -// which may lead to this message (assuming n is 10): -// -// Value of: Blah("a") -// Expected: has absolute value 10 -// Actual: -9 -// -// Note that both the matcher description and its parameter are -// printed, making the message human-friendly. -// -// In the matcher definition body, you can write 'foo_type' to -// reference the type of a parameter named 'foo'. For example, in the -// body of MATCHER_P(HasAbsoluteValue, value) above, you can write -// 'value_type' to refer to the type of 'value'. -// -// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to -// support multi-parameter matchers. -// -// Describing Parameterized Matchers -// ================================= -// -// The last argument to MATCHER*() is a string-typed expression. The -// expression can reference all of the matcher's parameters and a -// special bool-typed variable named 'negation'. When 'negation' is -// false, the expression should evaluate to the matcher's description; -// otherwise it should evaluate to the description of the negation of -// the matcher. For example, -// -// using testing::PrintToString; -// -// MATCHER_P2(InClosedRange, low, hi, -// std::string(negation ? "is not" : "is") + " in range [" + -// PrintToString(low) + ", " + PrintToString(hi) + "]") { -// return low <= arg && arg <= hi; -// } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: is in range [4, 6] -// ... -// Expected: is not in range [2, 4] -// -// If you specify "" as the description, the failure message will -// contain the sequence of words in the matcher name followed by the -// parameter values printed as a tuple. For example, -// -// MATCHER_P2(InClosedRange, low, hi, "") { ... } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: in closed range (4, 6) -// ... -// Expected: not (in closed range (2, 4)) -// -// Types of Matcher Parameters -// =========================== -// -// For the purpose of typing, you can view -// -// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -// -// as shorthand for -// -// template -// FooMatcherPk -// Foo(p1_type p1, ..., pk_type pk) { ... } -// -// When you write Foo(v1, ..., vk), the compiler infers the types of -// the parameters v1, ..., and vk for you. If you are not happy with -// the result of the type inference, you can specify the types by -// explicitly instantiating the template, as in Foo(5, -// false). As said earlier, you don't get to (or need to) specify -// 'arg_type' as that's determined by the context in which the matcher -// is used. You can assign the result of expression Foo(p1, ..., pk) -// to a variable of type FooMatcherPk. This -// can be useful when composing matchers. -// -// While you can instantiate a matcher template with reference types, -// passing the parameters by pointer usually makes your code more -// readable. If, however, you still want to pass a parameter by -// reference, be aware that in the failure message generated by the -// matcher you will see the value of the referenced object but not its -// address. -// -// Explaining Match Results -// ======================== -// -// Sometimes the matcher description alone isn't enough to explain why -// the match has failed or succeeded. For example, when expecting a -// long string, it can be very helpful to also print the diff between -// the expected string and the actual one. To achieve that, you can -// optionally stream additional information to a special variable -// named result_listener, whose type is a pointer to class -// MatchResultListener: -// -// MATCHER_P(EqualsLongString, str, "") { -// if (arg == str) return true; -// -// *result_listener << "the difference: " -/// << DiffStrings(str, arg); -// return false; -// } -// -// Overloading Matchers -// ==================== -// -// You can overload matchers with different numbers of parameters: -// -// MATCHER_P(Blah, a, description_string1) { ... } -// MATCHER_P2(Blah, a, b, description_string2) { ... } -// -// Caveats -// ======= -// -// When defining a new matcher, you should also consider implementing -// MatcherInterface or using MakePolymorphicMatcher(). These -// approaches require more work than the MATCHER* macros, but also -// give you more control on the types of the value being matched and -// the matcher parameters, which may leads to better compiler error -// messages when the matcher is used wrong. They also allow -// overloading matchers based on parameter types (as opposed to just -// based on the number of parameters). -// -// MATCHER*() can only be used in a namespace scope as templates cannot be -// declared inside of a local class. -// -// More Information -// ================ -// -// To learn more about using these macros, please search for 'MATCHER' -// on -// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md - -#define MATCHER(name, description)\ - class name##Matcher {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl()\ - {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple<>()));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl());\ - }\ - name##Matcher() {\ - }\ - private:\ - };\ - inline name##Matcher name() {\ - return name##Matcher();\ - }\ - template \ - bool name##Matcher::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P(name, p0, description)\ - template \ - class name##MatcherP {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - explicit gmock_Impl(p0##_type gmock_p0)\ - : p0(::std::move(gmock_p0)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0));\ - }\ - explicit name##MatcherP(p0##_type gmock_p0) : p0(::std::move(gmock_p0)) {\ - }\ - p0##_type const p0;\ - private:\ - };\ - template \ - inline name##MatcherP name(p0##_type p0) {\ - return name##MatcherP(p0);\ - }\ - template \ - template \ - bool name##MatcherP::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P2(name, p0, p1, description)\ - template \ - class name##MatcherP2 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1));\ - }\ - name##MatcherP2(p0##_type gmock_p0, \ - p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - private:\ - };\ - template \ - inline name##MatcherP2 name(p0##_type p0, \ - p1##_type p1) {\ - return name##MatcherP2(p0, p1);\ - }\ - template \ - template \ - bool name##MatcherP2::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P3(name, p0, p1, p2, description)\ - template \ - class name##MatcherP3 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2));\ - }\ - name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - private:\ - };\ - template \ - inline name##MatcherP3 name(p0##_type p0, \ - p1##_type p1, p2##_type p2) {\ - return name##MatcherP3(p0, p1, p2);\ - }\ - template \ - template \ - bool name##MatcherP3::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P4(name, p0, p1, p2, p3, description)\ - template \ - class name##MatcherP4 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, \ - p1, p2, p3)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3));\ - }\ - name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - private:\ - };\ - template \ - inline name##MatcherP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3) {\ - return name##MatcherP4(p0, \ - p1, p2, p3);\ - }\ - template \ - template \ - bool name##MatcherP4::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\ - template \ - class name##MatcherP5 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4));\ - }\ - name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - private:\ - };\ - template \ - inline name##MatcherP5 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4) {\ - return name##MatcherP5(p0, p1, p2, p3, p4);\ - }\ - template \ - template \ - bool name##MatcherP5::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\ - template \ - class name##MatcherP6 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5));\ - }\ - name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - private:\ - };\ - template \ - inline name##MatcherP6 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3, p4##_type p4, p5##_type p5) {\ - return name##MatcherP6(p0, p1, p2, p3, p4, p5);\ - }\ - template \ - template \ - bool name##MatcherP6::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\ - template \ - class name##MatcherP7 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5, \ - p6)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6));\ - }\ - name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - private:\ - };\ - template \ - inline name##MatcherP7 name(p0##_type p0, p1##_type p1, \ - p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6) {\ - return name##MatcherP7(p0, p1, p2, p3, p4, p5, p6);\ - }\ - template \ - template \ - bool name##MatcherP7::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\ - template \ - class name##MatcherP8 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, \ - p3, p4, p5, p6, p7)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7));\ - }\ - name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - private:\ - };\ - template \ - inline name##MatcherP8 name(p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6, p7##_type p7) {\ - return name##MatcherP8(p0, p1, p2, p3, p4, p5, \ - p6, p7);\ - }\ - template \ - template \ - bool name##MatcherP8::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\ - template \ - class name##MatcherP9 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \ - p8(::std::move(gmock_p8)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8));\ - }\ - name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - private:\ - };\ - template \ - inline name##MatcherP9 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ - p8##_type p8) {\ - return name##MatcherP9(p0, p1, p2, \ - p3, p4, p5, p6, p7, p8);\ - }\ - template \ - template \ - bool name##MatcherP9::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\ - template \ - class name##MatcherP10 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \ - p8(::std::move(gmock_p8)), p9(::std::move(gmock_p9)) {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - p9##_type const p9;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\ - }\ - name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \ - p9(::std::move(gmock_p9)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - p9##_type const p9;\ - private:\ - };\ - template \ - inline name##MatcherP10 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9) {\ - return name##MatcherP10(p0, \ - p1, p2, p3, p4, p5, p6, p7, p8, p9);\ - }\ - template \ - template \ - bool name##MatcherP10::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-matchers.h.pump b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-matchers.h.pump deleted file mode 100644 index 69d2ae418..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-generated-matchers.h.pump +++ /dev/null @@ -1,346 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert -$$ it to gmock-generated-matchers.h. -$$ -$var n = 10 $$ The maximum arity we support. -$$ }} This line fixes auto-indentation of the following code in Emacs. -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic matchers. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ - -#include -#include -#include -#include -#include -#include "gmock/gmock-matchers.h" - -// The MATCHER* family of macros can be used in a namespace scope to -// define custom matchers easily. -// -// Basic Usage -// =========== -// -// The syntax -// -// MATCHER(name, description_string) { statements; } -// -// defines a matcher with the given name that executes the statements, -// which must return a bool to indicate if the match succeeds. Inside -// the statements, you can refer to the value being matched by 'arg', -// and refer to its type by 'arg_type'. -// -// The description string documents what the matcher does, and is used -// to generate the failure message when the match fails. Since a -// MATCHER() is usually defined in a header file shared by multiple -// C++ source files, we require the description to be a C-string -// literal to avoid possible side effects. It can be empty, in which -// case we'll use the sequence of words in the matcher name as the -// description. -// -// For example: -// -// MATCHER(IsEven, "") { return (arg % 2) == 0; } -// -// allows you to write -// -// // Expects mock_foo.Bar(n) to be called where n is even. -// EXPECT_CALL(mock_foo, Bar(IsEven())); -// -// or, -// -// // Verifies that the value of some_expression is even. -// EXPECT_THAT(some_expression, IsEven()); -// -// If the above assertion fails, it will print something like: -// -// Value of: some_expression -// Expected: is even -// Actual: 7 -// -// where the description "is even" is automatically calculated from the -// matcher name IsEven. -// -// Argument Type -// ============= -// -// Note that the type of the value being matched (arg_type) is -// determined by the context in which you use the matcher and is -// supplied to you by the compiler, so you don't need to worry about -// declaring it (nor can you). This allows the matcher to be -// polymorphic. For example, IsEven() can be used to match any type -// where the value of "(arg % 2) == 0" can be implicitly converted to -// a bool. In the "Bar(IsEven())" example above, if method Bar() -// takes an int, 'arg_type' will be int; if it takes an unsigned long, -// 'arg_type' will be unsigned long; and so on. -// -// Parameterizing Matchers -// ======================= -// -// Sometimes you'll want to parameterize the matcher. For that you -// can use another macro: -// -// MATCHER_P(name, param_name, description_string) { statements; } -// -// For example: -// -// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -// -// will allow you to write: -// -// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -// -// which may lead to this message (assuming n is 10): -// -// Value of: Blah("a") -// Expected: has absolute value 10 -// Actual: -9 -// -// Note that both the matcher description and its parameter are -// printed, making the message human-friendly. -// -// In the matcher definition body, you can write 'foo_type' to -// reference the type of a parameter named 'foo'. For example, in the -// body of MATCHER_P(HasAbsoluteValue, value) above, you can write -// 'value_type' to refer to the type of 'value'. -// -// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to -// support multi-parameter matchers. -// -// Describing Parameterized Matchers -// ================================= -// -// The last argument to MATCHER*() is a string-typed expression. The -// expression can reference all of the matcher's parameters and a -// special bool-typed variable named 'negation'. When 'negation' is -// false, the expression should evaluate to the matcher's description; -// otherwise it should evaluate to the description of the negation of -// the matcher. For example, -// -// using testing::PrintToString; -// -// MATCHER_P2(InClosedRange, low, hi, -// std::string(negation ? "is not" : "is") + " in range [" + -// PrintToString(low) + ", " + PrintToString(hi) + "]") { -// return low <= arg && arg <= hi; -// } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: is in range [4, 6] -// ... -// Expected: is not in range [2, 4] -// -// If you specify "" as the description, the failure message will -// contain the sequence of words in the matcher name followed by the -// parameter values printed as a tuple. For example, -// -// MATCHER_P2(InClosedRange, low, hi, "") { ... } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: in closed range (4, 6) -// ... -// Expected: not (in closed range (2, 4)) -// -// Types of Matcher Parameters -// =========================== -// -// For the purpose of typing, you can view -// -// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -// -// as shorthand for -// -// template -// FooMatcherPk -// Foo(p1_type p1, ..., pk_type pk) { ... } -// -// When you write Foo(v1, ..., vk), the compiler infers the types of -// the parameters v1, ..., and vk for you. If you are not happy with -// the result of the type inference, you can specify the types by -// explicitly instantiating the template, as in Foo(5, -// false). As said earlier, you don't get to (or need to) specify -// 'arg_type' as that's determined by the context in which the matcher -// is used. You can assign the result of expression Foo(p1, ..., pk) -// to a variable of type FooMatcherPk. This -// can be useful when composing matchers. -// -// While you can instantiate a matcher template with reference types, -// passing the parameters by pointer usually makes your code more -// readable. If, however, you still want to pass a parameter by -// reference, be aware that in the failure message generated by the -// matcher you will see the value of the referenced object but not its -// address. -// -// Explaining Match Results -// ======================== -// -// Sometimes the matcher description alone isn't enough to explain why -// the match has failed or succeeded. For example, when expecting a -// long string, it can be very helpful to also print the diff between -// the expected string and the actual one. To achieve that, you can -// optionally stream additional information to a special variable -// named result_listener, whose type is a pointer to class -// MatchResultListener: -// -// MATCHER_P(EqualsLongString, str, "") { -// if (arg == str) return true; -// -// *result_listener << "the difference: " -/// << DiffStrings(str, arg); -// return false; -// } -// -// Overloading Matchers -// ==================== -// -// You can overload matchers with different numbers of parameters: -// -// MATCHER_P(Blah, a, description_string1) { ... } -// MATCHER_P2(Blah, a, b, description_string2) { ... } -// -// Caveats -// ======= -// -// When defining a new matcher, you should also consider implementing -// MatcherInterface or using MakePolymorphicMatcher(). These -// approaches require more work than the MATCHER* macros, but also -// give you more control on the types of the value being matched and -// the matcher parameters, which may leads to better compiler error -// messages when the matcher is used wrong. They also allow -// overloading matchers based on parameter types (as opposed to just -// based on the number of parameters). -// -// MATCHER*() can only be used in a namespace scope as templates cannot be -// declared inside of a local class. -// -// More Information -// ================ -// -// To learn more about using these macros, please search for 'MATCHER' -// on -// https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md - -$range i 0..n -$for i - -[[ -$var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]] - $else [[MATCHER_P$i]]]] -$var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]] - $else [[P$i]]]]]] -$range j 0..i-1 -$var template = [[$if i==0 [[]] $else [[ - - template <$for j, [[typename p$j##_type]]>\ -]]]] -$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] -$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] -$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]] -$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]] -$var params = [[$for j, [[p$j]]]] -$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]] -$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]] -$var param_field_decls = [[$for j -[[ - - p$j##_type const p$j;\ -]]]] -$var param_field_decls2 = [[$for j -[[ - - p$j##_type const p$j;\ -]]]] - -#define $macro_name(name$for j [[, p$j]], description)\$template - class $class_name {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\ - $impl_inits {}\ - bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const override;\ - void DescribeTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(false);\ - }\ - void DescribeNegationTo(::std::ostream* gmock_os) const override {\ - *gmock_os << FormatDescription(true);\ - }\$param_field_decls - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl($params));\ - }\ - [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\ - }\$param_field_decls2 - private:\ - };\$template - inline $class_name$param_types name($param_types_and_names) {\ - return $class_name$param_types($params);\ - }\$template - template \ - bool $class_name$param_types::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const -]] - - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-more-actions.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-more-actions.h deleted file mode 100644 index d42484aef..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-more-actions.h +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some actions that depend on gmock-generated-actions.h. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ - -#include -#include - -#include "gmock/gmock-generated-actions.h" - -namespace testing { -namespace internal { - -// An internal replacement for std::copy which mimics its behavior. This is -// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996. -// However Visual Studio 2010 and later do not honor #pragmas which disable that -// warning. -template -inline OutputIterator CopyElements(InputIterator first, - InputIterator last, - OutputIterator output) { - for (; first != last; ++first, ++output) { - *output = *first; - } - return output; -} - -} // namespace internal - -// Various overloads for Invoke(). - -// The ACTION*() macros trigger warning C4100 (unreferenced formal -// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in -// the macro definition, as the warnings are generated when the macro -// is expanded and macro expansion cannot contain #pragma. Therefore -// we suppress them here. -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -#endif - -// Action ReturnArg() returns the k-th argument of the mock function. -ACTION_TEMPLATE(ReturnArg, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { - return ::std::get(args); -} - -// Action SaveArg(pointer) saves the k-th (0-based) argument of the -// mock function to *pointer. -ACTION_TEMPLATE(SaveArg, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(pointer)) { - *pointer = ::std::get(args); -} - -// Action SaveArgPointee(pointer) saves the value pointed to -// by the k-th (0-based) argument of the mock function to *pointer. -ACTION_TEMPLATE(SaveArgPointee, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(pointer)) { - *pointer = *::std::get(args); -} - -// Action SetArgReferee(value) assigns 'value' to the variable -// referenced by the k-th (0-based) argument of the mock function. -ACTION_TEMPLATE(SetArgReferee, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(value)) { - typedef typename ::std::tuple_element::type argk_type; - // Ensures that argument #k is a reference. If you get a compiler - // error on the next line, you are using SetArgReferee(value) in - // a mock function whose k-th (0-based) argument is not a reference. - GTEST_COMPILE_ASSERT_(std::is_reference::value, - SetArgReferee_must_be_used_with_a_reference_argument); - ::std::get(args) = value; -} - -// Action SetArrayArgument(first, last) copies the elements in -// source range [first, last) to the array pointed to by the k-th -// (0-based) argument, which can be either a pointer or an -// iterator. The action does not take ownership of the elements in the -// source range. -ACTION_TEMPLATE(SetArrayArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_2_VALUE_PARAMS(first, last)) { - // Visual Studio deprecates ::std::copy, so we use our own copy in that case. -#ifdef _MSC_VER - internal::CopyElements(first, last, ::std::get(args)); -#else - ::std::copy(first, last, ::std::get(args)); -#endif -} - -// Action DeleteArg() deletes the k-th (0-based) argument of the mock -// function. -ACTION_TEMPLATE(DeleteArg, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { - delete ::std::get(args); -} - -// This action returns the value pointed to by 'pointer'. -ACTION_P(ReturnPointee, pointer) { return *pointer; } - -// Action Throw(exception) can be used in a mock function of any type -// to throw the given exception. Any copyable value can be thrown. -#if GTEST_HAS_EXCEPTIONS - -// Suppresses the 'unreachable code' warning that VC generates in opt modes. -# ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4702) // Temporarily disables warning 4702. -# endif -ACTION_P(Throw, exception) { throw exception; } -# ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -# endif - -#endif // GTEST_HAS_EXCEPTIONS - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-nice-strict.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-nice-strict.h deleted file mode 100644 index 5495a9805..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-nice-strict.h +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Implements class templates NiceMock, NaggyMock, and StrictMock. -// -// Given a mock class MockFoo that is created using Google Mock, -// NiceMock is a subclass of MockFoo that allows -// uninteresting calls (i.e. calls to mock methods that have no -// EXPECT_CALL specs), NaggyMock is a subclass of MockFoo -// that prints a warning when an uninteresting call occurs, and -// StrictMock is a subclass of MockFoo that treats all -// uninteresting calls as errors. -// -// Currently a mock is naggy by default, so MockFoo and -// NaggyMock behave like the same. However, we will soon -// switch the default behavior of mocks to be nice, as that in general -// leads to more maintainable tests. When that happens, MockFoo will -// stop behaving like NaggyMock and start behaving like -// NiceMock. -// -// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of -// their respective base class. Therefore you can write -// NiceMock(5, "a") to construct a nice mock where MockFoo -// has a constructor that accepts (int, const char*), for example. -// -// A known limitation is that NiceMock, NaggyMock, -// and StrictMock only works for mock methods defined using -// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. -// If a mock method is defined in a base class of MockFoo, the "nice" -// or "strict" modifier may not affect it, depending on the compiler. -// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT -// supported. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ - -#include "gmock/gmock-spec-builders.h" -#include "gmock/internal/gmock-port.h" - -namespace testing { - -template -class NiceMock : public MockClass { - public: - NiceMock() : MockClass() { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - // Ideally, we would inherit base class's constructors through a using - // declaration, which would preserve their visibility. However, many existing - // tests rely on the fact that current implementation reexports protected - // constructors as public. These tests would need to be cleaned up first. - - // Single argument constructor is special-cased so that it can be - // made explicit. - template - explicit NiceMock(A&& arg) : MockClass(std::forward(arg)) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NiceMock(A1&& arg1, A2&& arg2, An&&... args) - : MockClass(std::forward(arg1), std::forward(arg2), - std::forward(args)...) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } - - ~NiceMock() { // NOLINT - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); -}; - -template -class NaggyMock : public MockClass { - public: - NaggyMock() : MockClass() { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - // Ideally, we would inherit base class's constructors through a using - // declaration, which would preserve their visibility. However, many existing - // tests rely on the fact that current implementation reexports protected - // constructors as public. These tests would need to be cleaned up first. - - // Single argument constructor is special-cased so that it can be - // made explicit. - template - explicit NaggyMock(A&& arg) : MockClass(std::forward(arg)) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - NaggyMock(A1&& arg1, A2&& arg2, An&&... args) - : MockClass(std::forward(arg1), std::forward(arg2), - std::forward(args)...) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } - - ~NaggyMock() { // NOLINT - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); -}; - -template -class StrictMock : public MockClass { - public: - StrictMock() : MockClass() { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - // Ideally, we would inherit base class's constructors through a using - // declaration, which would preserve their visibility. However, many existing - // tests rely on the fact that current implementation reexports protected - // constructors as public. These tests would need to be cleaned up first. - - // Single argument constructor is special-cased so that it can be - // made explicit. - template - explicit StrictMock(A&& arg) : MockClass(std::forward(arg)) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - template - StrictMock(A1&& arg1, A2&& arg2, An&&... args) - : MockClass(std::forward(arg1), std::forward(arg2), - std::forward(args)...) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } - - ~StrictMock() { // NOLINT - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); -}; - -// The following specializations catch some (relatively more common) -// user errors of nesting nice and strict mocks. They do NOT catch -// all possible errors. - -// These specializations are declared but not defined, as NiceMock, -// NaggyMock, and StrictMock cannot be nested. - -template -class NiceMock >; -template -class NiceMock >; -template -class NiceMock >; - -template -class NaggyMock >; -template -class NaggyMock >; -template -class NaggyMock >; - -template -class StrictMock >; -template -class StrictMock >; -template -class StrictMock >; - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/custom/gmock-generated-actions.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/custom/gmock-generated-actions.h deleted file mode 100644 index 92d910cf0..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/custom/gmock-generated-actions.h +++ /dev/null @@ -1,10 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-actions.h.pump -// DO NOT EDIT BY HAND!!! - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ - -#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump deleted file mode 100644 index 67c221f14..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump +++ /dev/null @@ -1,12 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert -$$ it to callback-actions.h. -$$ -$var max_callback_arity = 5 -$$}} This meta comment fixes auto-indentation in editors. - -// GOOGLETEST_CM0002 DO NOT DELETE -#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ - -#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/gmock-port.h b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/gmock-port.h deleted file mode 100644 index 70872ef39..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/internal/gmock-port.h +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// Low-level types and utilities for porting Google Mock to various -// platforms. All macros ending with _ and symbols defined in an -// internal namespace are subject to change without notice. Code -// outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't -// end with _ are part of Google Mock's public API and can be used by -// code outside Google Mock. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ -#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ - -#include -#include -#include -#include - -// Most of the utilities needed for porting Google Mock are also -// required for Google Test and are defined in gtest-port.h. -// -// Note to maintainers: to reduce code duplication, prefer adding -// portability utilities to Google Test's gtest-port.h instead of -// here, as Google Mock depends on Google Test. Only add a utility -// here if it's truly specific to Google Mock. - -#include "gtest/internal/gtest-port.h" -#include "gmock/internal/custom/gmock-port.h" - -// For MS Visual C++, check the compiler version. At least VS 2015 is -// required to compile Google Mock. -#if defined(_MSC_VER) && _MSC_VER < 1900 -# error "At least Visual C++ 2015 (14.0) is required to compile Google Mock." -#endif - -// Macro for referencing flags. This is public as we want the user to -// use this syntax to reference Google Mock flags. -#define GMOCK_FLAG(name) FLAGS_gmock_##name - -#if !defined(GMOCK_DECLARE_bool_) - -// Macros for declaring flags. -# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) -# define GMOCK_DECLARE_int32_(name) extern GTEST_API_ int32_t GMOCK_FLAG(name) -# define GMOCK_DECLARE_string_(name) \ - extern GTEST_API_ ::std::string GMOCK_FLAG(name) - -// Macros for defining flags. -# define GMOCK_DEFINE_bool_(name, default_val, doc) \ - GTEST_API_ bool GMOCK_FLAG(name) = (default_val) -# define GMOCK_DEFINE_int32_(name, default_val, doc) \ - GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val) -# define GMOCK_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) - -#endif // !defined(GMOCK_DECLARE_bool_) - -#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/README.md b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/README.md deleted file mode 100644 index a3301e5bf..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Please Note: - -Files in this directory are no longer supported by the maintainers. They -represent mostly historical artifacts and supported by the community only. There -is no guarantee whatsoever that these scripts still work. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/fuse_gmock_files.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/fuse_gmock_files.py deleted file mode 100755 index c33c7253f..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/fuse_gmock_files.py +++ /dev/null @@ -1,240 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""fuse_gmock_files.py v0.1.0 -Fuses Google Mock and Google Test source code into two .h files and a .cc file. - -SYNOPSIS - fuse_gmock_files.py [GMOCK_ROOT_DIR] OUTPUT_DIR - - Scans GMOCK_ROOT_DIR for Google Mock and Google Test source - code, assuming Google Test is in the GMOCK_ROOT_DIR/../googletest - directory, and generates three files: - OUTPUT_DIR/gtest/gtest.h, OUTPUT_DIR/gmock/gmock.h, and - OUTPUT_DIR/gmock-gtest-all.cc. Then you can build your tests - by adding OUTPUT_DIR to the include search path and linking - with OUTPUT_DIR/gmock-gtest-all.cc. These three files contain - everything you need to use Google Mock. Hence you can - "install" Google Mock by copying them to wherever you want. - - GMOCK_ROOT_DIR can be omitted and defaults to the parent - directory of the directory holding this script. - -EXAMPLES - ./fuse_gmock_files.py fused_gmock - ./fuse_gmock_files.py path/to/unpacked/gmock fused_gmock - -This tool is experimental. In particular, it assumes that there is no -conditional inclusion of Google Mock or Google Test headers. Please -report any problems to googlemock@googlegroups.com. You can read -https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md for more -information. -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import re -import sets -import sys - -# We assume that this file is in the scripts/ directory in the Google -# Mock root directory. -DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') - -# We need to call into googletest/scripts/fuse_gtest_files.py. -sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, '../googletest/scripts')) -import fuse_gtest_files -gtest = fuse_gtest_files - -# Regex for matching '#include "gmock/..."'. -INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"') - -# Where to find the source seed files. -GMOCK_H_SEED = 'include/gmock/gmock.h' -GMOCK_ALL_CC_SEED = 'src/gmock-all.cc' - -# Where to put the generated files. -GTEST_H_OUTPUT = 'gtest/gtest.h' -GMOCK_H_OUTPUT = 'gmock/gmock.h' -GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc' - - -def GetGTestRootDir(gmock_root): - """Returns the root directory of Google Test.""" - - return os.path.join(gmock_root, '../googletest') - - -def ValidateGMockRootDir(gmock_root): - """Makes sure gmock_root points to a valid gmock root directory. - - The function aborts the program on failure. - """ - - gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root)) - gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED) - gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED) - - -def ValidateOutputDir(output_dir): - """Makes sure output_dir points to a valid output directory. - - The function aborts the program on failure. - """ - - gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT) - gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT) - gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT) - - -def FuseGMockH(gmock_root, output_dir): - """Scans folder gmock_root to generate gmock/gmock.h in output_dir.""" - - output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w') - processed_files = sets.Set() # Holds all gmock headers we've processed. - - def ProcessFile(gmock_header_path): - """Processes the given gmock header file.""" - - # We don't process the same header twice. - if gmock_header_path in processed_files: - return - - processed_files.add(gmock_header_path) - - # Reads each line in the given gmock header. - for line in file(os.path.join(gmock_root, gmock_header_path), 'r'): - m = INCLUDE_GMOCK_FILE_REGEX.match(line) - if m: - # It's '#include "gmock/..."' - let's process it recursively. - ProcessFile('include/' + m.group(1)) - else: - m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line) - if m: - # It's '#include "gtest/foo.h"'. We translate it to - # "gtest/gtest.h", regardless of what foo is, since all - # gtest headers are fused into gtest/gtest.h. - - # There is no need to #include gtest.h twice. - if not gtest.GTEST_H_SEED in processed_files: - processed_files.add(gtest.GTEST_H_SEED) - output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,)) - else: - # Otherwise we copy the line unchanged to the output file. - output_file.write(line) - - ProcessFile(GMOCK_H_SEED) - output_file.close() - - -def FuseGMockAllCcToFile(gmock_root, output_file): - """Scans folder gmock_root to fuse gmock-all.cc into output_file.""" - - processed_files = sets.Set() - - def ProcessFile(gmock_source_file): - """Processes the given gmock source file.""" - - # We don't process the same #included file twice. - if gmock_source_file in processed_files: - return - - processed_files.add(gmock_source_file) - - # Reads each line in the given gmock source file. - for line in file(os.path.join(gmock_root, gmock_source_file), 'r'): - m = INCLUDE_GMOCK_FILE_REGEX.match(line) - if m: - # It's '#include "gmock/foo.h"'. We treat it as '#include - # "gmock/gmock.h"', as all other gmock headers are being fused - # into gmock.h and cannot be #included directly. - - # There is no need to #include "gmock/gmock.h" more than once. - if not GMOCK_H_SEED in processed_files: - processed_files.add(GMOCK_H_SEED) - output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,)) - else: - m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line) - if m: - # It's '#include "gtest/..."'. - # There is no need to #include gtest.h as it has been - # #included by gtest-all.cc. - pass - else: - m = gtest.INCLUDE_SRC_FILE_REGEX.match(line) - if m: - # It's '#include "src/foo"' - let's process it recursively. - ProcessFile(m.group(1)) - else: - # Otherwise we copy the line unchanged to the output file. - output_file.write(line) - - ProcessFile(GMOCK_ALL_CC_SEED) - - -def FuseGMockGTestAllCc(gmock_root, output_dir): - """Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir.""" - - output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w') - # First, fuse gtest-all.cc into gmock-gtest-all.cc. - gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file) - # Next, append fused gmock-all.cc to gmock-gtest-all.cc. - FuseGMockAllCcToFile(gmock_root, output_file) - output_file.close() - - -def FuseGMock(gmock_root, output_dir): - """Fuses gtest.h, gmock.h, and gmock-gtest-all.h.""" - - ValidateGMockRootDir(gmock_root) - ValidateOutputDir(output_dir) - - gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir) - FuseGMockH(gmock_root, output_dir) - FuseGMockGTestAllCc(gmock_root, output_dir) - - -def main(): - argc = len(sys.argv) - if argc == 2: - # fuse_gmock_files.py OUTPUT_DIR - FuseGMock(DEFAULT_GMOCK_ROOT_DIR, sys.argv[1]) - elif argc == 3: - # fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR - FuseGMock(sys.argv[1], sys.argv[2]) - else: - print __doc__ - sys.exit(1) - - -if __name__ == '__main__': - main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/LICENSE b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/LICENSE deleted file mode 100644 index 87ea06365..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/LICENSE +++ /dev/null @@ -1,203 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [2007] Neal Norwitz - Portions Copyright [2007] Google Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/README b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/README deleted file mode 100644 index 01fd463dd..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/README +++ /dev/null @@ -1,34 +0,0 @@ - -The Google Mock class generator is an application that is part of cppclean. -For more information about cppclean, visit http://code.google.com/p/cppclean/ - -The mock generator requires Python 2.3.5 or later. If you don't have Python -installed on your system, you will also need to install it. You can download -Python from: http://www.python.org/download/releases/ - -To use the Google Mock class generator, you need to call it -on the command line passing the header file and class for which you want -to generate a Google Mock class. - -Make sure to install the scripts somewhere in your path. Then you can -run the program. - - gmock_gen.py header-file.h [ClassName]... - -If no ClassNames are specified, all classes in the file are emitted. - -To change the indentation from the default of 2, set INDENT in -the environment. For example to use an indent of 4 spaces: - -INDENT=4 gmock_gen.py header-file.h ClassName - -This version was made from SVN revision 281 in the cppclean repository. - -Known Limitations ------------------ -Not all code will be generated properly. For example, when mocking templated -classes, the template information is lost. You will need to add the template -information manually. - -Not all permutations of using multiple pointers/references will be rendered -properly. These will also have to be fixed manually. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/README.cppclean b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/README.cppclean deleted file mode 100644 index 65431b617..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/README.cppclean +++ /dev/null @@ -1,115 +0,0 @@ -Goal: ------ - CppClean attempts to find problems in C++ source that slow development - in large code bases, for example various forms of unused code. - Unused code can be unused functions, methods, data members, types, etc - to unnecessary #include directives. Unnecessary #includes can cause - considerable extra compiles increasing the edit-compile-run cycle. - - The project home page is: http://code.google.com/p/cppclean/ - - -Features: ---------- - * Find and print C++ language constructs: classes, methods, functions, etc. - * Find classes with virtual methods, no virtual destructor, and no bases - * Find global/static data that are potential problems when using threads - * Unnecessary forward class declarations - * Unnecessary function declarations - * Undeclared function definitions - * (planned) Find unnecessary header files #included - - No direct reference to anything in the header - - Header is unnecessary if classes were forward declared instead - * (planned) Source files that reference headers not directly #included, - ie, files that rely on a transitive #include from another header - * (planned) Unused members (private, protected, & public) methods and data - * (planned) Store AST in a SQL database so relationships can be queried - -AST is Abstract Syntax Tree, a representation of parsed source code. -http://en.wikipedia.org/wiki/Abstract_syntax_tree - - -System Requirements: --------------------- - * Python 2.4 or later (2.3 probably works too) - * Works on Windows (untested), Mac OS X, and Unix - - -How to Run: ------------ - For all examples, it is assumed that cppclean resides in a directory called - /cppclean. - - To print warnings for classes with virtual methods, no virtual destructor and - no base classes: - - /cppclean/run.sh nonvirtual_dtors.py file1.h file2.h file3.cc ... - - To print all the functions defined in header file(s): - - /cppclean/run.sh functions.py file1.h file2.h ... - - All the commands take multiple files on the command line. Other programs - include: find_warnings, headers, methods, and types. Some other programs - are available, but used primarily for debugging. - - run.sh is a simple wrapper that sets PYTHONPATH to /cppclean and then - runs the program in /cppclean/cpp/PROGRAM.py. There is currently - no equivalent for Windows. Contributions for a run.bat file - would be greatly appreciated. - - -How to Configure: ------------------ - You can add a siteheaders.py file in /cppclean/cpp to configure where - to look for other headers (typically -I options passed to a compiler). - Currently two values are supported: _TRANSITIVE and GetIncludeDirs. - _TRANSITIVE should be set to a boolean value (True or False) indicating - whether to transitively process all header files. The default is False. - - GetIncludeDirs is a function that takes a single argument and returns - a sequence of directories to include. This can be a generator or - return a static list. - - def GetIncludeDirs(filename): - return ['/some/path/with/other/headers'] - - # Here is a more complicated example. - def GetIncludeDirs(filename): - yield '/path1' - yield os.path.join('/path2', os.path.dirname(filename)) - yield '/path3' - - -How to Test: ------------- - For all examples, it is assumed that cppclean resides in a directory called - /cppclean. The tests require - - cd /cppclean - make test - # To generate expected results after a change: - make expected - - -Current Status: ---------------- - The parser works pretty well for header files, parsing about 99% of Google's - header files. Anything which inspects structure of C++ source files should - work reasonably well. Function bodies are not transformed to an AST, - but left as tokens. Much work is still needed on finding unused header files - and storing an AST in a database. - - -Non-goals: ----------- - * Parsing all valid C++ source - * Handling invalid C++ source gracefully - * Compiling to machine code (or anything beyond an AST) - - -Contact: --------- - If you used cppclean, I would love to hear about your experiences - cppclean@googlegroups.com. Even if you don't use cppclean, I'd like to - hear from you. :-) (You can contact me directly at: nnorwitz@gmail.com) diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/__init__.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/__init__.py deleted file mode 100755 index e69de29bb..000000000 diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/ast.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/ast.py deleted file mode 100755 index f6331d80b..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/ast.py +++ /dev/null @@ -1,1761 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Generate an Abstract Syntax Tree (AST) for C++.""" - -# FIXME: -# * Tokens should never be exported, need to convert to Nodes -# (return types, parameters, etc.) -# * Handle static class data for templatized classes -# * Handle casts (both C++ and C-style) -# * Handle conditions and loops (if/else, switch, for, while/do) -# -# TODO much, much later: -# * Handle #define -# * exceptions - - -try: - # Python 3.x - import builtins -except ImportError: - # Python 2.x - import __builtin__ as builtins - -import sys -import traceback - -from cpp import keywords -from cpp import tokenize -from cpp import utils - - -if not hasattr(builtins, 'reversed'): - # Support Python 2.3 and earlier. - def reversed(seq): - for i in range(len(seq)-1, -1, -1): - yield seq[i] - -if not hasattr(builtins, 'next'): - # Support Python 2.5 and earlier. - def next(obj): - return obj.next() - - -VISIBILITY_PUBLIC, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE = range(3) - -FUNCTION_NONE = 0x00 -FUNCTION_CONST = 0x01 -FUNCTION_VIRTUAL = 0x02 -FUNCTION_PURE_VIRTUAL = 0x04 -FUNCTION_CTOR = 0x08 -FUNCTION_DTOR = 0x10 -FUNCTION_ATTRIBUTE = 0x20 -FUNCTION_UNKNOWN_ANNOTATION = 0x40 -FUNCTION_THROW = 0x80 -FUNCTION_OVERRIDE = 0x100 - -""" -These are currently unused. Should really handle these properly at some point. - -TYPE_MODIFIER_INLINE = 0x010000 -TYPE_MODIFIER_EXTERN = 0x020000 -TYPE_MODIFIER_STATIC = 0x040000 -TYPE_MODIFIER_CONST = 0x080000 -TYPE_MODIFIER_REGISTER = 0x100000 -TYPE_MODIFIER_VOLATILE = 0x200000 -TYPE_MODIFIER_MUTABLE = 0x400000 - -TYPE_MODIFIER_MAP = { - 'inline': TYPE_MODIFIER_INLINE, - 'extern': TYPE_MODIFIER_EXTERN, - 'static': TYPE_MODIFIER_STATIC, - 'const': TYPE_MODIFIER_CONST, - 'register': TYPE_MODIFIER_REGISTER, - 'volatile': TYPE_MODIFIER_VOLATILE, - 'mutable': TYPE_MODIFIER_MUTABLE, - } -""" - -_INTERNAL_TOKEN = 'internal' -_NAMESPACE_POP = 'ns-pop' - - -# TODO(nnorwitz): use this as a singleton for templated_types, etc -# where we don't want to create a new empty dict each time. It is also const. -class _NullDict(object): - __contains__ = lambda self: False - keys = values = items = iterkeys = itervalues = iteritems = lambda self: () - - -# TODO(nnorwitz): move AST nodes into a separate module. -class Node(object): - """Base AST node.""" - - def __init__(self, start, end): - self.start = start - self.end = end - - def IsDeclaration(self): - """Returns bool if this node is a declaration.""" - return False - - def IsDefinition(self): - """Returns bool if this node is a definition.""" - return False - - def IsExportable(self): - """Returns bool if this node exportable from a header file.""" - return False - - def Requires(self, node): - """Does this AST node require the definition of the node passed in?""" - return False - - def XXX__str__(self): - return self._StringHelper(self.__class__.__name__, '') - - def _StringHelper(self, name, suffix): - if not utils.DEBUG: - return '%s(%s)' % (name, suffix) - return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix) - - def __repr__(self): - return str(self) - - -class Define(Node): - def __init__(self, start, end, name, definition): - Node.__init__(self, start, end) - self.name = name - self.definition = definition - - def __str__(self): - value = '%s %s' % (self.name, self.definition) - return self._StringHelper(self.__class__.__name__, value) - - -class Include(Node): - def __init__(self, start, end, filename, system): - Node.__init__(self, start, end) - self.filename = filename - self.system = system - - def __str__(self): - fmt = '"%s"' - if self.system: - fmt = '<%s>' - return self._StringHelper(self.__class__.__name__, fmt % self.filename) - - -class Goto(Node): - def __init__(self, start, end, label): - Node.__init__(self, start, end) - self.label = label - - def __str__(self): - return self._StringHelper(self.__class__.__name__, str(self.label)) - - -class Expr(Node): - def __init__(self, start, end, expr): - Node.__init__(self, start, end) - self.expr = expr - - def Requires(self, node): - # TODO(nnorwitz): impl. - return False - - def __str__(self): - return self._StringHelper(self.__class__.__name__, str(self.expr)) - - -class Return(Expr): - pass - - -class Delete(Expr): - pass - - -class Friend(Expr): - def __init__(self, start, end, expr, namespace): - Expr.__init__(self, start, end, expr) - self.namespace = namespace[:] - - -class Using(Node): - def __init__(self, start, end, names): - Node.__init__(self, start, end) - self.names = names - - def __str__(self): - return self._StringHelper(self.__class__.__name__, str(self.names)) - - -class Parameter(Node): - def __init__(self, start, end, name, parameter_type, default): - Node.__init__(self, start, end) - self.name = name - self.type = parameter_type - self.default = default - - def Requires(self, node): - # TODO(nnorwitz): handle namespaces, etc. - return self.type.name == node.name - - def __str__(self): - name = str(self.type) - suffix = '%s %s' % (name, self.name) - if self.default: - suffix += ' = ' + ''.join([d.name for d in self.default]) - return self._StringHelper(self.__class__.__name__, suffix) - - -class _GenericDeclaration(Node): - def __init__(self, start, end, name, namespace): - Node.__init__(self, start, end) - self.name = name - self.namespace = namespace[:] - - def FullName(self): - prefix = '' - if self.namespace and self.namespace[-1]: - prefix = '::'.join(self.namespace) + '::' - return prefix + self.name - - def _TypeStringHelper(self, suffix): - if self.namespace: - names = [n or '' for n in self.namespace] - suffix += ' in ' + '::'.join(names) - return self._StringHelper(self.__class__.__name__, suffix) - - -# TODO(nnorwitz): merge with Parameter in some way? -class VariableDeclaration(_GenericDeclaration): - def __init__(self, start, end, name, var_type, initial_value, namespace): - _GenericDeclaration.__init__(self, start, end, name, namespace) - self.type = var_type - self.initial_value = initial_value - - def Requires(self, node): - # TODO(nnorwitz): handle namespaces, etc. - return self.type.name == node.name - - def ToString(self): - """Return a string that tries to reconstitute the variable decl.""" - suffix = '%s %s' % (self.type, self.name) - if self.initial_value: - suffix += ' = ' + self.initial_value - return suffix - - def __str__(self): - return self._StringHelper(self.__class__.__name__, self.ToString()) - - -class Typedef(_GenericDeclaration): - def __init__(self, start, end, name, alias, namespace): - _GenericDeclaration.__init__(self, start, end, name, namespace) - self.alias = alias - - def IsDefinition(self): - return True - - def IsExportable(self): - return True - - def Requires(self, node): - # TODO(nnorwitz): handle namespaces, etc. - name = node.name - for token in self.alias: - if token is not None and name == token.name: - return True - return False - - def __str__(self): - suffix = '%s, %s' % (self.name, self.alias) - return self._TypeStringHelper(suffix) - - -class _NestedType(_GenericDeclaration): - def __init__(self, start, end, name, fields, namespace): - _GenericDeclaration.__init__(self, start, end, name, namespace) - self.fields = fields - - def IsDefinition(self): - return True - - def IsExportable(self): - return True - - def __str__(self): - suffix = '%s, {%s}' % (self.name, self.fields) - return self._TypeStringHelper(suffix) - - -class Union(_NestedType): - pass - - -class Enum(_NestedType): - pass - - -class Class(_GenericDeclaration): - def __init__(self, start, end, name, bases, templated_types, body, namespace): - _GenericDeclaration.__init__(self, start, end, name, namespace) - self.bases = bases - self.body = body - self.templated_types = templated_types - - def IsDeclaration(self): - return self.bases is None and self.body is None - - def IsDefinition(self): - return not self.IsDeclaration() - - def IsExportable(self): - return not self.IsDeclaration() - - def Requires(self, node): - # TODO(nnorwitz): handle namespaces, etc. - if self.bases: - for token_list in self.bases: - # TODO(nnorwitz): bases are tokens, do name comparision. - for token in token_list: - if token.name == node.name: - return True - # TODO(nnorwitz): search in body too. - return False - - def __str__(self): - name = self.name - if self.templated_types: - name += '<%s>' % self.templated_types - suffix = '%s, %s, %s' % (name, self.bases, self.body) - return self._TypeStringHelper(suffix) - - -class Struct(Class): - pass - - -class Function(_GenericDeclaration): - def __init__(self, start, end, name, return_type, parameters, - modifiers, templated_types, body, namespace): - _GenericDeclaration.__init__(self, start, end, name, namespace) - converter = TypeConverter(namespace) - self.return_type = converter.CreateReturnType(return_type) - self.parameters = converter.ToParameters(parameters) - self.modifiers = modifiers - self.body = body - self.templated_types = templated_types - - def IsDeclaration(self): - return self.body is None - - def IsDefinition(self): - return self.body is not None - - def IsExportable(self): - if self.return_type and 'static' in self.return_type.modifiers: - return False - return None not in self.namespace - - def Requires(self, node): - if self.parameters: - # TODO(nnorwitz): parameters are tokens, do name comparision. - for p in self.parameters: - if p.name == node.name: - return True - # TODO(nnorwitz): search in body too. - return False - - def __str__(self): - # TODO(nnorwitz): add templated_types. - suffix = ('%s %s(%s), 0x%02x, %s' % - (self.return_type, self.name, self.parameters, - self.modifiers, self.body)) - return self._TypeStringHelper(suffix) - - -class Method(Function): - def __init__(self, start, end, name, in_class, return_type, parameters, - modifiers, templated_types, body, namespace): - Function.__init__(self, start, end, name, return_type, parameters, - modifiers, templated_types, body, namespace) - # TODO(nnorwitz): in_class could also be a namespace which can - # mess up finding functions properly. - self.in_class = in_class - - -class Type(_GenericDeclaration): - """Type used for any variable (eg class, primitive, struct, etc).""" - - def __init__(self, start, end, name, templated_types, modifiers, - reference, pointer, array): - """ - Args: - name: str name of main type - templated_types: [Class (Type?)] template type info between <> - modifiers: [str] type modifiers (keywords) eg, const, mutable, etc. - reference, pointer, array: bools - """ - _GenericDeclaration.__init__(self, start, end, name, []) - self.templated_types = templated_types - if not name and modifiers: - self.name = modifiers.pop() - self.modifiers = modifiers - self.reference = reference - self.pointer = pointer - self.array = array - - def __str__(self): - prefix = '' - if self.modifiers: - prefix = ' '.join(self.modifiers) + ' ' - name = str(self.name) - if self.templated_types: - name += '<%s>' % self.templated_types - suffix = prefix + name - if self.reference: - suffix += '&' - if self.pointer: - suffix += '*' - if self.array: - suffix += '[]' - return self._TypeStringHelper(suffix) - - # By definition, Is* are always False. A Type can only exist in - # some sort of variable declaration, parameter, or return value. - def IsDeclaration(self): - return False - - def IsDefinition(self): - return False - - def IsExportable(self): - return False - - -class TypeConverter(object): - - def __init__(self, namespace_stack): - self.namespace_stack = namespace_stack - - def _GetTemplateEnd(self, tokens, start): - count = 1 - end = start - while 1: - token = tokens[end] - end += 1 - if token.name == '<': - count += 1 - elif token.name == '>': - count -= 1 - if count == 0: - break - return tokens[start:end-1], end - - def ToType(self, tokens): - """Convert [Token,...] to [Class(...), ] useful for base classes. - For example, code like class Foo : public Bar { ... }; - the "Bar" portion gets converted to an AST. - - Returns: - [Class(...), ...] - """ - result = [] - name_tokens = [] - reference = pointer = array = False - - def AddType(templated_types): - # Partition tokens into name and modifier tokens. - names = [] - modifiers = [] - for t in name_tokens: - if keywords.IsKeyword(t.name): - modifiers.append(t.name) - else: - names.append(t.name) - name = ''.join(names) - if name_tokens: - result.append(Type(name_tokens[0].start, name_tokens[-1].end, - name, templated_types, modifiers, - reference, pointer, array)) - del name_tokens[:] - - i = 0 - end = len(tokens) - while i < end: - token = tokens[i] - if token.name == '<': - new_tokens, new_end = self._GetTemplateEnd(tokens, i+1) - AddType(self.ToType(new_tokens)) - # If there is a comma after the template, we need to consume - # that here otherwise it becomes part of the name. - i = new_end - reference = pointer = array = False - elif token.name == ',': - AddType([]) - reference = pointer = array = False - elif token.name == '*': - pointer = True - elif token.name == '&': - reference = True - elif token.name == '[': - pointer = True - elif token.name == ']': - pass - else: - name_tokens.append(token) - i += 1 - - if name_tokens: - # No '<' in the tokens, just a simple name and no template. - AddType([]) - return result - - def DeclarationToParts(self, parts, needs_name_removed): - name = None - default = [] - if needs_name_removed: - # Handle default (initial) values properly. - for i, t in enumerate(parts): - if t.name == '=': - default = parts[i+1:] - name = parts[i-1].name - if name == ']' and parts[i-2].name == '[': - name = parts[i-3].name - i -= 1 - parts = parts[:i-1] - break - else: - if parts[-1].token_type == tokenize.NAME: - name = parts.pop().name - else: - # TODO(nnorwitz): this is a hack that happens for code like - # Register(Foo); where it thinks this is a function call - # but it's actually a declaration. - name = '???' - modifiers = [] - type_name = [] - other_tokens = [] - templated_types = [] - i = 0 - end = len(parts) - while i < end: - p = parts[i] - if keywords.IsKeyword(p.name): - modifiers.append(p.name) - elif p.name == '<': - templated_tokens, new_end = self._GetTemplateEnd(parts, i+1) - templated_types = self.ToType(templated_tokens) - i = new_end - 1 - # Don't add a spurious :: to data members being initialized. - next_index = i + 1 - if next_index < end and parts[next_index].name == '::': - i += 1 - elif p.name in ('[', ']', '='): - # These are handled elsewhere. - other_tokens.append(p) - elif p.name not in ('*', '&', '>'): - # Ensure that names have a space between them. - if (type_name and type_name[-1].token_type == tokenize.NAME and - p.token_type == tokenize.NAME): - type_name.append(tokenize.Token(tokenize.SYNTAX, ' ', 0, 0)) - type_name.append(p) - else: - other_tokens.append(p) - i += 1 - type_name = ''.join([t.name for t in type_name]) - return name, type_name, templated_types, modifiers, default, other_tokens - - def ToParameters(self, tokens): - if not tokens: - return [] - - result = [] - name = type_name = '' - type_modifiers = [] - pointer = reference = array = False - first_token = None - default = [] - - def AddParameter(end): - if default: - del default[0] # Remove flag. - parts = self.DeclarationToParts(type_modifiers, True) - (name, type_name, templated_types, modifiers, - unused_default, unused_other_tokens) = parts - parameter_type = Type(first_token.start, first_token.end, - type_name, templated_types, modifiers, - reference, pointer, array) - p = Parameter(first_token.start, end, name, - parameter_type, default) - result.append(p) - - template_count = 0 - for s in tokens: - if not first_token: - first_token = s - if s.name == '<': - template_count += 1 - elif s.name == '>': - template_count -= 1 - if template_count > 0: - type_modifiers.append(s) - continue - - if s.name == ',': - AddParameter(s.start) - name = type_name = '' - type_modifiers = [] - pointer = reference = array = False - first_token = None - default = [] - elif s.name == '*': - pointer = True - elif s.name == '&': - reference = True - elif s.name == '[': - array = True - elif s.name == ']': - pass # Just don't add to type_modifiers. - elif s.name == '=': - # Got a default value. Add any value (None) as a flag. - default.append(None) - elif default: - default.append(s) - else: - type_modifiers.append(s) - AddParameter(tokens[-1].end) - return result - - def CreateReturnType(self, return_type_seq): - if not return_type_seq: - return None - start = return_type_seq[0].start - end = return_type_seq[-1].end - _, name, templated_types, modifiers, default, other_tokens = \ - self.DeclarationToParts(return_type_seq, False) - names = [n.name for n in other_tokens] - reference = '&' in names - pointer = '*' in names - array = '[' in names - return Type(start, end, name, templated_types, modifiers, - reference, pointer, array) - - def GetTemplateIndices(self, names): - # names is a list of strings. - start = names.index('<') - end = len(names) - 1 - while end > 0: - if names[end] == '>': - break - end -= 1 - return start, end+1 - -class AstBuilder(object): - def __init__(self, token_stream, filename, in_class='', visibility=None, - namespace_stack=[]): - self.tokens = token_stream - self.filename = filename - # TODO(nnorwitz): use a better data structure (deque) for the queue. - # Switching directions of the "queue" improved perf by about 25%. - # Using a deque should be even better since we access from both sides. - self.token_queue = [] - self.namespace_stack = namespace_stack[:] - self.in_class = in_class - if in_class is None: - self.in_class_name_only = None - else: - self.in_class_name_only = in_class.split('::')[-1] - self.visibility = visibility - self.in_function = False - self.current_token = None - # Keep the state whether we are currently handling a typedef or not. - self._handling_typedef = False - - self.converter = TypeConverter(self.namespace_stack) - - def HandleError(self, msg, token): - printable_queue = list(reversed(self.token_queue[-20:])) - sys.stderr.write('Got %s in %s @ %s %s\n' % - (msg, self.filename, token, printable_queue)) - - def Generate(self): - while 1: - token = self._GetNextToken() - if not token: - break - - # Get the next token. - self.current_token = token - - # Dispatch on the next token type. - if token.token_type == _INTERNAL_TOKEN: - if token.name == _NAMESPACE_POP: - self.namespace_stack.pop() - continue - - try: - result = self._GenerateOne(token) - if result is not None: - yield result - except: - self.HandleError('exception', token) - raise - - def _CreateVariable(self, pos_token, name, type_name, type_modifiers, - ref_pointer_name_seq, templated_types, value=None): - reference = '&' in ref_pointer_name_seq - pointer = '*' in ref_pointer_name_seq - array = '[' in ref_pointer_name_seq - var_type = Type(pos_token.start, pos_token.end, type_name, - templated_types, type_modifiers, - reference, pointer, array) - return VariableDeclaration(pos_token.start, pos_token.end, - name, var_type, value, self.namespace_stack) - - def _GenerateOne(self, token): - if token.token_type == tokenize.NAME: - if (keywords.IsKeyword(token.name) and - not keywords.IsBuiltinType(token.name)): - if token.name == 'enum': - # Pop the next token and only put it back if it's not - # 'class'. This allows us to support the two-token - # 'enum class' keyword as if it were simply 'enum'. - next = self._GetNextToken() - if next.name != 'class': - self._AddBackToken(next) - - method = getattr(self, 'handle_' + token.name) - return method() - elif token.name == self.in_class_name_only: - # The token name is the same as the class, must be a ctor if - # there is a paren. Otherwise, it's the return type. - # Peek ahead to get the next token to figure out which. - next = self._GetNextToken() - self._AddBackToken(next) - if next.token_type == tokenize.SYNTAX and next.name == '(': - return self._GetMethod([token], FUNCTION_CTOR, None, True) - # Fall through--handle like any other method. - - # Handle data or function declaration/definition. - syntax = tokenize.SYNTAX - temp_tokens, last_token = \ - self._GetVarTokensUpToIgnoringTemplates(syntax, - '(', ';', '{', '[') - temp_tokens.insert(0, token) - if last_token.name == '(': - # If there is an assignment before the paren, - # this is an expression, not a method. - expr = bool([e for e in temp_tokens if e.name == '=']) - if expr: - new_temp = self._GetTokensUpTo(tokenize.SYNTAX, ';') - temp_tokens.append(last_token) - temp_tokens.extend(new_temp) - last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0) - - if last_token.name == '[': - # Handle array, this isn't a method, unless it's an operator. - # TODO(nnorwitz): keep the size somewhere. - # unused_size = self._GetTokensUpTo(tokenize.SYNTAX, ']') - temp_tokens.append(last_token) - if temp_tokens[-2].name == 'operator': - temp_tokens.append(self._GetNextToken()) - else: - temp_tokens2, last_token = \ - self._GetVarTokensUpTo(tokenize.SYNTAX, ';') - temp_tokens.extend(temp_tokens2) - - if last_token.name == ';': - # Handle data, this isn't a method. - parts = self.converter.DeclarationToParts(temp_tokens, True) - (name, type_name, templated_types, modifiers, default, - unused_other_tokens) = parts - - t0 = temp_tokens[0] - names = [t.name for t in temp_tokens] - if templated_types: - start, end = self.converter.GetTemplateIndices(names) - names = names[:start] + names[end:] - default = ''.join([t.name for t in default]) - return self._CreateVariable(t0, name, type_name, modifiers, - names, templated_types, default) - if last_token.name == '{': - self._AddBackTokens(temp_tokens[1:]) - self._AddBackToken(last_token) - method_name = temp_tokens[0].name - method = getattr(self, 'handle_' + method_name, None) - if not method: - # Must be declaring a variable. - # TODO(nnorwitz): handle the declaration. - return None - return method() - return self._GetMethod(temp_tokens, 0, None, False) - elif token.token_type == tokenize.SYNTAX: - if token.name == '~' and self.in_class: - # Must be a dtor (probably not in method body). - token = self._GetNextToken() - # self.in_class can contain A::Name, but the dtor will only - # be Name. Make sure to compare against the right value. - if (token.token_type == tokenize.NAME and - token.name == self.in_class_name_only): - return self._GetMethod([token], FUNCTION_DTOR, None, True) - # TODO(nnorwitz): handle a lot more syntax. - elif token.token_type == tokenize.PREPROCESSOR: - # TODO(nnorwitz): handle more preprocessor directives. - # token starts with a #, so remove it and strip whitespace. - name = token.name[1:].lstrip() - if name.startswith('include'): - # Remove "include". - name = name[7:].strip() - assert name - # Handle #include \ "header-on-second-line.h". - if name.startswith('\\'): - name = name[1:].strip() - assert name[0] in '<"', token - assert name[-1] in '>"', token - system = name[0] == '<' - filename = name[1:-1] - return Include(token.start, token.end, filename, system) - if name.startswith('define'): - # Remove "define". - name = name[6:].strip() - assert name - value = '' - for i, c in enumerate(name): - if c.isspace(): - value = name[i:].lstrip() - name = name[:i] - break - return Define(token.start, token.end, name, value) - if name.startswith('if') and name[2:3].isspace(): - condition = name[3:].strip() - if condition.startswith('0') or condition.startswith('(0)'): - self._SkipIf0Blocks() - return None - - def _GetTokensUpTo(self, expected_token_type, expected_token): - return self._GetVarTokensUpTo(expected_token_type, expected_token)[0] - - def _GetVarTokensUpTo(self, expected_token_type, *expected_tokens): - last_token = self._GetNextToken() - tokens = [] - while (last_token.token_type != expected_token_type or - last_token.name not in expected_tokens): - tokens.append(last_token) - last_token = self._GetNextToken() - return tokens, last_token - - # Same as _GetVarTokensUpTo, but skips over '<...>' which could contain an - # expected token. - def _GetVarTokensUpToIgnoringTemplates(self, expected_token_type, - *expected_tokens): - last_token = self._GetNextToken() - tokens = [] - nesting = 0 - while (nesting > 0 or - last_token.token_type != expected_token_type or - last_token.name not in expected_tokens): - tokens.append(last_token) - last_token = self._GetNextToken() - if last_token.name == '<': - nesting += 1 - elif last_token.name == '>': - nesting -= 1 - return tokens, last_token - - # TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary. - def _IgnoreUpTo(self, token_type, token): - unused_tokens = self._GetTokensUpTo(token_type, token) - - def _SkipIf0Blocks(self): - count = 1 - while 1: - token = self._GetNextToken() - if token.token_type != tokenize.PREPROCESSOR: - continue - - name = token.name[1:].lstrip() - if name.startswith('endif'): - count -= 1 - if count == 0: - break - elif name.startswith('if'): - count += 1 - - def _GetMatchingChar(self, open_paren, close_paren, GetNextToken=None): - if GetNextToken is None: - GetNextToken = self._GetNextToken - # Assumes the current token is open_paren and we will consume - # and return up to the close_paren. - count = 1 - token = GetNextToken() - while 1: - if token.token_type == tokenize.SYNTAX: - if token.name == open_paren: - count += 1 - elif token.name == close_paren: - count -= 1 - if count == 0: - break - yield token - token = GetNextToken() - yield token - - def _GetParameters(self): - return self._GetMatchingChar('(', ')') - - def GetScope(self): - return self._GetMatchingChar('{', '}') - - def _GetNextToken(self): - if self.token_queue: - return self.token_queue.pop() - try: - return next(self.tokens) - except StopIteration: - return - - def _AddBackToken(self, token): - if token.whence == tokenize.WHENCE_STREAM: - token.whence = tokenize.WHENCE_QUEUE - self.token_queue.insert(0, token) - else: - assert token.whence == tokenize.WHENCE_QUEUE, token - self.token_queue.append(token) - - def _AddBackTokens(self, tokens): - if tokens: - if tokens[-1].whence == tokenize.WHENCE_STREAM: - for token in tokens: - token.whence = tokenize.WHENCE_QUEUE - self.token_queue[:0] = reversed(tokens) - else: - assert tokens[-1].whence == tokenize.WHENCE_QUEUE, tokens - self.token_queue.extend(reversed(tokens)) - - def GetName(self, seq=None): - """Returns ([tokens], next_token_info).""" - GetNextToken = self._GetNextToken - if seq is not None: - it = iter(seq) - GetNextToken = lambda: next(it) - next_token = GetNextToken() - tokens = [] - last_token_was_name = False - while (next_token.token_type == tokenize.NAME or - (next_token.token_type == tokenize.SYNTAX and - next_token.name in ('::', '<'))): - # Two NAMEs in a row means the identifier should terminate. - # It's probably some sort of variable declaration. - if last_token_was_name and next_token.token_type == tokenize.NAME: - break - last_token_was_name = next_token.token_type == tokenize.NAME - tokens.append(next_token) - # Handle templated names. - if next_token.name == '<': - tokens.extend(self._GetMatchingChar('<', '>', GetNextToken)) - last_token_was_name = True - next_token = GetNextToken() - return tokens, next_token - - def GetMethod(self, modifiers, templated_types): - return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(') - assert len(return_type_and_name) >= 1 - return self._GetMethod(return_type_and_name, modifiers, templated_types, - False) - - def _GetMethod(self, return_type_and_name, modifiers, templated_types, - get_paren): - template_portion = None - if get_paren: - token = self._GetNextToken() - assert token.token_type == tokenize.SYNTAX, token - if token.name == '<': - # Handle templatized dtors. - template_portion = [token] - template_portion.extend(self._GetMatchingChar('<', '>')) - token = self._GetNextToken() - assert token.token_type == tokenize.SYNTAX, token - assert token.name == '(', token - - name = return_type_and_name.pop() - # Handle templatized ctors. - if name.name == '>': - index = 1 - while return_type_and_name[index].name != '<': - index += 1 - template_portion = return_type_and_name[index:] + [name] - del return_type_and_name[index:] - name = return_type_and_name.pop() - elif name.name == ']': - rt = return_type_and_name - assert rt[-1].name == '[', return_type_and_name - assert rt[-2].name == 'operator', return_type_and_name - name_seq = return_type_and_name[-2:] - del return_type_and_name[-2:] - name = tokenize.Token(tokenize.NAME, 'operator[]', - name_seq[0].start, name.end) - # Get the open paren so _GetParameters() below works. - unused_open_paren = self._GetNextToken() - - # TODO(nnorwitz): store template_portion. - return_type = return_type_and_name - indices = name - if return_type: - indices = return_type[0] - - # Force ctor for templatized ctors. - if name.name == self.in_class and not modifiers: - modifiers |= FUNCTION_CTOR - parameters = list(self._GetParameters()) - del parameters[-1] # Remove trailing ')'. - - # Handling operator() is especially weird. - if name.name == 'operator' and not parameters: - token = self._GetNextToken() - assert token.name == '(', token - parameters = list(self._GetParameters()) - del parameters[-1] # Remove trailing ')'. - - token = self._GetNextToken() - while token.token_type == tokenize.NAME: - modifier_token = token - token = self._GetNextToken() - if modifier_token.name == 'const': - modifiers |= FUNCTION_CONST - elif modifier_token.name == '__attribute__': - # TODO(nnorwitz): handle more __attribute__ details. - modifiers |= FUNCTION_ATTRIBUTE - assert token.name == '(', token - # Consume everything between the (parens). - unused_tokens = list(self._GetMatchingChar('(', ')')) - token = self._GetNextToken() - elif modifier_token.name == 'throw': - modifiers |= FUNCTION_THROW - assert token.name == '(', token - # Consume everything between the (parens). - unused_tokens = list(self._GetMatchingChar('(', ')')) - token = self._GetNextToken() - elif modifier_token.name == 'override': - modifiers |= FUNCTION_OVERRIDE - elif modifier_token.name == modifier_token.name.upper(): - # HACK(nnorwitz): assume that all upper-case names - # are some macro we aren't expanding. - modifiers |= FUNCTION_UNKNOWN_ANNOTATION - else: - self.HandleError('unexpected token', modifier_token) - - assert token.token_type == tokenize.SYNTAX, token - # Handle ctor initializers. - if token.name == ':': - # TODO(nnorwitz): anything else to handle for initializer list? - while token.name != ';' and token.name != '{': - token = self._GetNextToken() - - # Handle pointer to functions that are really data but look - # like method declarations. - if token.name == '(': - if parameters[0].name == '*': - # name contains the return type. - name = parameters.pop() - # parameters contains the name of the data. - modifiers = [p.name for p in parameters] - # Already at the ( to open the parameter list. - function_parameters = list(self._GetMatchingChar('(', ')')) - del function_parameters[-1] # Remove trailing ')'. - # TODO(nnorwitz): store the function_parameters. - token = self._GetNextToken() - assert token.token_type == tokenize.SYNTAX, token - assert token.name == ';', token - return self._CreateVariable(indices, name.name, indices.name, - modifiers, '', None) - # At this point, we got something like: - # return_type (type::*name_)(params); - # This is a data member called name_ that is a function pointer. - # With this code: void (sq_type::*field_)(string&); - # We get: name=void return_type=[] parameters=sq_type ... field_ - # TODO(nnorwitz): is return_type always empty? - # TODO(nnorwitz): this isn't even close to being correct. - # Just put in something so we don't crash and can move on. - real_name = parameters[-1] - modifiers = [p.name for p in self._GetParameters()] - del modifiers[-1] # Remove trailing ')'. - return self._CreateVariable(indices, real_name.name, indices.name, - modifiers, '', None) - - if token.name == '{': - body = list(self.GetScope()) - del body[-1] # Remove trailing '}'. - else: - body = None - if token.name == '=': - token = self._GetNextToken() - - if token.name == 'default' or token.name == 'delete': - # Ignore explicitly defaulted and deleted special members - # in C++11. - token = self._GetNextToken() - else: - # Handle pure-virtual declarations. - assert token.token_type == tokenize.CONSTANT, token - assert token.name == '0', token - modifiers |= FUNCTION_PURE_VIRTUAL - token = self._GetNextToken() - - if token.name == '[': - # TODO(nnorwitz): store tokens and improve parsing. - # template char (&ASH(T (&seq)[N]))[N]; - tokens = list(self._GetMatchingChar('[', ']')) - token = self._GetNextToken() - - assert token.name == ';', (token, return_type_and_name, parameters) - - # Looks like we got a method, not a function. - if len(return_type) > 2 and return_type[-1].name == '::': - return_type, in_class = \ - self._GetReturnTypeAndClassName(return_type) - return Method(indices.start, indices.end, name.name, in_class, - return_type, parameters, modifiers, templated_types, - body, self.namespace_stack) - return Function(indices.start, indices.end, name.name, return_type, - parameters, modifiers, templated_types, body, - self.namespace_stack) - - def _GetReturnTypeAndClassName(self, token_seq): - # Splitting the return type from the class name in a method - # can be tricky. For example, Return::Type::Is::Hard::To::Find(). - # Where is the return type and where is the class name? - # The heuristic used is to pull the last name as the class name. - # This includes all the templated type info. - # TODO(nnorwitz): if there is only One name like in the - # example above, punt and assume the last bit is the class name. - - # Ignore a :: prefix, if exists so we can find the first real name. - i = 0 - if token_seq[0].name == '::': - i = 1 - # Ignore a :: suffix, if exists. - end = len(token_seq) - 1 - if token_seq[end-1].name == '::': - end -= 1 - - # Make a copy of the sequence so we can append a sentinel - # value. This is required for GetName will has to have some - # terminating condition beyond the last name. - seq_copy = token_seq[i:end] - seq_copy.append(tokenize.Token(tokenize.SYNTAX, '', 0, 0)) - names = [] - while i < end: - # Iterate through the sequence parsing out each name. - new_name, next = self.GetName(seq_copy[i:]) - assert new_name, 'Got empty new_name, next=%s' % next - # We got a pointer or ref. Add it to the name. - if next and next.token_type == tokenize.SYNTAX: - new_name.append(next) - names.append(new_name) - i += len(new_name) - - # Now that we have the names, it's time to undo what we did. - - # Remove the sentinel value. - names[-1].pop() - # Flatten the token sequence for the return type. - return_type = [e for seq in names[:-1] for e in seq] - # The class name is the last name. - class_name = names[-1] - return return_type, class_name - - def handle_bool(self): - pass - - def handle_char(self): - pass - - def handle_int(self): - pass - - def handle_long(self): - pass - - def handle_short(self): - pass - - def handle_double(self): - pass - - def handle_float(self): - pass - - def handle_void(self): - pass - - def handle_wchar_t(self): - pass - - def handle_unsigned(self): - pass - - def handle_signed(self): - pass - - def _GetNestedType(self, ctor): - name = None - name_tokens, token = self.GetName() - if name_tokens: - name = ''.join([t.name for t in name_tokens]) - - # Handle forward declarations. - if token.token_type == tokenize.SYNTAX and token.name == ';': - return ctor(token.start, token.end, name, None, - self.namespace_stack) - - if token.token_type == tokenize.NAME and self._handling_typedef: - self._AddBackToken(token) - return ctor(token.start, token.end, name, None, - self.namespace_stack) - - # Must be the type declaration. - fields = list(self._GetMatchingChar('{', '}')) - del fields[-1] # Remove trailing '}'. - if token.token_type == tokenize.SYNTAX and token.name == '{': - next = self._GetNextToken() - new_type = ctor(token.start, token.end, name, fields, - self.namespace_stack) - # A name means this is an anonymous type and the name - # is the variable declaration. - if next.token_type != tokenize.NAME: - return new_type - name = new_type - token = next - - # Must be variable declaration using the type prefixed with keyword. - assert token.token_type == tokenize.NAME, token - return self._CreateVariable(token, token.name, name, [], '', None) - - def handle_struct(self): - # Special case the handling typedef/aliasing of structs here. - # It would be a pain to handle in the class code. - name_tokens, var_token = self.GetName() - if name_tokens: - next_token = self._GetNextToken() - is_syntax = (var_token.token_type == tokenize.SYNTAX and - var_token.name[0] in '*&') - is_variable = (var_token.token_type == tokenize.NAME and - next_token.name == ';') - variable = var_token - if is_syntax and not is_variable: - variable = next_token - temp = self._GetNextToken() - if temp.token_type == tokenize.SYNTAX and temp.name == '(': - # Handle methods declared to return a struct. - t0 = name_tokens[0] - struct = tokenize.Token(tokenize.NAME, 'struct', - t0.start-7, t0.start-2) - type_and_name = [struct] - type_and_name.extend(name_tokens) - type_and_name.extend((var_token, next_token)) - return self._GetMethod(type_and_name, 0, None, False) - assert temp.name == ';', (temp, name_tokens, var_token) - if is_syntax or (is_variable and not self._handling_typedef): - modifiers = ['struct'] - type_name = ''.join([t.name for t in name_tokens]) - position = name_tokens[0] - return self._CreateVariable(position, variable.name, type_name, - modifiers, var_token.name, None) - name_tokens.extend((var_token, next_token)) - self._AddBackTokens(name_tokens) - else: - self._AddBackToken(var_token) - return self._GetClass(Struct, VISIBILITY_PUBLIC, None) - - def handle_union(self): - return self._GetNestedType(Union) - - def handle_enum(self): - return self._GetNestedType(Enum) - - def handle_auto(self): - # TODO(nnorwitz): warn about using auto? Probably not since it - # will be reclaimed and useful for C++0x. - pass - - def handle_register(self): - pass - - def handle_const(self): - pass - - def handle_inline(self): - pass - - def handle_extern(self): - pass - - def handle_static(self): - pass - - def handle_virtual(self): - # What follows must be a method. - token = token2 = self._GetNextToken() - if token.name == 'inline': - # HACK(nnorwitz): handle inline dtors by ignoring 'inline'. - token2 = self._GetNextToken() - if token2.token_type == tokenize.SYNTAX and token2.name == '~': - return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None) - assert token.token_type == tokenize.NAME or token.name == '::', token - return_type_and_name, _ = self._GetVarTokensUpToIgnoringTemplates( - tokenize.SYNTAX, '(') # ) - return_type_and_name.insert(0, token) - if token2 is not token: - return_type_and_name.insert(1, token2) - return self._GetMethod(return_type_and_name, FUNCTION_VIRTUAL, - None, False) - - def handle_volatile(self): - pass - - def handle_mutable(self): - pass - - def handle_public(self): - assert self.in_class - self.visibility = VISIBILITY_PUBLIC - - def handle_protected(self): - assert self.in_class - self.visibility = VISIBILITY_PROTECTED - - def handle_private(self): - assert self.in_class - self.visibility = VISIBILITY_PRIVATE - - def handle_friend(self): - tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';') - assert tokens - t0 = tokens[0] - return Friend(t0.start, t0.end, tokens, self.namespace_stack) - - def handle_static_cast(self): - pass - - def handle_const_cast(self): - pass - - def handle_dynamic_cast(self): - pass - - def handle_reinterpret_cast(self): - pass - - def handle_new(self): - pass - - def handle_delete(self): - tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';') - assert tokens - return Delete(tokens[0].start, tokens[0].end, tokens) - - def handle_typedef(self): - token = self._GetNextToken() - if (token.token_type == tokenize.NAME and - keywords.IsKeyword(token.name)): - # Token must be struct/enum/union/class. - method = getattr(self, 'handle_' + token.name) - self._handling_typedef = True - tokens = [method()] - self._handling_typedef = False - else: - tokens = [token] - - # Get the remainder of the typedef up to the semi-colon. - tokens.extend(self._GetTokensUpTo(tokenize.SYNTAX, ';')) - - # TODO(nnorwitz): clean all this up. - assert tokens - name = tokens.pop() - indices = name - if tokens: - indices = tokens[0] - if not indices: - indices = token - if name.name == ')': - # HACK(nnorwitz): Handle pointers to functions "properly". - if (len(tokens) >= 4 and - tokens[1].name == '(' and tokens[2].name == '*'): - tokens.append(name) - name = tokens[3] - elif name.name == ']': - # HACK(nnorwitz): Handle arrays properly. - if len(tokens) >= 2: - tokens.append(name) - name = tokens[1] - new_type = tokens - if tokens and isinstance(tokens[0], tokenize.Token): - new_type = self.converter.ToType(tokens)[0] - return Typedef(indices.start, indices.end, name.name, - new_type, self.namespace_stack) - - def handle_typeid(self): - pass # Not needed yet. - - def handle_typename(self): - pass # Not needed yet. - - def _GetTemplatedTypes(self): - result = {} - tokens = list(self._GetMatchingChar('<', '>')) - len_tokens = len(tokens) - 1 # Ignore trailing '>'. - i = 0 - while i < len_tokens: - key = tokens[i].name - i += 1 - if keywords.IsKeyword(key) or key == ',': - continue - type_name = default = None - if i < len_tokens: - i += 1 - if tokens[i-1].name == '=': - assert i < len_tokens, '%s %s' % (i, tokens) - default, unused_next_token = self.GetName(tokens[i:]) - i += len(default) - else: - if tokens[i-1].name != ',': - # We got something like: Type variable. - # Re-adjust the key (variable) and type_name (Type). - key = tokens[i-1].name - type_name = tokens[i-2] - - result[key] = (type_name, default) - return result - - def handle_template(self): - token = self._GetNextToken() - assert token.token_type == tokenize.SYNTAX, token - assert token.name == '<', token - templated_types = self._GetTemplatedTypes() - # TODO(nnorwitz): for now, just ignore the template params. - token = self._GetNextToken() - if token.token_type == tokenize.NAME: - if token.name == 'class': - return self._GetClass(Class, VISIBILITY_PRIVATE, templated_types) - elif token.name == 'struct': - return self._GetClass(Struct, VISIBILITY_PUBLIC, templated_types) - elif token.name == 'friend': - return self.handle_friend() - self._AddBackToken(token) - tokens, last = self._GetVarTokensUpTo(tokenize.SYNTAX, '(', ';') - tokens.append(last) - self._AddBackTokens(tokens) - if last.name == '(': - return self.GetMethod(FUNCTION_NONE, templated_types) - # Must be a variable definition. - return None - - def handle_true(self): - pass # Nothing to do. - - def handle_false(self): - pass # Nothing to do. - - def handle_asm(self): - pass # Not needed yet. - - def handle_class(self): - return self._GetClass(Class, VISIBILITY_PRIVATE, None) - - def _GetBases(self): - # Get base classes. - bases = [] - while 1: - token = self._GetNextToken() - assert token.token_type == tokenize.NAME, token - # TODO(nnorwitz): store kind of inheritance...maybe. - if token.name not in ('public', 'protected', 'private'): - # If inheritance type is not specified, it is private. - # Just put the token back so we can form a name. - # TODO(nnorwitz): it would be good to warn about this. - self._AddBackToken(token) - else: - # Check for virtual inheritance. - token = self._GetNextToken() - if token.name != 'virtual': - self._AddBackToken(token) - else: - # TODO(nnorwitz): store that we got virtual for this base. - pass - base, next_token = self.GetName() - bases_ast = self.converter.ToType(base) - assert len(bases_ast) == 1, bases_ast - bases.append(bases_ast[0]) - assert next_token.token_type == tokenize.SYNTAX, next_token - if next_token.name == '{': - token = next_token - break - # Support multiple inheritance. - assert next_token.name == ',', next_token - return bases, token - - def _GetClass(self, class_type, visibility, templated_types): - class_name = None - class_token = self._GetNextToken() - if class_token.token_type != tokenize.NAME: - assert class_token.token_type == tokenize.SYNTAX, class_token - token = class_token - else: - # Skip any macro (e.g. storage class specifiers) after the - # 'class' keyword. - next_token = self._GetNextToken() - if next_token.token_type == tokenize.NAME: - self._AddBackToken(next_token) - else: - self._AddBackTokens([class_token, next_token]) - name_tokens, token = self.GetName() - class_name = ''.join([t.name for t in name_tokens]) - bases = None - if token.token_type == tokenize.SYNTAX: - if token.name == ';': - # Forward declaration. - return class_type(class_token.start, class_token.end, - class_name, None, templated_types, None, - self.namespace_stack) - if token.name in '*&': - # Inline forward declaration. Could be method or data. - name_token = self._GetNextToken() - next_token = self._GetNextToken() - if next_token.name == ';': - # Handle data - modifiers = ['class'] - return self._CreateVariable(class_token, name_token.name, - class_name, - modifiers, token.name, None) - else: - # Assume this is a method. - tokens = (class_token, token, name_token, next_token) - self._AddBackTokens(tokens) - return self.GetMethod(FUNCTION_NONE, None) - if token.name == ':': - bases, token = self._GetBases() - - body = None - if token.token_type == tokenize.SYNTAX and token.name == '{': - assert token.token_type == tokenize.SYNTAX, token - assert token.name == '{', token - - ast = AstBuilder(self.GetScope(), self.filename, class_name, - visibility, self.namespace_stack) - body = list(ast.Generate()) - - if not self._handling_typedef: - token = self._GetNextToken() - if token.token_type != tokenize.NAME: - assert token.token_type == tokenize.SYNTAX, token - assert token.name == ';', token - else: - new_class = class_type(class_token.start, class_token.end, - class_name, bases, None, - body, self.namespace_stack) - - modifiers = [] - return self._CreateVariable(class_token, - token.name, new_class, - modifiers, token.name, None) - else: - if not self._handling_typedef: - self.HandleError('non-typedef token', token) - self._AddBackToken(token) - - return class_type(class_token.start, class_token.end, class_name, - bases, templated_types, body, self.namespace_stack) - - def handle_namespace(self): - token = self._GetNextToken() - # Support anonymous namespaces. - name = None - if token.token_type == tokenize.NAME: - name = token.name - token = self._GetNextToken() - self.namespace_stack.append(name) - assert token.token_type == tokenize.SYNTAX, token - # Create an internal token that denotes when the namespace is complete. - internal_token = tokenize.Token(_INTERNAL_TOKEN, _NAMESPACE_POP, - None, None) - internal_token.whence = token.whence - if token.name == '=': - # TODO(nnorwitz): handle aliasing namespaces. - name, next_token = self.GetName() - assert next_token.name == ';', next_token - self._AddBackToken(internal_token) - else: - assert token.name == '{', token - tokens = list(self.GetScope()) - # Replace the trailing } with the internal namespace pop token. - tokens[-1] = internal_token - # Handle namespace with nothing in it. - self._AddBackTokens(tokens) - return None - - def handle_using(self): - tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';') - assert tokens - return Using(tokens[0].start, tokens[0].end, tokens) - - def handle_explicit(self): - assert self.in_class - # Nothing much to do. - # TODO(nnorwitz): maybe verify the method name == class name. - # This must be a ctor. - return self.GetMethod(FUNCTION_CTOR, None) - - def handle_this(self): - pass # Nothing to do. - - def handle_operator(self): - # Pull off the next token(s?) and make that part of the method name. - pass - - def handle_sizeof(self): - pass - - def handle_case(self): - pass - - def handle_switch(self): - pass - - def handle_default(self): - token = self._GetNextToken() - assert token.token_type == tokenize.SYNTAX - assert token.name == ':' - - def handle_if(self): - pass - - def handle_else(self): - pass - - def handle_return(self): - tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';') - if not tokens: - return Return(self.current_token.start, self.current_token.end, None) - return Return(tokens[0].start, tokens[0].end, tokens) - - def handle_goto(self): - tokens = self._GetTokensUpTo(tokenize.SYNTAX, ';') - assert len(tokens) == 1, str(tokens) - return Goto(tokens[0].start, tokens[0].end, tokens[0].name) - - def handle_try(self): - pass # Not needed yet. - - def handle_catch(self): - pass # Not needed yet. - - def handle_throw(self): - pass # Not needed yet. - - def handle_while(self): - pass - - def handle_do(self): - pass - - def handle_for(self): - pass - - def handle_break(self): - self._IgnoreUpTo(tokenize.SYNTAX, ';') - - def handle_continue(self): - self._IgnoreUpTo(tokenize.SYNTAX, ';') - - -def BuilderFromSource(source, filename): - """Utility method that returns an AstBuilder from source code. - - Args: - source: 'C++ source code' - filename: 'file1' - - Returns: - AstBuilder - """ - return AstBuilder(tokenize.GetTokens(source), filename) - - -def PrintIndentifiers(filename, should_print): - """Prints all identifiers for a C++ source file. - - Args: - filename: 'file1' - should_print: predicate with signature: bool Function(token) - """ - source = utils.ReadFile(filename, False) - if source is None: - sys.stderr.write('Unable to find: %s\n' % filename) - return - - #print('Processing %s' % actual_filename) - builder = BuilderFromSource(source, filename) - try: - for node in builder.Generate(): - if should_print(node): - print(node.name) - except KeyboardInterrupt: - return - except: - pass - - -def PrintAllIndentifiers(filenames, should_print): - """Prints all identifiers for each C++ source file in filenames. - - Args: - filenames: ['file1', 'file2', ...] - should_print: predicate with signature: bool Function(token) - """ - for path in filenames: - PrintIndentifiers(path, should_print) - - -def main(argv): - for filename in argv[1:]: - source = utils.ReadFile(filename) - if source is None: - continue - - print('Processing %s' % filename) - builder = BuilderFromSource(source, filename) - try: - entire_ast = filter(None, builder.Generate()) - except KeyboardInterrupt: - return - except: - # Already printed a warning, print the traceback and continue. - traceback.print_exc() - else: - if utils.DEBUG: - for ast in entire_ast: - print(ast) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/gmock_class.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/gmock_class.py deleted file mode 100755 index 89862ae1e..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/gmock_class.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Generate Google Mock classes from base classes. - -This program will read in a C++ source file and output the Google Mock -classes for the specified classes. If no class is specified, all -classes in the source file are emitted. - -Usage: - gmock_class.py header-file.h [ClassName]... - -Output is sent to stdout. -""" - -import os -import re -import sys - -from cpp import ast -from cpp import utils - -# Preserve compatibility with Python 2.3. -try: - _dummy = set -except NameError: - import sets - - set = sets.Set - -_VERSION = (1, 0, 1) # The version of this script. -# How many spaces to indent. Can set me with the INDENT environment variable. -_INDENT = 2 - - -def _RenderType(ast_type): - """Renders the potentially recursively templated type into a string. - - Args: - ast_type: The AST of the type. - - Returns: - Rendered string and a boolean to indicate whether we have multiple args - (which is not handled correctly). - """ - has_multiarg_error = False - # Add modifiers like 'const'. - modifiers = '' - if ast_type.modifiers: - modifiers = ' '.join(ast_type.modifiers) + ' ' - return_type = modifiers + ast_type.name - if ast_type.templated_types: - # Collect template args. - template_args = [] - for arg in ast_type.templated_types: - rendered_arg, e = _RenderType(arg) - if e: has_multiarg_error = True - template_args.append(rendered_arg) - return_type += '<' + ', '.join(template_args) + '>' - # We are actually not handling multi-template-args correctly. So mark it. - if len(template_args) > 1: - has_multiarg_error = True - if ast_type.pointer: - return_type += '*' - if ast_type.reference: - return_type += '&' - return return_type, has_multiarg_error - - -def _GetNumParameters(parameters, source): - num_parameters = len(parameters) - if num_parameters == 1: - first_param = parameters[0] - if source[first_param.start:first_param.end].strip() == 'void': - # We must treat T(void) as a function with no parameters. - return 0 - return num_parameters - - -def _GenerateMethods(output_lines, source, class_node): - function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | - ast.FUNCTION_OVERRIDE) - ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR - indent = ' ' * _INDENT - - for node in class_node.body: - # We only care about virtual functions. - if (isinstance(node, ast.Function) and - node.modifiers & function_type and - not node.modifiers & ctor_or_dtor): - # Pick out all the elements we need from the original function. - const = '' - if node.modifiers & ast.FUNCTION_CONST: - const = 'CONST_' - num_parameters = _GetNumParameters(node.parameters, source) - return_type = 'void' - if node.return_type: - return_type, has_multiarg_error = _RenderType(node.return_type) - if has_multiarg_error: - for line in [ - '// The following line won\'t really compile, as the return', - '// type has multiple template arguments. To fix it, use a', - '// typedef for the return type.']: - output_lines.append(indent + line) - tmpl = '' - if class_node.templated_types: - tmpl = '_T' - mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl) - - args = '' - if node.parameters: - # Get the full text of the parameters from the start - # of the first parameter to the end of the last parameter. - start = node.parameters[0].start - end = node.parameters[-1].end - # Remove // comments. - args_strings = re.sub(r'//.*', '', source[start:end]) - # Remove /* comments */. - args_strings = re.sub(r'/\*.*\*/', '', args_strings) - # Remove default arguments. - args_strings = re.sub(r'=.*,', ',', args_strings) - args_strings = re.sub(r'=.*', '', args_strings) - # Condense multiple spaces and eliminate newlines putting the - # parameters together on a single line. Ensure there is a - # space in an argument which is split by a newline without - # intervening whitespace, e.g.: int\nBar - args = re.sub(' +', ' ', args_strings.replace('\n', ' ')) - - # Create the mock method definition. - output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name), - '%s%s(%s));' % (indent * 3, return_type, args)]) - - -def _GenerateMocks(filename, source, ast_list, desired_class_names): - processed_class_names = set() - lines = [] - for node in ast_list: - if (isinstance(node, ast.Class) and node.body and - # desired_class_names being None means that all classes are selected. - (not desired_class_names or node.name in desired_class_names)): - class_name = node.name - parent_name = class_name - processed_class_names.add(class_name) - class_node = node - # Add namespace before the class. - if class_node.namespace: - lines.extend(['namespace %s {' % n for n in class_node.namespace]) # } - lines.append('') - - # Add template args for templated classes. - if class_node.templated_types: - # TODO(paulchang): The AST doesn't preserve template argument order, - # so we have to make up names here. - # TODO(paulchang): Handle non-type template arguments (e.g. - # template). - template_arg_count = len(class_node.templated_types.keys()) - template_args = ['T%d' % n for n in range(template_arg_count)] - template_decls = ['typename ' + arg for arg in template_args] - lines.append('template <' + ', '.join(template_decls) + '>') - parent_name += '<' + ', '.join(template_args) + '>' - - # Add the class prolog. - lines.append('class Mock%s : public %s {' # } - % (class_name, parent_name)) - lines.append('%spublic:' % (' ' * (_INDENT // 2))) - - # Add all the methods. - _GenerateMethods(lines, source, class_node) - - # Close the class. - if lines: - # If there are no virtual methods, no need for a public label. - if len(lines) == 2: - del lines[-1] - - # Only close the class if there really is a class. - lines.append('};') - lines.append('') # Add an extra newline. - - # Close the namespace. - if class_node.namespace: - for i in range(len(class_node.namespace) - 1, -1, -1): - lines.append('} // namespace %s' % class_node.namespace[i]) - lines.append('') # Add an extra newline. - - if desired_class_names: - missing_class_name_list = list(desired_class_names - processed_class_names) - if missing_class_name_list: - missing_class_name_list.sort() - sys.stderr.write('Class(es) not found in %s: %s\n' % - (filename, ', '.join(missing_class_name_list))) - elif not processed_class_names: - sys.stderr.write('No class found in %s\n' % filename) - - return lines - - -def main(argv=sys.argv): - if len(argv) < 2: - sys.stderr.write('Google Mock Class Generator v%s\n\n' % - '.'.join(map(str, _VERSION))) - sys.stderr.write(__doc__) - return 1 - - global _INDENT - try: - _INDENT = int(os.environ['INDENT']) - except KeyError: - pass - except: - sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT')) - - filename = argv[1] - desired_class_names = None # None means all classes in the source file. - if len(argv) >= 3: - desired_class_names = set(argv[2:]) - source = utils.ReadFile(filename) - if source is None: - return 1 - - builder = ast.BuilderFromSource(source, filename) - try: - entire_ast = filter(None, builder.Generate()) - except KeyboardInterrupt: - return - except: - # An error message was already printed since we couldn't parse. - sys.exit(1) - else: - lines = _GenerateMocks(filename, source, entire_ast, desired_class_names) - sys.stdout.write('\n'.join(lines)) - - -if __name__ == '__main__': - main(sys.argv) diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/gmock_class_test.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/gmock_class_test.py deleted file mode 100755 index 211a92dd2..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/gmock_class_test.py +++ /dev/null @@ -1,540 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2009 Neal Norwitz All Rights Reserved. -# Portions Copyright 2009 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for gmock.scripts.generator.cpp.gmock_class.""" - -import os -import sys -import unittest - -# Allow the cpp imports below to work when run as a standalone script. -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) - -from cpp import ast -from cpp import gmock_class - - -class TestCase(unittest.TestCase): - """Helper class that adds assert methods.""" - - @staticmethod - def StripLeadingWhitespace(lines): - """Strip leading whitespace in each line in 'lines'.""" - return '\n'.join([s.lstrip() for s in lines.split('\n')]) - - def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines): - """Specialized assert that ignores the indent level.""" - self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines)) - - -class GenerateMethodsTest(TestCase): - - @staticmethod - def GenerateMethodSource(cpp_source): - """Convert C++ source to Google Mock output source lines.""" - method_source_lines = [] - # is a pseudo-filename, it is not read or written. - builder = ast.BuilderFromSource(cpp_source, '') - ast_list = list(builder.Generate()) - gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0]) - return '\n'.join(method_source_lines) - - def testSimpleMethod(self): - source = """ -class Foo { - public: - virtual int Bar(); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) - - def testSimpleConstructorsAndDestructor(self): - source = """ -class Foo { - public: - Foo(); - Foo(int x); - Foo(const Foo& f); - Foo(Foo&& f); - ~Foo(); - virtual int Bar() = 0; -}; -""" - # The constructors and destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) - - def testVirtualDestructor(self): - source = """ -class Foo { - public: - virtual ~Foo(); - virtual int Bar() = 0; -}; -""" - # The destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) - - def testExplicitlyDefaultedConstructorsAndDestructor(self): - source = """ -class Foo { - public: - Foo() = default; - Foo(const Foo& f) = default; - Foo(Foo&& f) = default; - ~Foo() = default; - virtual int Bar() = 0; -}; -""" - # The constructors and destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) - - def testExplicitlyDeletedConstructorsAndDestructor(self): - source = """ -class Foo { - public: - Foo() = delete; - Foo(const Foo& f) = delete; - Foo(Foo&& f) = delete; - ~Foo() = delete; - virtual int Bar() = 0; -}; -""" - # The constructors and destructor should be ignored. - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) - - def testSimpleOverrideMethod(self): - source = """ -class Foo { - public: - int Bar() override; -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint());', - self.GenerateMethodSource(source)) - - def testSimpleConstMethod(self): - source = """ -class Foo { - public: - virtual void Bar(bool flag) const; -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));', - self.GenerateMethodSource(source)) - - def testExplicitVoid(self): - source = """ -class Foo { - public: - virtual int Bar(void); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0(Bar,\nint(void));', - self.GenerateMethodSource(source)) - - def testStrangeNewlineInParameter(self): - source = """ -class Foo { - public: - virtual void Bar(int -a) = 0; -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nvoid(int a));', - self.GenerateMethodSource(source)) - - def testDefaultParameters(self): - source = """ -class Foo { - public: - virtual void Bar(int a, char c = 'x') = 0; -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\nvoid(int a, char c ));', - self.GenerateMethodSource(source)) - - def testMultipleDefaultParameters(self): - source = """ -class Foo { - public: - virtual void Bar( - int a = 42, - char c = 'x', - const int* const p = nullptr, - const std::string& s = "42", - char tab[] = {'4','2'}, - int const *& rp = aDefaultPointer) = 0; -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - "MOCK_METHOD7(Bar,\n" - "void(int a , char c , const int* const p , const std::string& s , char tab[] , int const *& rp ));", - self.GenerateMethodSource(source)) - - def testConstDefaultParameter(self): - source = """ -class Test { - public: - virtual bool Bar(const int test_arg = 42) = 0; -}; -""" - expected = 'MOCK_METHOD1(Bar,\nbool(const int test_arg ));' - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMethodSource(source)) - - def testConstRefDefaultParameter(self): - source = """ -class Test { - public: - virtual bool Bar(const std::string& test_arg = "42" ) = 0; -}; -""" - expected = 'MOCK_METHOD1(Bar,\nbool(const std::string& test_arg ));' - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMethodSource(source)) - - def testRemovesCommentsWhenDefaultsArePresent(self): - source = """ -class Foo { - public: - virtual void Bar(int a = 42 /* a comment */, - char /* other comment */ c= 'x') = 0; -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\nvoid(int a , char c));', - self.GenerateMethodSource(source)) - - def testDoubleSlashCommentsInParameterListAreRemoved(self): - source = """ -class Foo { - public: - virtual void Bar(int a, // inline comments should be elided. - int b // inline comments should be elided. - ) const = 0; -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));', - self.GenerateMethodSource(source)) - - def testCStyleCommentsInParameterListAreNotRemoved(self): - # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these - # comments. Also note that C style comments after the last parameter - # are still elided. - source = """ -class Foo { - public: - virtual const string& Bar(int /* keeper */, int b); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\nconst string&(int , int b));', - self.GenerateMethodSource(source)) - - def testArgsOfTemplateTypes(self): - source = """ -class Foo { - public: - virtual int Bar(const vector& v, map* output); -};""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD2(Bar,\n' - 'int(const vector& v, map* output));', - self.GenerateMethodSource(source)) - - def testReturnTypeWithOneTemplateArg(self): - source = """ -class Foo { - public: - virtual vector* Bar(int n); -};""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nvector*(int n));', - self.GenerateMethodSource(source)) - - def testReturnTypeWithManyTemplateArgs(self): - source = """ -class Foo { - public: - virtual map Bar(); -};""" - # Comparing the comment text is brittle - we'll think of something - # better in case this gets annoying, but for now let's keep it simple. - self.assertEqualIgnoreLeadingWhitespace( - '// The following line won\'t really compile, as the return\n' - '// type has multiple template arguments. To fix it, use a\n' - '// typedef for the return type.\n' - 'MOCK_METHOD0(Bar,\nmap());', - self.GenerateMethodSource(source)) - - def testSimpleMethodInTemplatedClass(self): - source = """ -template -class Foo { - public: - virtual int Bar(); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD0_T(Bar,\nint());', - self.GenerateMethodSource(source)) - - def testPointerArgWithoutNames(self): - source = """ -class Foo { - virtual int Bar(C*); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nint(C*));', - self.GenerateMethodSource(source)) - - def testReferenceArgWithoutNames(self): - source = """ -class Foo { - virtual int Bar(C&); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nint(C&));', - self.GenerateMethodSource(source)) - - def testArrayArgWithoutNames(self): - source = """ -class Foo { - virtual int Bar(C[]); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - 'MOCK_METHOD1(Bar,\nint(C[]));', - self.GenerateMethodSource(source)) - - -class GenerateMocksTest(TestCase): - - @staticmethod - def GenerateMocks(cpp_source): - """Convert C++ source to complete Google Mock output source.""" - # is a pseudo-filename, it is not read or written. - filename = '' - builder = ast.BuilderFromSource(cpp_source, filename) - ast_list = list(builder.Generate()) - lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None) - return '\n'.join(lines) - - def testNamespaces(self): - source = """ -namespace Foo { -namespace Bar { class Forward; } -namespace Baz { - -class Test { - public: - virtual void Foo(); -}; - -} // namespace Baz -} // namespace Foo -""" - expected = """\ -namespace Foo { -namespace Baz { - -class MockTest : public Test { -public: -MOCK_METHOD0(Foo, -void()); -}; - -} // namespace Baz -} // namespace Foo -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testClassWithStorageSpecifierMacro(self): - source = """ -class STORAGE_SPECIFIER Test { - public: - virtual void Foo(); -}; -""" - expected = """\ -class MockTest : public Test { -public: -MOCK_METHOD0(Foo, -void()); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testTemplatedForwardDeclaration(self): - source = """ -template class Forward; // Forward declaration should be ignored. -class Test { - public: - virtual void Foo(); -}; -""" - expected = """\ -class MockTest : public Test { -public: -MOCK_METHOD0(Foo, -void()); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testTemplatedClass(self): - source = """ -template -class Test { - public: - virtual void Foo(); -}; -""" - expected = """\ -template -class MockTest : public Test { -public: -MOCK_METHOD0_T(Foo, -void()); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testTemplateInATemplateTypedef(self): - source = """ -class Test { - public: - typedef std::vector> FooType; - virtual void Bar(const FooType& test_arg); -}; -""" - expected = """\ -class MockTest : public Test { -public: -MOCK_METHOD1(Bar, -void(const FooType& test_arg)); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testTemplateInATemplateTypedefWithComma(self): - source = """ -class Test { - public: - typedef std::function>&, int> FooType; - virtual void Bar(const FooType& test_arg); -}; -""" - expected = """\ -class MockTest : public Test { -public: -MOCK_METHOD1(Bar, -void(const FooType& test_arg)); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testEnumType(self): - source = """ -class Test { - public: - enum Bar { - BAZ, QUX, QUUX, QUUUX - }; - virtual void Foo(); -}; -""" - expected = """\ -class MockTest : public Test { -public: -MOCK_METHOD0(Foo, -void()); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testEnumClassType(self): - source = """ -class Test { - public: - enum class Bar { - BAZ, QUX, QUUX, QUUUX - }; - virtual void Foo(); -}; -""" - expected = """\ -class MockTest : public Test { -public: -MOCK_METHOD0(Foo, -void()); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - def testStdFunction(self): - source = """ -class Test { - public: - Test(std::function foo) : foo_(foo) {} - - virtual std::function foo(); - - private: - std::function foo_; -}; -""" - expected = """\ -class MockTest : public Test { -public: -MOCK_METHOD0(foo, -std::function()); -}; -""" - self.assertEqualIgnoreLeadingWhitespace( - expected, self.GenerateMocks(source)) - - -if __name__ == '__main__': - unittest.main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/keywords.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/keywords.py deleted file mode 100755 index e4282714d..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/keywords.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""C++ keywords and helper utilities for determining keywords.""" - -try: - # Python 3.x - import builtins -except ImportError: - # Python 2.x - import __builtin__ as builtins - - -if not hasattr(builtins, 'set'): - # Nominal support for Python 2.3. - from sets import Set as set - - -TYPES = set('bool char int long short double float void wchar_t unsigned signed'.split()) -TYPE_MODIFIERS = set('auto register const inline extern static virtual volatile mutable'.split()) -ACCESS = set('public protected private friend'.split()) - -CASTS = set('static_cast const_cast dynamic_cast reinterpret_cast'.split()) - -OTHERS = set('true false asm class namespace using explicit this operator sizeof'.split()) -OTHER_TYPES = set('new delete typedef struct union enum typeid typename template'.split()) - -CONTROL = set('case switch default if else return goto'.split()) -EXCEPTION = set('try catch throw'.split()) -LOOP = set('while do for break continue'.split()) - -ALL = TYPES | TYPE_MODIFIERS | ACCESS | CASTS | OTHERS | OTHER_TYPES | CONTROL | EXCEPTION | LOOP - - -def IsKeyword(token): - return token in ALL - -def IsBuiltinType(token): - if token in ('virtual', 'inline'): - # These only apply to methods, they can't be types by themselves. - return False - return token in TYPES or token in TYPE_MODIFIERS diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/tokenize.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/tokenize.py deleted file mode 100755 index a75edcb14..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/tokenize.py +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tokenize C++ source code.""" - -try: - # Python 3.x - import builtins -except ImportError: - # Python 2.x - import __builtin__ as builtins - - -import sys - -from cpp import utils - - -if not hasattr(builtins, 'set'): - # Nominal support for Python 2.3. - from sets import Set as set - - -# Add $ as a valid identifier char since so much code uses it. -_letters = 'abcdefghijklmnopqrstuvwxyz' -VALID_IDENTIFIER_CHARS = set(_letters + _letters.upper() + '_0123456789$') -HEX_DIGITS = set('0123456789abcdefABCDEF') -INT_OR_FLOAT_DIGITS = set('01234567890eE-+') - - -# C++0x string preffixes. -_STR_PREFIXES = set(('R', 'u8', 'u8R', 'u', 'uR', 'U', 'UR', 'L', 'LR')) - - -# Token types. -UNKNOWN = 'UNKNOWN' -SYNTAX = 'SYNTAX' -CONSTANT = 'CONSTANT' -NAME = 'NAME' -PREPROCESSOR = 'PREPROCESSOR' - -# Where the token originated from. This can be used for backtracking. -# It is always set to WHENCE_STREAM in this code. -WHENCE_STREAM, WHENCE_QUEUE = range(2) - - -class Token(object): - """Data container to represent a C++ token. - - Tokens can be identifiers, syntax char(s), constants, or - pre-processor directives. - - start contains the index of the first char of the token in the source - end contains the index of the last char of the token in the source - """ - - def __init__(self, token_type, name, start, end): - self.token_type = token_type - self.name = name - self.start = start - self.end = end - self.whence = WHENCE_STREAM - - def __str__(self): - if not utils.DEBUG: - return 'Token(%r)' % self.name - return 'Token(%r, %s, %s)' % (self.name, self.start, self.end) - - __repr__ = __str__ - - -def _GetString(source, start, i): - i = source.find('"', i+1) - while source[i-1] == '\\': - # Count the trailing backslashes. - backslash_count = 1 - j = i - 2 - while source[j] == '\\': - backslash_count += 1 - j -= 1 - # When trailing backslashes are even, they escape each other. - if (backslash_count % 2) == 0: - break - i = source.find('"', i+1) - return i + 1 - - -def _GetChar(source, start, i): - # NOTE(nnorwitz): may not be quite correct, should be good enough. - i = source.find("'", i+1) - while source[i-1] == '\\': - # Need to special case '\\'. - if (i - 2) > start and source[i-2] == '\\': - break - i = source.find("'", i+1) - # Try to handle unterminated single quotes (in a #if 0 block). - if i < 0: - i = start - return i + 1 - - -def GetTokens(source): - """Returns a sequence of Tokens. - - Args: - source: string of C++ source code. - - Yields: - Token that represents the next token in the source. - """ - # Cache various valid character sets for speed. - valid_identifier_chars = VALID_IDENTIFIER_CHARS - hex_digits = HEX_DIGITS - int_or_float_digits = INT_OR_FLOAT_DIGITS - int_or_float_digits2 = int_or_float_digits | set('.') - - # Only ignore errors while in a #if 0 block. - ignore_errors = False - count_ifs = 0 - - i = 0 - end = len(source) - while i < end: - # Skip whitespace. - while i < end and source[i].isspace(): - i += 1 - if i >= end: - return - - token_type = UNKNOWN - start = i - c = source[i] - if c.isalpha() or c == '_': # Find a string token. - token_type = NAME - while source[i] in valid_identifier_chars: - i += 1 - # String and character constants can look like a name if - # they are something like L"". - if (source[i] == "'" and (i - start) == 1 and - source[start:i] in 'uUL'): - # u, U, and L are valid C++0x character preffixes. - token_type = CONSTANT - i = _GetChar(source, start, i) - elif source[i] == "'" and source[start:i] in _STR_PREFIXES: - token_type = CONSTANT - i = _GetString(source, start, i) - elif c == '/' and source[i+1] == '/': # Find // comments. - i = source.find('\n', i) - if i == -1: # Handle EOF. - i = end - continue - elif c == '/' and source[i+1] == '*': # Find /* comments. */ - i = source.find('*/', i) + 2 - continue - elif c in ':+-<>&|*=': # : or :: (plus other chars). - token_type = SYNTAX - i += 1 - new_ch = source[i] - if new_ch == c and c != '>': # Treat ">>" as two tokens. - i += 1 - elif c == '-' and new_ch == '>': - i += 1 - elif new_ch == '=': - i += 1 - elif c in '()[]{}~!?^%;/.,': # Handle single char tokens. - token_type = SYNTAX - i += 1 - if c == '.' and source[i].isdigit(): - token_type = CONSTANT - i += 1 - while source[i] in int_or_float_digits: - i += 1 - # Handle float suffixes. - for suffix in ('l', 'f'): - if suffix == source[i:i+1].lower(): - i += 1 - break - elif c.isdigit(): # Find integer. - token_type = CONSTANT - if c == '0' and source[i+1] in 'xX': - # Handle hex digits. - i += 2 - while source[i] in hex_digits: - i += 1 - else: - while source[i] in int_or_float_digits2: - i += 1 - # Handle integer (and float) suffixes. - for suffix in ('ull', 'll', 'ul', 'l', 'f', 'u'): - size = len(suffix) - if suffix == source[i:i+size].lower(): - i += size - break - elif c == '"': # Find string. - token_type = CONSTANT - i = _GetString(source, start, i) - elif c == "'": # Find char. - token_type = CONSTANT - i = _GetChar(source, start, i) - elif c == '#': # Find pre-processor command. - token_type = PREPROCESSOR - got_if = source[i:i+3] == '#if' and source[i+3:i+4].isspace() - if got_if: - count_ifs += 1 - elif source[i:i+6] == '#endif': - count_ifs -= 1 - if count_ifs == 0: - ignore_errors = False - - # TODO(nnorwitz): handle preprocessor statements (\ continuations). - while 1: - i1 = source.find('\n', i) - i2 = source.find('//', i) - i3 = source.find('/*', i) - i4 = source.find('"', i) - # NOTE(nnorwitz): doesn't handle comments in #define macros. - # Get the first important symbol (newline, comment, EOF/end). - i = min([x for x in (i1, i2, i3, i4, end) if x != -1]) - - # Handle #include "dir//foo.h" properly. - if source[i] == '"': - i = source.find('"', i+1) + 1 - assert i > 0 - continue - # Keep going if end of the line and the line ends with \. - if not (i == i1 and source[i-1] == '\\'): - if got_if: - condition = source[start+4:i].lstrip() - if (condition.startswith('0') or - condition.startswith('(0)')): - ignore_errors = True - break - i += 1 - elif c == '\\': # Handle \ in code. - # This is different from the pre-processor \ handling. - i += 1 - continue - elif ignore_errors: - # The tokenizer seems to be in pretty good shape. This - # raise is conditionally disabled so that bogus code - # in an #if 0 block can be handled. Since we will ignore - # it anyways, this is probably fine. So disable the - # exception and return the bogus char. - i += 1 - else: - sys.stderr.write('Got invalid token in %s @ %d token:%s: %r\n' % - ('?', i, c, source[i-10:i+10])) - raise RuntimeError('unexpected token') - - if i <= 0: - print('Invalid index, exiting now.') - return - yield Token(token_type, source[start:i], start, i) - - -if __name__ == '__main__': - def main(argv): - """Driver mostly for testing purposes.""" - for filename in argv[1:]: - source = utils.ReadFile(filename) - if source is None: - continue - - for token in GetTokens(source): - print('%-12s: %s' % (token.token_type, token.name)) - # print('\r%6.2f%%' % (100.0 * index / token.end),) - sys.stdout.write('\n') - - - main(sys.argv) diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/utils.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/utils.py deleted file mode 100755 index 6f5fc097b..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/cpp/utils.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007 Neal Norwitz -# Portions Copyright 2007 Google Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Generic utilities for C++ parsing.""" - -import sys - -# Set to True to see the start/end token indices. -DEBUG = True - - -def ReadFile(filename, print_error=True): - """Returns the contents of a file.""" - try: - fp = open(filename) - try: - return fp.read() - finally: - fp.close() - except IOError: - if print_error: - print('Error reading %s: %s' % (filename, sys.exc_info()[1])) - return None diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/gmock_gen.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/gmock_gen.py deleted file mode 100755 index 9d528a56d..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/generator/gmock_gen.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008 Google Inc. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Driver for starting up Google Mock class generator.""" - - -import os -import sys - -if __name__ == '__main__': - # Add the directory of this script to the path so we can import gmock_class. - sys.path.append(os.path.dirname(__file__)) - - from cpp import gmock_class - # Fix the docstring in case they require the usage. - gmock_class.__doc__ = gmock_class.__doc__.replace('gmock_class.py', __file__) - gmock_class.main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/pump.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/pump.py deleted file mode 100755 index 5523a19de..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/scripts/pump.py +++ /dev/null @@ -1,856 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2008, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""pump v0.2.0 - Pretty Useful for Meta Programming. - -A tool for preprocessor meta programming. Useful for generating -repetitive boilerplate code. Especially useful for writing C++ -classes, functions, macros, and templates that need to work with -various number of arguments. - -USAGE: - pump.py SOURCE_FILE - -EXAMPLES: - pump.py foo.cc.pump - Converts foo.cc.pump to foo.cc. - -GRAMMAR: - CODE ::= ATOMIC_CODE* - ATOMIC_CODE ::= $var ID = EXPRESSION - | $var ID = [[ CODE ]] - | $range ID EXPRESSION..EXPRESSION - | $for ID SEPARATOR [[ CODE ]] - | $($) - | $ID - | $(EXPRESSION) - | $if EXPRESSION [[ CODE ]] ELSE_BRANCH - | [[ CODE ]] - | RAW_CODE - SEPARATOR ::= RAW_CODE | EMPTY - ELSE_BRANCH ::= $else [[ CODE ]] - | $elif EXPRESSION [[ CODE ]] ELSE_BRANCH - | EMPTY - EXPRESSION has Python syntax. -""" - -from __future__ import print_function - -import io -import os -import re -import sys - - -TOKEN_TABLE = [ - (re.compile(r'\$var\s+'), '$var'), - (re.compile(r'\$elif\s+'), '$elif'), - (re.compile(r'\$else\s+'), '$else'), - (re.compile(r'\$for\s+'), '$for'), - (re.compile(r'\$if\s+'), '$if'), - (re.compile(r'\$range\s+'), '$range'), - (re.compile(r'\$[_A-Za-z]\w*'), '$id'), - (re.compile(r'\$\(\$\)'), '$($)'), - (re.compile(r'\$'), '$'), - (re.compile(r'\[\[\n?'), '[['), - (re.compile(r'\]\]\n?'), ']]'), - ] - - -class Cursor: - """Represents a position (line and column) in a text file.""" - - def __init__(self, line=-1, column=-1): - self.line = line - self.column = column - - def __eq__(self, rhs): - return self.line == rhs.line and self.column == rhs.column - - def __ne__(self, rhs): - return not self == rhs - - def __lt__(self, rhs): - return self.line < rhs.line or ( - self.line == rhs.line and self.column < rhs.column) - - def __le__(self, rhs): - return self < rhs or self == rhs - - def __gt__(self, rhs): - return rhs < self - - def __ge__(self, rhs): - return rhs <= self - - def __str__(self): - if self == Eof(): - return 'EOF' - else: - return '%s(%s)' % (self.line + 1, self.column) - - def __add__(self, offset): - return Cursor(self.line, self.column + offset) - - def __sub__(self, offset): - return Cursor(self.line, self.column - offset) - - def Clone(self): - """Returns a copy of self.""" - - return Cursor(self.line, self.column) - - -# Special cursor to indicate the end-of-file. -def Eof(): - """Returns the special cursor to denote the end-of-file.""" - return Cursor(-1, -1) - - -class Token: - """Represents a token in a Pump source file.""" - - def __init__(self, start=None, end=None, value=None, token_type=None): - if start is None: - self.start = Eof() - else: - self.start = start - if end is None: - self.end = Eof() - else: - self.end = end - self.value = value - self.token_type = token_type - - def __str__(self): - return 'Token @%s: \'%s\' type=%s' % ( - self.start, self.value, self.token_type) - - def Clone(self): - """Returns a copy of self.""" - - return Token(self.start.Clone(), self.end.Clone(), self.value, - self.token_type) - - -def StartsWith(lines, pos, string): - """Returns True iff the given position in lines starts with 'string'.""" - - return lines[pos.line][pos.column:].startswith(string) - - -def FindFirstInLine(line, token_table): - best_match_start = -1 - for (regex, token_type) in token_table: - m = regex.search(line) - if m: - # We found regex in lines - if best_match_start < 0 or m.start() < best_match_start: - best_match_start = m.start() - best_match_length = m.end() - m.start() - best_match_token_type = token_type - - if best_match_start < 0: - return None - - return (best_match_start, best_match_length, best_match_token_type) - - -def FindFirst(lines, token_table, cursor): - """Finds the first occurrence of any string in strings in lines.""" - - start = cursor.Clone() - cur_line_number = cursor.line - for line in lines[start.line:]: - if cur_line_number == start.line: - line = line[start.column:] - m = FindFirstInLine(line, token_table) - if m: - # We found a regex in line. - (start_column, length, token_type) = m - if cur_line_number == start.line: - start_column += start.column - found_start = Cursor(cur_line_number, start_column) - found_end = found_start + length - return MakeToken(lines, found_start, found_end, token_type) - cur_line_number += 1 - # We failed to find str in lines - return None - - -def SubString(lines, start, end): - """Returns a substring in lines.""" - - if end == Eof(): - end = Cursor(len(lines) - 1, len(lines[-1])) - - if start >= end: - return '' - - if start.line == end.line: - return lines[start.line][start.column:end.column] - - result_lines = ([lines[start.line][start.column:]] + - lines[start.line + 1:end.line] + - [lines[end.line][:end.column]]) - return ''.join(result_lines) - - -def StripMetaComments(str): - """Strip meta comments from each line in the given string.""" - - # First, completely remove lines containing nothing but a meta - # comment, including the trailing \n. - str = re.sub(r'^\s*\$\$.*\n', '', str) - - # Then, remove meta comments from contentful lines. - return re.sub(r'\s*\$\$.*', '', str) - - -def MakeToken(lines, start, end, token_type): - """Creates a new instance of Token.""" - - return Token(start, end, SubString(lines, start, end), token_type) - - -def ParseToken(lines, pos, regex, token_type): - line = lines[pos.line][pos.column:] - m = regex.search(line) - if m and not m.start(): - return MakeToken(lines, pos, pos + m.end(), token_type) - else: - print('ERROR: %s expected at %s.' % (token_type, pos)) - sys.exit(1) - - -ID_REGEX = re.compile(r'[_A-Za-z]\w*') -EQ_REGEX = re.compile(r'=') -REST_OF_LINE_REGEX = re.compile(r'.*?(?=$|\$\$)') -OPTIONAL_WHITE_SPACES_REGEX = re.compile(r'\s*') -WHITE_SPACE_REGEX = re.compile(r'\s') -DOT_DOT_REGEX = re.compile(r'\.\.') - - -def Skip(lines, pos, regex): - line = lines[pos.line][pos.column:] - m = re.search(regex, line) - if m and not m.start(): - return pos + m.end() - else: - return pos - - -def SkipUntil(lines, pos, regex, token_type): - line = lines[pos.line][pos.column:] - m = re.search(regex, line) - if m: - return pos + m.start() - else: - print ('ERROR: %s expected on line %s after column %s.' % - (token_type, pos.line + 1, pos.column)) - sys.exit(1) - - -def ParseExpTokenInParens(lines, pos): - def ParseInParens(pos): - pos = Skip(lines, pos, OPTIONAL_WHITE_SPACES_REGEX) - pos = Skip(lines, pos, r'\(') - pos = Parse(pos) - pos = Skip(lines, pos, r'\)') - return pos - - def Parse(pos): - pos = SkipUntil(lines, pos, r'\(|\)', ')') - if SubString(lines, pos, pos + 1) == '(': - pos = Parse(pos + 1) - pos = Skip(lines, pos, r'\)') - return Parse(pos) - else: - return pos - - start = pos.Clone() - pos = ParseInParens(pos) - return MakeToken(lines, start, pos, 'exp') - - -def RStripNewLineFromToken(token): - if token.value.endswith('\n'): - return Token(token.start, token.end, token.value[:-1], token.token_type) - else: - return token - - -def TokenizeLines(lines, pos): - while True: - found = FindFirst(lines, TOKEN_TABLE, pos) - if not found: - yield MakeToken(lines, pos, Eof(), 'code') - return - - if found.start == pos: - prev_token = None - prev_token_rstripped = None - else: - prev_token = MakeToken(lines, pos, found.start, 'code') - prev_token_rstripped = RStripNewLineFromToken(prev_token) - - if found.token_type == '$var': - if prev_token_rstripped: - yield prev_token_rstripped - yield found - id_token = ParseToken(lines, found.end, ID_REGEX, 'id') - yield id_token - pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX) - - eq_token = ParseToken(lines, pos, EQ_REGEX, '=') - yield eq_token - pos = Skip(lines, eq_token.end, r'\s*') - - if SubString(lines, pos, pos + 2) != '[[': - exp_token = ParseToken(lines, pos, REST_OF_LINE_REGEX, 'exp') - yield exp_token - pos = Cursor(exp_token.end.line + 1, 0) - elif found.token_type == '$for': - if prev_token_rstripped: - yield prev_token_rstripped - yield found - id_token = ParseToken(lines, found.end, ID_REGEX, 'id') - yield id_token - pos = Skip(lines, id_token.end, WHITE_SPACE_REGEX) - elif found.token_type == '$range': - if prev_token_rstripped: - yield prev_token_rstripped - yield found - id_token = ParseToken(lines, found.end, ID_REGEX, 'id') - yield id_token - pos = Skip(lines, id_token.end, OPTIONAL_WHITE_SPACES_REGEX) - - dots_pos = SkipUntil(lines, pos, DOT_DOT_REGEX, '..') - yield MakeToken(lines, pos, dots_pos, 'exp') - yield MakeToken(lines, dots_pos, dots_pos + 2, '..') - pos = dots_pos + 2 - new_pos = Cursor(pos.line + 1, 0) - yield MakeToken(lines, pos, new_pos, 'exp') - pos = new_pos - elif found.token_type == '$': - if prev_token: - yield prev_token - yield found - exp_token = ParseExpTokenInParens(lines, found.end) - yield exp_token - pos = exp_token.end - elif (found.token_type == ']]' or found.token_type == '$if' or - found.token_type == '$elif' or found.token_type == '$else'): - if prev_token_rstripped: - yield prev_token_rstripped - yield found - pos = found.end - else: - if prev_token: - yield prev_token - yield found - pos = found.end - - -def Tokenize(s): - """A generator that yields the tokens in the given string.""" - if s != '': - lines = s.splitlines(True) - for token in TokenizeLines(lines, Cursor(0, 0)): - yield token - - -class CodeNode: - def __init__(self, atomic_code_list=None): - self.atomic_code = atomic_code_list - - -class VarNode: - def __init__(self, identifier=None, atomic_code=None): - self.identifier = identifier - self.atomic_code = atomic_code - - -class RangeNode: - def __init__(self, identifier=None, exp1=None, exp2=None): - self.identifier = identifier - self.exp1 = exp1 - self.exp2 = exp2 - - -class ForNode: - def __init__(self, identifier=None, sep=None, code=None): - self.identifier = identifier - self.sep = sep - self.code = code - - -class ElseNode: - def __init__(self, else_branch=None): - self.else_branch = else_branch - - -class IfNode: - def __init__(self, exp=None, then_branch=None, else_branch=None): - self.exp = exp - self.then_branch = then_branch - self.else_branch = else_branch - - -class RawCodeNode: - def __init__(self, token=None): - self.raw_code = token - - -class LiteralDollarNode: - def __init__(self, token): - self.token = token - - -class ExpNode: - def __init__(self, token, python_exp): - self.token = token - self.python_exp = python_exp - - -def PopFront(a_list): - head = a_list[0] - a_list[:1] = [] - return head - - -def PushFront(a_list, elem): - a_list[:0] = [elem] - - -def PopToken(a_list, token_type=None): - token = PopFront(a_list) - if token_type is not None and token.token_type != token_type: - print('ERROR: %s expected at %s' % (token_type, token.start)) - print('ERROR: %s found instead' % (token,)) - sys.exit(1) - - return token - - -def PeekToken(a_list): - if not a_list: - return None - - return a_list[0] - - -def ParseExpNode(token): - python_exp = re.sub(r'([_A-Za-z]\w*)', r'self.GetValue("\1")', token.value) - return ExpNode(token, python_exp) - - -def ParseElseNode(tokens): - def Pop(token_type=None): - return PopToken(tokens, token_type) - - next = PeekToken(tokens) - if not next: - return None - if next.token_type == '$else': - Pop('$else') - Pop('[[') - code_node = ParseCodeNode(tokens) - Pop(']]') - return code_node - elif next.token_type == '$elif': - Pop('$elif') - exp = Pop('code') - Pop('[[') - code_node = ParseCodeNode(tokens) - Pop(']]') - inner_else_node = ParseElseNode(tokens) - return CodeNode([IfNode(ParseExpNode(exp), code_node, inner_else_node)]) - elif not next.value.strip(): - Pop('code') - return ParseElseNode(tokens) - else: - return None - - -def ParseAtomicCodeNode(tokens): - def Pop(token_type=None): - return PopToken(tokens, token_type) - - head = PopFront(tokens) - t = head.token_type - if t == 'code': - return RawCodeNode(head) - elif t == '$var': - id_token = Pop('id') - Pop('=') - next = PeekToken(tokens) - if next.token_type == 'exp': - exp_token = Pop() - return VarNode(id_token, ParseExpNode(exp_token)) - Pop('[[') - code_node = ParseCodeNode(tokens) - Pop(']]') - return VarNode(id_token, code_node) - elif t == '$for': - id_token = Pop('id') - next_token = PeekToken(tokens) - if next_token.token_type == 'code': - sep_token = next_token - Pop('code') - else: - sep_token = None - Pop('[[') - code_node = ParseCodeNode(tokens) - Pop(']]') - return ForNode(id_token, sep_token, code_node) - elif t == '$if': - exp_token = Pop('code') - Pop('[[') - code_node = ParseCodeNode(tokens) - Pop(']]') - else_node = ParseElseNode(tokens) - return IfNode(ParseExpNode(exp_token), code_node, else_node) - elif t == '$range': - id_token = Pop('id') - exp1_token = Pop('exp') - Pop('..') - exp2_token = Pop('exp') - return RangeNode(id_token, ParseExpNode(exp1_token), - ParseExpNode(exp2_token)) - elif t == '$id': - return ParseExpNode(Token(head.start + 1, head.end, head.value[1:], 'id')) - elif t == '$($)': - return LiteralDollarNode(head) - elif t == '$': - exp_token = Pop('exp') - return ParseExpNode(exp_token) - elif t == '[[': - code_node = ParseCodeNode(tokens) - Pop(']]') - return code_node - else: - PushFront(tokens, head) - return None - - -def ParseCodeNode(tokens): - atomic_code_list = [] - while True: - if not tokens: - break - atomic_code_node = ParseAtomicCodeNode(tokens) - if atomic_code_node: - atomic_code_list.append(atomic_code_node) - else: - break - return CodeNode(atomic_code_list) - - -def ParseToAST(pump_src_text): - """Convert the given Pump source text into an AST.""" - tokens = list(Tokenize(pump_src_text)) - code_node = ParseCodeNode(tokens) - return code_node - - -class Env: - def __init__(self): - self.variables = [] - self.ranges = [] - - def Clone(self): - clone = Env() - clone.variables = self.variables[:] - clone.ranges = self.ranges[:] - return clone - - def PushVariable(self, var, value): - # If value looks like an int, store it as an int. - try: - int_value = int(value) - if ('%s' % int_value) == value: - value = int_value - except Exception: - pass - self.variables[:0] = [(var, value)] - - def PopVariable(self): - self.variables[:1] = [] - - def PushRange(self, var, lower, upper): - self.ranges[:0] = [(var, lower, upper)] - - def PopRange(self): - self.ranges[:1] = [] - - def GetValue(self, identifier): - for (var, value) in self.variables: - if identifier == var: - return value - - print('ERROR: meta variable %s is undefined.' % (identifier,)) - sys.exit(1) - - def EvalExp(self, exp): - try: - result = eval(exp.python_exp) - except Exception as e: # pylint: disable=broad-except - print('ERROR: caught exception %s: %s' % (e.__class__.__name__, e)) - print('ERROR: failed to evaluate meta expression %s at %s' % - (exp.python_exp, exp.token.start)) - sys.exit(1) - return result - - def GetRange(self, identifier): - for (var, lower, upper) in self.ranges: - if identifier == var: - return (lower, upper) - - print('ERROR: range %s is undefined.' % (identifier,)) - sys.exit(1) - - -class Output: - def __init__(self): - self.string = '' - - def GetLastLine(self): - index = self.string.rfind('\n') - if index < 0: - return '' - - return self.string[index + 1:] - - def Append(self, s): - self.string += s - - -def RunAtomicCode(env, node, output): - if isinstance(node, VarNode): - identifier = node.identifier.value.strip() - result = Output() - RunAtomicCode(env.Clone(), node.atomic_code, result) - value = result.string - env.PushVariable(identifier, value) - elif isinstance(node, RangeNode): - identifier = node.identifier.value.strip() - lower = int(env.EvalExp(node.exp1)) - upper = int(env.EvalExp(node.exp2)) - env.PushRange(identifier, lower, upper) - elif isinstance(node, ForNode): - identifier = node.identifier.value.strip() - if node.sep is None: - sep = '' - else: - sep = node.sep.value - (lower, upper) = env.GetRange(identifier) - for i in range(lower, upper + 1): - new_env = env.Clone() - new_env.PushVariable(identifier, i) - RunCode(new_env, node.code, output) - if i != upper: - output.Append(sep) - elif isinstance(node, RawCodeNode): - output.Append(node.raw_code.value) - elif isinstance(node, IfNode): - cond = env.EvalExp(node.exp) - if cond: - RunCode(env.Clone(), node.then_branch, output) - elif node.else_branch is not None: - RunCode(env.Clone(), node.else_branch, output) - elif isinstance(node, ExpNode): - value = env.EvalExp(node) - output.Append('%s' % (value,)) - elif isinstance(node, LiteralDollarNode): - output.Append('$') - elif isinstance(node, CodeNode): - RunCode(env.Clone(), node, output) - else: - print('BAD') - print(node) - sys.exit(1) - - -def RunCode(env, code_node, output): - for atomic_code in code_node.atomic_code: - RunAtomicCode(env, atomic_code, output) - - -def IsSingleLineComment(cur_line): - return '//' in cur_line - - -def IsInPreprocessorDirective(prev_lines, cur_line): - if cur_line.lstrip().startswith('#'): - return True - return prev_lines and prev_lines[-1].endswith('\\') - - -def WrapComment(line, output): - loc = line.find('//') - before_comment = line[:loc].rstrip() - if before_comment == '': - indent = loc - else: - output.append(before_comment) - indent = len(before_comment) - len(before_comment.lstrip()) - prefix = indent*' ' + '// ' - max_len = 80 - len(prefix) - comment = line[loc + 2:].strip() - segs = [seg for seg in re.split(r'(\w+\W*)', comment) if seg != ''] - cur_line = '' - for seg in segs: - if len((cur_line + seg).rstrip()) < max_len: - cur_line += seg - else: - if cur_line.strip() != '': - output.append(prefix + cur_line.rstrip()) - cur_line = seg.lstrip() - if cur_line.strip() != '': - output.append(prefix + cur_line.strip()) - - -def WrapCode(line, line_concat, output): - indent = len(line) - len(line.lstrip()) - prefix = indent*' ' # Prefix of the current line - max_len = 80 - indent - len(line_concat) # Maximum length of the current line - new_prefix = prefix + 4*' ' # Prefix of a continuation line - new_max_len = max_len - 4 # Maximum length of a continuation line - # Prefers to wrap a line after a ',' or ';'. - segs = [seg for seg in re.split(r'([^,;]+[,;]?)', line.strip()) if seg != ''] - cur_line = '' # The current line without leading spaces. - for seg in segs: - # If the line is still too long, wrap at a space. - while cur_line == '' and len(seg.strip()) > max_len: - seg = seg.lstrip() - split_at = seg.rfind(' ', 0, max_len) - output.append(prefix + seg[:split_at].strip() + line_concat) - seg = seg[split_at + 1:] - prefix = new_prefix - max_len = new_max_len - - if len((cur_line + seg).rstrip()) < max_len: - cur_line = (cur_line + seg).lstrip() - else: - output.append(prefix + cur_line.rstrip() + line_concat) - prefix = new_prefix - max_len = new_max_len - cur_line = seg.lstrip() - if cur_line.strip() != '': - output.append(prefix + cur_line.strip()) - - -def WrapPreprocessorDirective(line, output): - WrapCode(line, ' \\', output) - - -def WrapPlainCode(line, output): - WrapCode(line, '', output) - - -def IsMultiLineIWYUPragma(line): - return re.search(r'/\* IWYU pragma: ', line) - - -def IsHeaderGuardIncludeOrOneLineIWYUPragma(line): - return (re.match(r'^#(ifndef|define|endif\s*//)\s*[\w_]+\s*$', line) or - re.match(r'^#include\s', line) or - # Don't break IWYU pragmas, either; that causes iwyu.py problems. - re.search(r'// IWYU pragma: ', line)) - - -def WrapLongLine(line, output): - line = line.rstrip() - if len(line) <= 80: - output.append(line) - elif IsSingleLineComment(line): - if IsHeaderGuardIncludeOrOneLineIWYUPragma(line): - # The style guide made an exception to allow long header guard lines, - # includes and IWYU pragmas. - output.append(line) - else: - WrapComment(line, output) - elif IsInPreprocessorDirective(output, line): - if IsHeaderGuardIncludeOrOneLineIWYUPragma(line): - # The style guide made an exception to allow long header guard lines, - # includes and IWYU pragmas. - output.append(line) - else: - WrapPreprocessorDirective(line, output) - elif IsMultiLineIWYUPragma(line): - output.append(line) - else: - WrapPlainCode(line, output) - - -def BeautifyCode(string): - lines = string.splitlines() - output = [] - for line in lines: - WrapLongLine(line, output) - output2 = [line.rstrip() for line in output] - return '\n'.join(output2) + '\n' - - -def ConvertFromPumpSource(src_text): - """Return the text generated from the given Pump source text.""" - ast = ParseToAST(StripMetaComments(src_text)) - output = Output() - RunCode(Env(), ast, output) - return BeautifyCode(output.string) - - -def main(argv): - if len(argv) == 1: - print(__doc__) - sys.exit(1) - - file_path = argv[-1] - output_str = ConvertFromPumpSource(io.open(file_path, 'r').read()) - if file_path.endswith('.pump'): - output_file_path = file_path[:-5] - else: - output_file_path = '-' - if output_file_path == '-': - print(output_str,) - else: - output_file = io.open(output_file_path, 'w') - output_file.write(u'// This file was GENERATED by command:\n') - output_file.write(u'// %s %s\n' % - (os.path.basename(__file__), os.path.basename(file_path))) - output_file.write(u'// DO NOT EDIT BY HAND!!!\n\n') - output_file.write(output_str) - output_file.close() - - -if __name__ == '__main__': - main(sys.argv) diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_nc.cc b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_nc.cc deleted file mode 100644 index d38fe85ef..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_nc.cc +++ /dev/null @@ -1,16 +0,0 @@ -#include "gmock/gmock.h" - -#include -#include - -#if defined(TEST_MOCK_METHOD_INVALID_CONST_SPEC) - -struct Base { - MOCK_METHOD(int, F, (), (onst)); -}; - -#else - -// Sanity check - this should compile. - -#endif diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_nc_test.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_nc_test.py deleted file mode 100644 index 8ef6e09fa..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_nc_test.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Negative compilation tests for Google Mock macro MOCK_METHOD.""" - -import os -import sys - -IS_LINUX = os.name == "posix" and os.uname()[0] == "Linux" -if not IS_LINUX: - sys.stderr.write( - "WARNING: Negative compilation tests are not supported on this platform") - sys.exit(0) - -# Suppresses the 'Import not at the top of the file' lint complaint. -# pylint: disable-msg=C6204 -from google3.testing.pybase import fake_target_util -from google3.testing.pybase import googletest - -# pylint: enable-msg=C6204 - - -class GMockMethodNCTest(googletest.TestCase): - """Negative compilation tests for MOCK_METHOD.""" - - # The class body is intentionally empty. The actual test*() methods - # will be defined at run time by a call to - # DefineNegativeCompilationTests() later. - pass - - -# Defines a list of test specs, where each element is a tuple -# (test name, list of regexes for matching the compiler errors). -TEST_SPECS = [ - ("MOCK_METHOD_INVALID_CONST_SPEC", - [r"onst cannot be recognized as a valid specification modifier"]), -] - -# Define a test method in GMockNCTest for each element in TEST_SPECS. -fake_target_util.DefineNegativeCompilationTests( - GMockMethodNCTest, - "google3/third_party/googletest/googlemock/test/gmock-function-mocker_nc", - "gmock-function-mocker_nc.o", TEST_SPECS) - -if __name__ == "__main__": - googletest.main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_test.cc b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_test.cc deleted file mode 100644 index 90d6b5f13..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-function-mocker_test.cc +++ /dev/null @@ -1,696 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file tests the function mocker classes. -#include "gmock/gmock-generated-function-mockers.h" - -#if GTEST_OS_WINDOWS -// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but -// we are getting compiler errors if we use basetyps.h, hence including -// objbase.h for definition of STDMETHOD. -# include -#endif // GTEST_OS_WINDOWS - -#include -#include -#include - -#include "gmock/gmock.h" -#include "gtest/gtest.h" - -namespace testing { -namespace gmock_function_mocker_test { - -using testing::_; -using testing::A; -using testing::An; -using testing::AnyNumber; -using testing::Const; -using testing::DoDefault; -using testing::Eq; -using testing::Lt; -using testing::MockFunction; -using testing::Ref; -using testing::Return; -using testing::ReturnRef; -using testing::TypedEq; - -template -class TemplatedCopyable { - public: - TemplatedCopyable() {} - - template - TemplatedCopyable(const U& other) {} // NOLINT -}; - -class FooInterface { - public: - virtual ~FooInterface() {} - - virtual void VoidReturning(int x) = 0; - - virtual int Nullary() = 0; - virtual bool Unary(int x) = 0; - virtual long Binary(short x, int y) = 0; // NOLINT - virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, - const std::string& k) = 0; - - virtual bool TakesNonConstReference(int& n) = 0; // NOLINT - virtual std::string TakesConstReference(const int& n) = 0; - virtual bool TakesConst(const int x) = 0; - - virtual int OverloadedOnArgumentNumber() = 0; - virtual int OverloadedOnArgumentNumber(int n) = 0; - - virtual int OverloadedOnArgumentType(int n) = 0; - virtual char OverloadedOnArgumentType(char c) = 0; - - virtual int OverloadedOnConstness() = 0; - virtual char OverloadedOnConstness() const = 0; - - virtual int TypeWithHole(int (*func)()) = 0; - virtual int TypeWithComma(const std::map& a_map) = 0; - virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable&) = 0; - - virtual int (*ReturnsFunctionPointer1(int))(bool) = 0; - using fn_ptr = int (*)(bool); - virtual fn_ptr ReturnsFunctionPointer2(int) = 0; - -#if GTEST_OS_WINDOWS - STDMETHOD_(int, CTNullary)() = 0; - STDMETHOD_(bool, CTUnary)(int x) = 0; - STDMETHOD_(int, CTDecimal) - (bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, const std::string& k) = 0; - STDMETHOD_(char, CTConst)(int x) const = 0; -#endif // GTEST_OS_WINDOWS -}; - -// Const qualifiers on arguments were once (incorrectly) considered -// significant in determining whether two virtual functions had the same -// signature. This was fixed in Visual Studio 2008. However, the compiler -// still emits a warning that alerts about this change in behavior. -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4373) -#endif -class MockFoo : public FooInterface { - public: - MockFoo() {} - - // Makes sure that a mock function parameter can be named. - MOCK_METHOD(void, VoidReturning, (int n)); // NOLINT - - MOCK_METHOD(int, Nullary, ()); // NOLINT - - // Makes sure that a mock function parameter can be unnamed. - MOCK_METHOD(bool, Unary, (int)); // NOLINT - MOCK_METHOD(long, Binary, (short, int)); // NOLINT - MOCK_METHOD(int, Decimal, - (bool, char, short, int, long, float, // NOLINT - double, unsigned, char*, const std::string& str), - (override)); - - MOCK_METHOD(bool, TakesNonConstReference, (int&)); // NOLINT - MOCK_METHOD(std::string, TakesConstReference, (const int&)); - MOCK_METHOD(bool, TakesConst, (const int)); // NOLINT - - // Tests that the function return type can contain unprotected comma. - MOCK_METHOD((std::map), ReturnTypeWithComma, (), ()); - MOCK_METHOD((std::map), ReturnTypeWithComma, (int), - (const)); // NOLINT - - MOCK_METHOD(int, OverloadedOnArgumentNumber, ()); // NOLINT - MOCK_METHOD(int, OverloadedOnArgumentNumber, (int)); // NOLINT - - MOCK_METHOD(int, OverloadedOnArgumentType, (int)); // NOLINT - MOCK_METHOD(char, OverloadedOnArgumentType, (char)); // NOLINT - - MOCK_METHOD(int, OverloadedOnConstness, (), (override)); // NOLINT - MOCK_METHOD(char, OverloadedOnConstness, (), (override, const)); // NOLINT - - MOCK_METHOD(int, TypeWithHole, (int (*)()), ()); // NOLINT - MOCK_METHOD(int, TypeWithComma, ((const std::map&))); - MOCK_METHOD(int, TypeWithTemplatedCopyCtor, - (const TemplatedCopyable&)); // NOLINT - - MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ()); - MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ()); - -#if GTEST_OS_WINDOWS - MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE))); - MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE))); - MOCK_METHOD(int, CTDecimal, - (bool b, char c, short d, int e, long f, float g, double h, - unsigned i, char* j, const std::string& k), - (Calltype(STDMETHODCALLTYPE))); - MOCK_METHOD(char, CTConst, (int), (const, Calltype(STDMETHODCALLTYPE))); - MOCK_METHOD((std::map), CTReturnTypeWithComma, (), - (Calltype(STDMETHODCALLTYPE))); -#endif // GTEST_OS_WINDOWS - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); -}; -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -class MockMethodFunctionMockerTest : public testing::Test { - protected: - MockMethodFunctionMockerTest() : foo_(&mock_foo_) {} - - FooInterface* const foo_; - MockFoo mock_foo_; -}; - -// Tests mocking a void-returning function. -TEST_F(MockMethodFunctionMockerTest, MocksVoidFunction) { - EXPECT_CALL(mock_foo_, VoidReturning(Lt(100))); - foo_->VoidReturning(0); -} - -// Tests mocking a nullary function. -TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunction) { - EXPECT_CALL(mock_foo_, Nullary()) - .WillOnce(DoDefault()) - .WillOnce(Return(1)); - - EXPECT_EQ(0, foo_->Nullary()); - EXPECT_EQ(1, foo_->Nullary()); -} - -// Tests mocking a unary function. -TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunction) { - EXPECT_CALL(mock_foo_, Unary(Eq(2))) - .Times(2) - .WillOnce(Return(true)); - - EXPECT_TRUE(foo_->Unary(2)); - EXPECT_FALSE(foo_->Unary(2)); -} - -// Tests mocking a binary function. -TEST_F(MockMethodFunctionMockerTest, MocksBinaryFunction) { - EXPECT_CALL(mock_foo_, Binary(2, _)) - .WillOnce(Return(3)); - - EXPECT_EQ(3, foo_->Binary(2, 1)); -} - -// Tests mocking a decimal function. -TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunction) { - EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A(), - Lt(100), 5U, NULL, "hi")) - .WillOnce(Return(5)); - - EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); -} - -// Tests mocking a function that takes a non-const reference. -TEST_F(MockMethodFunctionMockerTest, - MocksFunctionWithNonConstReferenceArgument) { - int a = 0; - EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a))) - .WillOnce(Return(true)); - - EXPECT_TRUE(foo_->TakesNonConstReference(a)); -} - -// Tests mocking a function that takes a const reference. -TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstReferenceArgument) { - int a = 0; - EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a))) - .WillOnce(Return("Hello")); - - EXPECT_EQ("Hello", foo_->TakesConstReference(a)); -} - -// Tests mocking a function that takes a const variable. -TEST_F(MockMethodFunctionMockerTest, MocksFunctionWithConstArgument) { - EXPECT_CALL(mock_foo_, TakesConst(Lt(10))) - .WillOnce(DoDefault()); - - EXPECT_FALSE(foo_->TakesConst(5)); -} - -// Tests mocking functions overloaded on the number of arguments. -TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) { - EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber()) - .WillOnce(Return(1)); - EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_)) - .WillOnce(Return(2)); - - EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1)); - EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber()); -} - -// Tests mocking functions overloaded on the types of argument. -TEST_F(MockMethodFunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) { - EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An())) - .WillOnce(Return(1)); - EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq('a'))) - .WillOnce(Return('b')); - - EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0)); - EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a')); -} - -// Tests mocking functions overloaded on the const-ness of this object. -TEST_F(MockMethodFunctionMockerTest, - MocksFunctionsOverloadedOnConstnessOfThis) { - EXPECT_CALL(mock_foo_, OverloadedOnConstness()); - EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness()) - .WillOnce(Return('a')); - - EXPECT_EQ(0, foo_->OverloadedOnConstness()); - EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness()); -} - -TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithComma) { - const std::map a_map; - EXPECT_CALL(mock_foo_, ReturnTypeWithComma()) - .WillOnce(Return(a_map)); - EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42)) - .WillOnce(Return(a_map)); - - EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma()); - EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42)); -} - -TEST_F(MockMethodFunctionMockerTest, MocksTypeWithTemplatedCopyCtor) { - EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true)); - EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable())); -} - -#if GTEST_OS_WINDOWS -// Tests mocking a nullary function with calltype. -TEST_F(MockMethodFunctionMockerTest, MocksNullaryFunctionWithCallType) { - EXPECT_CALL(mock_foo_, CTNullary()) - .WillOnce(Return(-1)) - .WillOnce(Return(0)); - - EXPECT_EQ(-1, foo_->CTNullary()); - EXPECT_EQ(0, foo_->CTNullary()); -} - -// Tests mocking a unary function with calltype. -TEST_F(MockMethodFunctionMockerTest, MocksUnaryFunctionWithCallType) { - EXPECT_CALL(mock_foo_, CTUnary(Eq(2))) - .Times(2) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_TRUE(foo_->CTUnary(2)); - EXPECT_FALSE(foo_->CTUnary(2)); -} - -// Tests mocking a decimal function with calltype. -TEST_F(MockMethodFunctionMockerTest, MocksDecimalFunctionWithCallType) { - EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A(), - Lt(100), 5U, NULL, "hi")) - .WillOnce(Return(10)); - - EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); -} - -// Tests mocking functions overloaded on the const-ness of this object. -TEST_F(MockMethodFunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { - EXPECT_CALL(Const(mock_foo_), CTConst(_)) - .WillOnce(Return('a')); - - EXPECT_EQ('a', Const(*foo_).CTConst(0)); -} - -TEST_F(MockMethodFunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { - const std::map a_map; - EXPECT_CALL(mock_foo_, CTReturnTypeWithComma()) - .WillOnce(Return(a_map)); - - EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma()); -} - -#endif // GTEST_OS_WINDOWS - -class MockB { - public: - MockB() {} - - MOCK_METHOD(void, DoB, ()); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); -}; - -// Tests that functions with no EXPECT_CALL() rules can be called any -// number of times. -TEST(MockMethodExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) { - { - MockB b; - } - - { - MockB b; - b.DoB(); - } - - { - MockB b; - b.DoB(); - b.DoB(); - } -} - -// Tests mocking template interfaces. - -template -class StackInterface { - public: - virtual ~StackInterface() {} - - // Template parameter appears in function parameter. - virtual void Push(const T& value) = 0; - virtual void Pop() = 0; - virtual int GetSize() const = 0; - // Template parameter appears in function return type. - virtual const T& GetTop() const = 0; -}; - -template -class MockStack : public StackInterface { - public: - MockStack() {} - - MOCK_METHOD(void, Push, (const T& elem), ()); - MOCK_METHOD(void, Pop, (), (final)); - MOCK_METHOD(int, GetSize, (), (const, override)); - MOCK_METHOD(const T&, GetTop, (), (const)); - - // Tests that the function return type can contain unprotected comma. - MOCK_METHOD((std::map), ReturnTypeWithComma, (), ()); - MOCK_METHOD((std::map), ReturnTypeWithComma, (int), (const)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack); -}; - -// Tests that template mock works. -TEST(MockMethodTemplateMockTest, Works) { - MockStack mock; - - EXPECT_CALL(mock, GetSize()) - .WillOnce(Return(0)) - .WillOnce(Return(1)) - .WillOnce(Return(0)); - EXPECT_CALL(mock, Push(_)); - int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); - - EXPECT_EQ(0, mock.GetSize()); - mock.Push(5); - EXPECT_EQ(1, mock.GetSize()); - EXPECT_EQ(5, mock.GetTop()); - mock.Pop(); - EXPECT_EQ(0, mock.GetSize()); -} - -TEST(MockMethodTemplateMockTest, MethodWithCommaInReturnTypeWorks) { - MockStack mock; - - const std::map a_map; - EXPECT_CALL(mock, ReturnTypeWithComma()) - .WillOnce(Return(a_map)); - EXPECT_CALL(mock, ReturnTypeWithComma(1)) - .WillOnce(Return(a_map)); - - EXPECT_EQ(a_map, mock.ReturnTypeWithComma()); - EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); -} - -#if GTEST_OS_WINDOWS -// Tests mocking template interfaces with calltype. - -template -class StackInterfaceWithCallType { - public: - virtual ~StackInterfaceWithCallType() {} - - // Template parameter appears in function parameter. - STDMETHOD_(void, Push)(const T& value) = 0; - STDMETHOD_(void, Pop)() = 0; - STDMETHOD_(int, GetSize)() const = 0; - // Template parameter appears in function return type. - STDMETHOD_(const T&, GetTop)() const = 0; -}; - -template -class MockStackWithCallType : public StackInterfaceWithCallType { - public: - MockStackWithCallType() {} - - MOCK_METHOD(void, Push, (const T& elem), - (Calltype(STDMETHODCALLTYPE), override)); - MOCK_METHOD(void, Pop, (), (Calltype(STDMETHODCALLTYPE), override)); - MOCK_METHOD(int, GetSize, (), (Calltype(STDMETHODCALLTYPE), override, const)); - MOCK_METHOD(const T&, GetTop, (), - (Calltype(STDMETHODCALLTYPE), override, const)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType); -}; - -// Tests that template mock with calltype works. -TEST(MockMethodTemplateMockTestWithCallType, Works) { - MockStackWithCallType mock; - - EXPECT_CALL(mock, GetSize()) - .WillOnce(Return(0)) - .WillOnce(Return(1)) - .WillOnce(Return(0)); - EXPECT_CALL(mock, Push(_)); - int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); - - EXPECT_EQ(0, mock.GetSize()); - mock.Push(5); - EXPECT_EQ(1, mock.GetSize()); - EXPECT_EQ(5, mock.GetTop()); - mock.Pop(); - EXPECT_EQ(0, mock.GetSize()); -} -#endif // GTEST_OS_WINDOWS - -#define MY_MOCK_METHODS1_ \ - MOCK_METHOD(void, Overloaded, ()); \ - MOCK_METHOD(int, Overloaded, (int), (const)); \ - MOCK_METHOD(bool, Overloaded, (bool f, int n)) - -class MockOverloadedOnArgNumber { - public: - MockOverloadedOnArgNumber() {} - - MY_MOCK_METHODS1_; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber); -}; - -TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { - MockOverloadedOnArgNumber mock; - EXPECT_CALL(mock, Overloaded()); - EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); - EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true)); - - mock.Overloaded(); - EXPECT_EQ(2, mock.Overloaded(1)); - EXPECT_TRUE(mock.Overloaded(true, 1)); -} - -#define MY_MOCK_METHODS2_ \ - MOCK_CONST_METHOD1(Overloaded, int(int n)); \ - MOCK_METHOD1(Overloaded, int(int n)) - -class MockOverloadedOnConstness { - public: - MockOverloadedOnConstness() {} - - MY_MOCK_METHODS2_; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness); -}; - -TEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) { - MockOverloadedOnConstness mock; - const MockOverloadedOnConstness* const_mock = &mock; - EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); - EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3)); - - EXPECT_EQ(2, mock.Overloaded(1)); - EXPECT_EQ(3, const_mock->Overloaded(1)); -} - -TEST(MockMethodMockFunctionTest, WorksForVoidNullary) { - MockFunction foo; - EXPECT_CALL(foo, Call()); - foo.Call(); -} - -TEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) { - MockFunction foo; - EXPECT_CALL(foo, Call()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); - EXPECT_EQ(1, foo.Call()); - EXPECT_EQ(2, foo.Call()); -} - -TEST(MockMethodMockFunctionTest, WorksForVoidUnary) { - MockFunction foo; - EXPECT_CALL(foo, Call(1)); - foo.Call(1); -} - -TEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) { - MockFunction foo; - EXPECT_CALL(foo, Call(false, 42)) - .WillOnce(Return(1)) - .WillOnce(Return(2)); - EXPECT_CALL(foo, Call(true, Ge(100))) - .WillOnce(Return(3)); - EXPECT_EQ(1, foo.Call(false, 42)); - EXPECT_EQ(2, foo.Call(false, 42)); - EXPECT_EQ(3, foo.Call(true, 120)); -} - -TEST(MockMethodMockFunctionTest, WorksFor10Arguments) { - MockFunction foo; - EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _)) - .WillOnce(Return(1)) - .WillOnce(Return(2)); - EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true)); - EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false)); -} - -TEST(MockMethodMockFunctionTest, AsStdFunction) { - MockFunction foo; - auto call = [](const std::function &f, int i) { - return f(i); - }; - EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1)); - EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2)); - EXPECT_EQ(-1, call(foo.AsStdFunction(), 1)); - EXPECT_EQ(-2, call(foo.AsStdFunction(), 2)); -} - -TEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) { - MockFunction foo; - int value = 1; - EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value)); - int& ref = foo.AsStdFunction()(); - EXPECT_EQ(1, ref); - value = 2; - EXPECT_EQ(2, ref); -} - -TEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) { - MockFunction foo; - auto call = [](const std::function &f, int &i) { - return f(i); - }; - int i = 42; - EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); - EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); -} - - -struct MockMethodSizes0 { - MOCK_METHOD(void, func, ()); -}; -struct MockMethodSizes1 { - MOCK_METHOD(void, func, (int)); -}; -struct MockMethodSizes2 { - MOCK_METHOD(void, func, (int, int)); -}; -struct MockMethodSizes3 { - MOCK_METHOD(void, func, (int, int, int)); -}; -struct MockMethodSizes4 { - MOCK_METHOD(void, func, (int, int, int, int)); -}; - -TEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) { - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); -} - -void hasTwoParams(int, int); -void MaybeThrows(); -void DoesntThrow() noexcept; -struct MockMethodNoexceptSpecifier { - MOCK_METHOD(void, func1, (), (noexcept)); - MOCK_METHOD(void, func2, (), (noexcept(true))); - MOCK_METHOD(void, func3, (), (noexcept(false))); - MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows())))); - MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow())))); - MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const)); - MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow())))); - // Put commas in the noexcept expression - MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1, 2))), const)); -}; - -TEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) { - EXPECT_TRUE(noexcept(std::declval().func1())); - EXPECT_TRUE(noexcept(std::declval().func2())); - EXPECT_FALSE(noexcept(std::declval().func3())); - EXPECT_FALSE(noexcept(std::declval().func4())); - EXPECT_TRUE(noexcept(std::declval().func5())); - EXPECT_TRUE(noexcept(std::declval().func6())); - EXPECT_TRUE(noexcept(std::declval().func7())); - EXPECT_EQ(noexcept(std::declval().func8()), - noexcept(hasTwoParams(1, 2))); -} - -} // namespace gmock_function_mocker_test -} // namespace testing diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-generated-function-mockers_test.cc b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-generated-function-mockers_test.cc deleted file mode 100644 index dff3a9f0f..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-generated-function-mockers_test.cc +++ /dev/null @@ -1,659 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file tests the function mocker classes. - -#include "gmock/gmock-generated-function-mockers.h" - -#if GTEST_OS_WINDOWS -// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but -// we are getting compiler errors if we use basetyps.h, hence including -// objbase.h for definition of STDMETHOD. -# include -#endif // GTEST_OS_WINDOWS - -#include -#include -#include "gmock/gmock.h" -#include "gtest/gtest.h" - -namespace testing { -namespace gmock_generated_function_mockers_test { - -using testing::_; -using testing::A; -using testing::An; -using testing::AnyNumber; -using testing::Const; -using testing::DoDefault; -using testing::Eq; -using testing::Lt; -using testing::MockFunction; -using testing::Ref; -using testing::Return; -using testing::ReturnRef; -using testing::TypedEq; - -template -class TemplatedCopyable { - public: - TemplatedCopyable() {} - - template - TemplatedCopyable(const U& other) {} // NOLINT -}; - -class FooInterface { - public: - virtual ~FooInterface() {} - - virtual void VoidReturning(int x) = 0; - - virtual int Nullary() = 0; - virtual bool Unary(int x) = 0; - virtual long Binary(short x, int y) = 0; // NOLINT - virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, - const std::string& k) = 0; - - virtual bool TakesNonConstReference(int& n) = 0; // NOLINT - virtual std::string TakesConstReference(const int& n) = 0; - virtual bool TakesConst(const int x) = 0; - - virtual int OverloadedOnArgumentNumber() = 0; - virtual int OverloadedOnArgumentNumber(int n) = 0; - - virtual int OverloadedOnArgumentType(int n) = 0; - virtual char OverloadedOnArgumentType(char c) = 0; - - virtual int OverloadedOnConstness() = 0; - virtual char OverloadedOnConstness() const = 0; - - virtual int TypeWithHole(int (*func)()) = 0; - virtual int TypeWithComma(const std::map& a_map) = 0; - virtual int TypeWithTemplatedCopyCtor( - const TemplatedCopyable& a_vector) = 0; - -#if GTEST_OS_WINDOWS - STDMETHOD_(int, CTNullary)() = 0; - STDMETHOD_(bool, CTUnary)(int x) = 0; - STDMETHOD_(int, CTDecimal) - (bool b, char c, short d, int e, long f, // NOLINT - float g, double h, unsigned i, char* j, const std::string& k) = 0; - STDMETHOD_(char, CTConst)(int x) const = 0; -#endif // GTEST_OS_WINDOWS -}; - -// Const qualifiers on arguments were once (incorrectly) considered -// significant in determining whether two virtual functions had the same -// signature. This was fixed in Visual Studio 2008. However, the compiler -// still emits a warning that alerts about this change in behavior. -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4373) -#endif -class MockFoo : public FooInterface { - public: - MockFoo() {} - - // Makes sure that a mock function parameter can be named. - MOCK_METHOD1(VoidReturning, void(int n)); // NOLINT - - MOCK_METHOD0(Nullary, int()); // NOLINT - - // Makes sure that a mock function parameter can be unnamed. - MOCK_METHOD1(Unary, bool(int)); // NOLINT - MOCK_METHOD2(Binary, long(short, int)); // NOLINT - MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT - double, unsigned, char*, const std::string& str)); - - MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT - MOCK_METHOD1(TakesConstReference, std::string(const int&)); - MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT - - // Tests that the function return type can contain unprotected comma. - MOCK_METHOD0(ReturnTypeWithComma, std::map()); - MOCK_CONST_METHOD1(ReturnTypeWithComma, - std::map(int)); // NOLINT - - MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT - MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT - - MOCK_METHOD1(OverloadedOnArgumentType, int(int)); // NOLINT - MOCK_METHOD1(OverloadedOnArgumentType, char(char)); // NOLINT - - MOCK_METHOD0(OverloadedOnConstness, int()); // NOLINT - MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT - - MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT - MOCK_METHOD1(TypeWithComma, - int(const std::map&)); // NOLINT - MOCK_METHOD1(TypeWithTemplatedCopyCtor, - int(const TemplatedCopyable&)); // NOLINT - -#if GTEST_OS_WINDOWS - MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int()); - MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int)); - MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, - int(bool b, char c, short d, int e, long f, - float g, double h, unsigned i, char* j, - const std::string& k)); - MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int)); - - // Tests that the function return type can contain unprotected comma. - MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma, - std::map()); -#endif // GTEST_OS_WINDOWS - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); -}; -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -class FunctionMockerTest : public testing::Test { - protected: - FunctionMockerTest() : foo_(&mock_foo_) {} - - FooInterface* const foo_; - MockFoo mock_foo_; -}; - -// Tests mocking a void-returning function. -TEST_F(FunctionMockerTest, MocksVoidFunction) { - EXPECT_CALL(mock_foo_, VoidReturning(Lt(100))); - foo_->VoidReturning(0); -} - -// Tests mocking a nullary function. -TEST_F(FunctionMockerTest, MocksNullaryFunction) { - EXPECT_CALL(mock_foo_, Nullary()) - .WillOnce(DoDefault()) - .WillOnce(Return(1)); - - EXPECT_EQ(0, foo_->Nullary()); - EXPECT_EQ(1, foo_->Nullary()); -} - -// Tests mocking a unary function. -TEST_F(FunctionMockerTest, MocksUnaryFunction) { - EXPECT_CALL(mock_foo_, Unary(Eq(2))) - .Times(2) - .WillOnce(Return(true)); - - EXPECT_TRUE(foo_->Unary(2)); - EXPECT_FALSE(foo_->Unary(2)); -} - -// Tests mocking a binary function. -TEST_F(FunctionMockerTest, MocksBinaryFunction) { - EXPECT_CALL(mock_foo_, Binary(2, _)) - .WillOnce(Return(3)); - - EXPECT_EQ(3, foo_->Binary(2, 1)); -} - -// Tests mocking a decimal function. -TEST_F(FunctionMockerTest, MocksDecimalFunction) { - EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A(), Lt(100), 5U, - nullptr, "hi")) - .WillOnce(Return(5)); - - EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); -} - -// Tests mocking a function that takes a non-const reference. -TEST_F(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) { - int a = 0; - EXPECT_CALL(mock_foo_, TakesNonConstReference(Ref(a))) - .WillOnce(Return(true)); - - EXPECT_TRUE(foo_->TakesNonConstReference(a)); -} - -// Tests mocking a function that takes a const reference. -TEST_F(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) { - int a = 0; - EXPECT_CALL(mock_foo_, TakesConstReference(Ref(a))) - .WillOnce(Return("Hello")); - - EXPECT_EQ("Hello", foo_->TakesConstReference(a)); -} - -// Tests mocking a function that takes a const variable. -TEST_F(FunctionMockerTest, MocksFunctionWithConstArgument) { - EXPECT_CALL(mock_foo_, TakesConst(Lt(10))) - .WillOnce(DoDefault()); - - EXPECT_FALSE(foo_->TakesConst(5)); -} - -// Tests mocking functions overloaded on the number of arguments. -TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) { - EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber()) - .WillOnce(Return(1)); - EXPECT_CALL(mock_foo_, OverloadedOnArgumentNumber(_)) - .WillOnce(Return(2)); - - EXPECT_EQ(2, foo_->OverloadedOnArgumentNumber(1)); - EXPECT_EQ(1, foo_->OverloadedOnArgumentNumber()); -} - -// Tests mocking functions overloaded on the types of argument. -TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) { - EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(An())) - .WillOnce(Return(1)); - EXPECT_CALL(mock_foo_, OverloadedOnArgumentType(TypedEq('a'))) - .WillOnce(Return('b')); - - EXPECT_EQ(1, foo_->OverloadedOnArgumentType(0)); - EXPECT_EQ('b', foo_->OverloadedOnArgumentType('a')); -} - -// Tests mocking functions overloaded on the const-ness of this object. -TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) { - EXPECT_CALL(mock_foo_, OverloadedOnConstness()); - EXPECT_CALL(Const(mock_foo_), OverloadedOnConstness()) - .WillOnce(Return('a')); - - EXPECT_EQ(0, foo_->OverloadedOnConstness()); - EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness()); -} - -TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) { - const std::map a_map; - EXPECT_CALL(mock_foo_, ReturnTypeWithComma()) - .WillOnce(Return(a_map)); - EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42)) - .WillOnce(Return(a_map)); - - EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma()); - EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42)); -} - -TEST_F(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) { - EXPECT_CALL(mock_foo_, TypeWithTemplatedCopyCtor(_)).WillOnce(Return(true)); - EXPECT_TRUE(foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable())); -} - -#if GTEST_OS_WINDOWS -// Tests mocking a nullary function with calltype. -TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) { - EXPECT_CALL(mock_foo_, CTNullary()) - .WillOnce(Return(-1)) - .WillOnce(Return(0)); - - EXPECT_EQ(-1, foo_->CTNullary()); - EXPECT_EQ(0, foo_->CTNullary()); -} - -// Tests mocking a unary function with calltype. -TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) { - EXPECT_CALL(mock_foo_, CTUnary(Eq(2))) - .Times(2) - .WillOnce(Return(true)) - .WillOnce(Return(false)); - - EXPECT_TRUE(foo_->CTUnary(2)); - EXPECT_FALSE(foo_->CTUnary(2)); -} - -// Tests mocking a decimal function with calltype. -TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) { - EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A(), Lt(100), 5U, - nullptr, "hi")) - .WillOnce(Return(10)); - - EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); -} - -// Tests mocking functions overloaded on the const-ness of this object. -TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) { - EXPECT_CALL(Const(mock_foo_), CTConst(_)) - .WillOnce(Return('a')); - - EXPECT_EQ('a', Const(*foo_).CTConst(0)); -} - -TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) { - const std::map a_map; - EXPECT_CALL(mock_foo_, CTReturnTypeWithComma()) - .WillOnce(Return(a_map)); - - EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma()); -} - -#endif // GTEST_OS_WINDOWS - -class MockB { - public: - MockB() {} - - MOCK_METHOD0(DoB, void()); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); -}; - -// Tests that functions with no EXPECT_CALL() ruls can be called any -// number of times. -TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) { - { - MockB b; - } - - { - MockB b; - b.DoB(); - } - - { - MockB b; - b.DoB(); - b.DoB(); - } -} - -// Tests mocking template interfaces. - -template -class StackInterface { - public: - virtual ~StackInterface() {} - - // Template parameter appears in function parameter. - virtual void Push(const T& value) = 0; - virtual void Pop() = 0; - virtual int GetSize() const = 0; - // Template parameter appears in function return type. - virtual const T& GetTop() const = 0; -}; - -template -class MockStack : public StackInterface { - public: - MockStack() {} - - MOCK_METHOD1_T(Push, void(const T& elem)); - MOCK_METHOD0_T(Pop, void()); - MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT - MOCK_CONST_METHOD0_T(GetTop, const T&()); - - // Tests that the function return type can contain unprotected comma. - MOCK_METHOD0_T(ReturnTypeWithComma, std::map()); - MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map(int)); // NOLINT - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack); -}; - -// Tests that template mock works. -TEST(TemplateMockTest, Works) { - MockStack mock; - - EXPECT_CALL(mock, GetSize()) - .WillOnce(Return(0)) - .WillOnce(Return(1)) - .WillOnce(Return(0)); - EXPECT_CALL(mock, Push(_)); - int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); - - EXPECT_EQ(0, mock.GetSize()); - mock.Push(5); - EXPECT_EQ(1, mock.GetSize()); - EXPECT_EQ(5, mock.GetTop()); - mock.Pop(); - EXPECT_EQ(0, mock.GetSize()); -} - -TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) { - MockStack mock; - - const std::map a_map; - EXPECT_CALL(mock, ReturnTypeWithComma()) - .WillOnce(Return(a_map)); - EXPECT_CALL(mock, ReturnTypeWithComma(1)) - .WillOnce(Return(a_map)); - - EXPECT_EQ(a_map, mock.ReturnTypeWithComma()); - EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1)); -} - -#if GTEST_OS_WINDOWS -// Tests mocking template interfaces with calltype. - -template -class StackInterfaceWithCallType { - public: - virtual ~StackInterfaceWithCallType() {} - - // Template parameter appears in function parameter. - STDMETHOD_(void, Push)(const T& value) = 0; - STDMETHOD_(void, Pop)() = 0; - STDMETHOD_(int, GetSize)() const = 0; - // Template parameter appears in function return type. - STDMETHOD_(const T&, GetTop)() const = 0; -}; - -template -class MockStackWithCallType : public StackInterfaceWithCallType { - public: - MockStackWithCallType() {} - - MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem)); - MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void()); - MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int()); - MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&()); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStackWithCallType); -}; - -// Tests that template mock with calltype works. -TEST(TemplateMockTestWithCallType, Works) { - MockStackWithCallType mock; - - EXPECT_CALL(mock, GetSize()) - .WillOnce(Return(0)) - .WillOnce(Return(1)) - .WillOnce(Return(0)); - EXPECT_CALL(mock, Push(_)); - int n = 5; - EXPECT_CALL(mock, GetTop()) - .WillOnce(ReturnRef(n)); - EXPECT_CALL(mock, Pop()) - .Times(AnyNumber()); - - EXPECT_EQ(0, mock.GetSize()); - mock.Push(5); - EXPECT_EQ(1, mock.GetSize()); - EXPECT_EQ(5, mock.GetTop()); - mock.Pop(); - EXPECT_EQ(0, mock.GetSize()); -} -#endif // GTEST_OS_WINDOWS - -#define MY_MOCK_METHODS1_ \ - MOCK_METHOD0(Overloaded, void()); \ - MOCK_CONST_METHOD1(Overloaded, int(int n)); \ - MOCK_METHOD2(Overloaded, bool(bool f, int n)) - -class MockOverloadedOnArgNumber { - public: - MockOverloadedOnArgNumber() {} - - MY_MOCK_METHODS1_; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnArgNumber); -}; - -TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) { - MockOverloadedOnArgNumber mock; - EXPECT_CALL(mock, Overloaded()); - EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); - EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true)); - - mock.Overloaded(); - EXPECT_EQ(2, mock.Overloaded(1)); - EXPECT_TRUE(mock.Overloaded(true, 1)); -} - -#define MY_MOCK_METHODS2_ \ - MOCK_CONST_METHOD1(Overloaded, int(int n)); \ - MOCK_METHOD1(Overloaded, int(int n)) - -class MockOverloadedOnConstness { - public: - MockOverloadedOnConstness() {} - - MY_MOCK_METHODS2_; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(MockOverloadedOnConstness); -}; - -TEST(OverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) { - MockOverloadedOnConstness mock; - const MockOverloadedOnConstness* const_mock = &mock; - EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2)); - EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3)); - - EXPECT_EQ(2, mock.Overloaded(1)); - EXPECT_EQ(3, const_mock->Overloaded(1)); -} - -TEST(MockFunctionTest, WorksForVoidNullary) { - MockFunction foo; - EXPECT_CALL(foo, Call()); - foo.Call(); -} - -TEST(MockFunctionTest, WorksForNonVoidNullary) { - MockFunction foo; - EXPECT_CALL(foo, Call()) - .WillOnce(Return(1)) - .WillOnce(Return(2)); - EXPECT_EQ(1, foo.Call()); - EXPECT_EQ(2, foo.Call()); -} - -TEST(MockFunctionTest, WorksForVoidUnary) { - MockFunction foo; - EXPECT_CALL(foo, Call(1)); - foo.Call(1); -} - -TEST(MockFunctionTest, WorksForNonVoidBinary) { - MockFunction foo; - EXPECT_CALL(foo, Call(false, 42)) - .WillOnce(Return(1)) - .WillOnce(Return(2)); - EXPECT_CALL(foo, Call(true, Ge(100))) - .WillOnce(Return(3)); - EXPECT_EQ(1, foo.Call(false, 42)); - EXPECT_EQ(2, foo.Call(false, 42)); - EXPECT_EQ(3, foo.Call(true, 120)); -} - -TEST(MockFunctionTest, WorksFor10Arguments) { - MockFunction foo; - EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _)) - .WillOnce(Return(1)) - .WillOnce(Return(2)); - EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true)); - EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false)); -} - -TEST(MockFunctionTest, AsStdFunction) { - MockFunction foo; - auto call = [](const std::function &f, int i) { - return f(i); - }; - EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1)); - EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2)); - EXPECT_EQ(-1, call(foo.AsStdFunction(), 1)); - EXPECT_EQ(-2, call(foo.AsStdFunction(), 2)); -} - -TEST(MockFunctionTest, AsStdFunctionReturnsReference) { - MockFunction foo; - int value = 1; - EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value)); - int& ref = foo.AsStdFunction()(); - EXPECT_EQ(1, ref); - value = 2; - EXPECT_EQ(2, ref); -} - -TEST(MockFunctionTest, AsStdFunctionWithReferenceParameter) { - MockFunction foo; - auto call = [](const std::function &f, int &i) { - return f(i); - }; - int i = 42; - EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1)); - EXPECT_EQ(-1, call(foo.AsStdFunction(), i)); -} - - -struct MockMethodSizes0 { - MOCK_METHOD0(func, void()); -}; -struct MockMethodSizes1 { - MOCK_METHOD1(func, void(int)); -}; -struct MockMethodSizes2 { - MOCK_METHOD2(func, void(int, int)); -}; -struct MockMethodSizes3 { - MOCK_METHOD3(func, void(int, int, int)); -}; -struct MockMethodSizes4 { - MOCK_METHOD4(func, void(int, int, int, int)); -}; - -TEST(MockFunctionTest, MockMethodSizeOverhead) { - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1)); - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2)); - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3)); - EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4)); -} - -} // namespace gmock_generated_function_mockers_test -} // namespace testing diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-generated-matchers_test.cc b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-generated-matchers_test.cc deleted file mode 100644 index 6783f8f8d..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-generated-matchers_test.cc +++ /dev/null @@ -1,1314 +0,0 @@ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Google Mock - a framework for writing C++ mock classes. -// -// This file tests the built-in matchers generated by a script. - -// Silence warning C4244: 'initializing': conversion from 'int' to 'short', -// possible loss of data and C4100, unreferenced local parameter -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4244) -# pragma warning(disable:4100) -#endif - -#include "gmock/gmock-generated-matchers.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gmock/gmock.h" -#include "gtest/gtest-spi.h" -#include "gtest/gtest.h" - -namespace { - -using std::list; -using std::map; -using std::pair; -using std::set; -using std::stringstream; -using std::vector; -using testing::_; -using testing::AllOf; -using testing::AllOfArray; -using testing::AnyOf; -using testing::AnyOfArray; -using testing::Args; -using testing::Contains; -using testing::ElementsAre; -using testing::ElementsAreArray; -using testing::Eq; -using testing::Ge; -using testing::Gt; -using testing::Le; -using testing::Lt; -using testing::MakeMatcher; -using testing::Matcher; -using testing::MatcherInterface; -using testing::MatchResultListener; -using testing::Ne; -using testing::Not; -using testing::Pointee; -using testing::PrintToString; -using testing::Ref; -using testing::StaticAssertTypeEq; -using testing::StrEq; -using testing::Value; -using testing::internal::ElementsAreArrayMatcher; - -// Returns the description of the given matcher. -template -std::string Describe(const Matcher& m) { - stringstream ss; - m.DescribeTo(&ss); - return ss.str(); -} - -// Returns the description of the negation of the given matcher. -template -std::string DescribeNegation(const Matcher& m) { - stringstream ss; - m.DescribeNegationTo(&ss); - return ss.str(); -} - -// Returns the reason why x matches, or doesn't match, m. -template -std::string Explain(const MatcherType& m, const Value& x) { - stringstream ss; - m.ExplainMatchResultTo(x, &ss); - return ss.str(); -} - -// For testing ExplainMatchResultTo(). -class GreaterThanMatcher : public MatcherInterface { - public: - explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} - - void DescribeTo(::std::ostream* os) const override { - *os << "is greater than " << rhs_; - } - - bool MatchAndExplain(int lhs, MatchResultListener* listener) const override { - const int diff = lhs - rhs_; - if (diff > 0) { - *listener << "which is " << diff << " more than " << rhs_; - } else if (diff == 0) { - *listener << "which is the same as " << rhs_; - } else { - *listener << "which is " << -diff << " less than " << rhs_; - } - - return lhs > rhs_; - } - - private: - int rhs_; -}; - -Matcher GreaterThan(int n) { - return MakeMatcher(new GreaterThanMatcher(n)); -} - -// Tests for ElementsAre(). - -TEST(ElementsAreTest, CanDescribeExpectingNoElement) { - Matcher&> m = ElementsAre(); - EXPECT_EQ("is empty", Describe(m)); -} - -TEST(ElementsAreTest, CanDescribeExpectingOneElement) { - Matcher > m = ElementsAre(Gt(5)); - EXPECT_EQ("has 1 element that is > 5", Describe(m)); -} - -TEST(ElementsAreTest, CanDescribeExpectingManyElements) { - Matcher > m = ElementsAre(StrEq("one"), "two"); - EXPECT_EQ("has 2 elements where\n" - "element #0 is equal to \"one\",\n" - "element #1 is equal to \"two\"", Describe(m)); -} - -TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) { - Matcher > m = ElementsAre(); - EXPECT_EQ("isn't empty", DescribeNegation(m)); -} - -TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) { - Matcher& > m = ElementsAre(Gt(5)); - EXPECT_EQ("doesn't have 1 element, or\n" - "element #0 isn't > 5", DescribeNegation(m)); -} - -TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) { - Matcher&> m = ElementsAre("one", "two"); - EXPECT_EQ("doesn't have 2 elements, or\n" - "element #0 isn't equal to \"one\", or\n" - "element #1 isn't equal to \"two\"", DescribeNegation(m)); -} - -TEST(ElementsAreTest, DoesNotExplainTrivialMatch) { - Matcher& > m = ElementsAre(1, Ne(2)); - - list test_list; - test_list.push_back(1); - test_list.push_back(3); - EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything. -} - -TEST(ElementsAreTest, ExplainsNonTrivialMatch) { - Matcher& > m = - ElementsAre(GreaterThan(1), 0, GreaterThan(2)); - - const int a[] = { 10, 0, 100 }; - vector test_vector(std::begin(a), std::end(a)); - EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n" - "and whose element #2 matches, which is 98 more than 2", - Explain(m, test_vector)); -} - -TEST(ElementsAreTest, CanExplainMismatchWrongSize) { - Matcher& > m = ElementsAre(1, 3); - - list test_list; - // No need to explain when the container is empty. - EXPECT_EQ("", Explain(m, test_list)); - - test_list.push_back(1); - EXPECT_EQ("which has 1 element", Explain(m, test_list)); -} - -TEST(ElementsAreTest, CanExplainMismatchRightSize) { - Matcher& > m = ElementsAre(1, GreaterThan(5)); - - vector v; - v.push_back(2); - v.push_back(1); - EXPECT_EQ("whose element #0 doesn't match", Explain(m, v)); - - v[0] = 1; - EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5", - Explain(m, v)); -} - -TEST(ElementsAreTest, MatchesOneElementVector) { - vector test_vector; - test_vector.push_back("test string"); - - EXPECT_THAT(test_vector, ElementsAre(StrEq("test string"))); -} - -TEST(ElementsAreTest, MatchesOneElementList) { - list test_list; - test_list.push_back("test string"); - - EXPECT_THAT(test_list, ElementsAre("test string")); -} - -TEST(ElementsAreTest, MatchesThreeElementVector) { - vector test_vector; - test_vector.push_back("one"); - test_vector.push_back("two"); - test_vector.push_back("three"); - - EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _)); -} - -TEST(ElementsAreTest, MatchesOneElementEqMatcher) { - vector test_vector; - test_vector.push_back(4); - - EXPECT_THAT(test_vector, ElementsAre(Eq(4))); -} - -TEST(ElementsAreTest, MatchesOneElementAnyMatcher) { - vector test_vector; - test_vector.push_back(4); - - EXPECT_THAT(test_vector, ElementsAre(_)); -} - -TEST(ElementsAreTest, MatchesOneElementValue) { - vector test_vector; - test_vector.push_back(4); - - EXPECT_THAT(test_vector, ElementsAre(4)); -} - -TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) { - vector test_vector; - test_vector.push_back(1); - test_vector.push_back(2); - test_vector.push_back(3); - - EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _)); -} - -TEST(ElementsAreTest, MatchesTenElementVector) { - const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - vector test_vector(std::begin(a), std::end(a)); - - EXPECT_THAT(test_vector, - // The element list can contain values and/or matchers - // of different types. - ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _)); -} - -TEST(ElementsAreTest, DoesNotMatchWrongSize) { - vector test_vector; - test_vector.push_back("test string"); - test_vector.push_back("test string"); - - Matcher > m = ElementsAre(StrEq("test string")); - EXPECT_FALSE(m.Matches(test_vector)); -} - -TEST(ElementsAreTest, DoesNotMatchWrongValue) { - vector test_vector; - test_vector.push_back("other string"); - - Matcher > m = ElementsAre(StrEq("test string")); - EXPECT_FALSE(m.Matches(test_vector)); -} - -TEST(ElementsAreTest, DoesNotMatchWrongOrder) { - vector test_vector; - test_vector.push_back("one"); - test_vector.push_back("three"); - test_vector.push_back("two"); - - Matcher > m = - ElementsAre(StrEq("one"), StrEq("two"), StrEq("three")); - EXPECT_FALSE(m.Matches(test_vector)); -} - -TEST(ElementsAreTest, WorksForNestedContainer) { - constexpr std::array strings = {{"Hi", "world"}}; - - vector > nested; - for (size_t i = 0; i < strings.size(); i++) { - nested.push_back(list(strings[i], strings[i] + strlen(strings[i]))); - } - - EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')), - ElementsAre('w', 'o', _, _, 'd'))); - EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'), - ElementsAre('w', 'o', _, _, 'd')))); -} - -TEST(ElementsAreTest, WorksWithByRefElementMatchers) { - int a[] = { 0, 1, 2 }; - vector v(std::begin(a), std::end(a)); - - EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2]))); - EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2])))); -} - -TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) { - int a[] = { 0, 1, 2 }; - vector v(std::begin(a), std::end(a)); - - EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _))); - EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3)))); -} - -TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) { - int array[] = { 0, 1, 2 }; - EXPECT_THAT(array, ElementsAre(0, 1, _)); - EXPECT_THAT(array, Not(ElementsAre(1, _, _))); - EXPECT_THAT(array, Not(ElementsAre(0, _))); -} - -class NativeArrayPassedAsPointerAndSize { - public: - NativeArrayPassedAsPointerAndSize() {} - - MOCK_METHOD2(Helper, void(int* array, int size)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize); -}; - -TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) { - int array[] = { 0, 1 }; - ::std::tuple array_as_tuple(array, 2); - EXPECT_THAT(array_as_tuple, ElementsAre(0, 1)); - EXPECT_THAT(array_as_tuple, Not(ElementsAre(0))); - - NativeArrayPassedAsPointerAndSize helper; - EXPECT_CALL(helper, Helper(_, _)) - .With(ElementsAre(0, 1)); - helper.Helper(array, 2); -} - -TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) { - const char a2[][3] = { "hi", "lo" }; - EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'), - ElementsAre('l', 'o', '\0'))); - EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo"))); - EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')), - ElementsAre('l', 'o', '\0'))); -} - -TEST(ElementsAreTest, AcceptsStringLiteral) { - std::string array[] = {"hi", "one", "two"}; - EXPECT_THAT(array, ElementsAre("hi", "one", "two")); - EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too"))); -} - -// Declared here with the size unknown. Defined AFTER the following test. -extern const char kHi[]; - -TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) { - // The size of kHi is not known in this test, but ElementsAre() should - // still accept it. - - std::string array1[] = {"hi"}; - EXPECT_THAT(array1, ElementsAre(kHi)); - - std::string array2[] = {"ho"}; - EXPECT_THAT(array2, Not(ElementsAre(kHi))); -} - -const char kHi[] = "hi"; - -TEST(ElementsAreTest, MakesCopyOfArguments) { - int x = 1; - int y = 2; - // This should make a copy of x and y. - ::testing::internal::ElementsAreMatcher > - polymorphic_matcher = ElementsAre(x, y); - // Changing x and y now shouldn't affect the meaning of the above matcher. - x = y = 0; - const int array1[] = { 1, 2 }; - EXPECT_THAT(array1, polymorphic_matcher); - const int array2[] = { 0, 0 }; - EXPECT_THAT(array2, Not(polymorphic_matcher)); -} - - -// Tests for ElementsAreArray(). Since ElementsAreArray() shares most -// of the implementation with ElementsAre(), we don't test it as -// thoroughly here. - -TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) { - const int a[] = { 1, 2, 3 }; - - vector test_vector(std::begin(a), std::end(a)); - EXPECT_THAT(test_vector, ElementsAreArray(a)); - - test_vector[2] = 0; - EXPECT_THAT(test_vector, Not(ElementsAreArray(a))); -} - -TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) { - std::array a = {{"one", "two", "three"}}; - - vector test_vector(std::begin(a), std::end(a)); - EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size())); - - const char** p = a.data(); - test_vector[0] = "1"; - EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size()))); -} - -TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) { - const char* a[] = { "one", "two", "three" }; - - vector test_vector(std::begin(a), std::end(a)); - EXPECT_THAT(test_vector, ElementsAreArray(a)); - - test_vector[0] = "1"; - EXPECT_THAT(test_vector, Not(ElementsAreArray(a))); -} - -TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) { - const Matcher kMatcherArray[] = {StrEq("one"), StrEq("two"), - StrEq("three")}; - - vector test_vector; - test_vector.push_back("one"); - test_vector.push_back("two"); - test_vector.push_back("three"); - EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray)); - - test_vector.push_back("three"); - EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray))); -} - -TEST(ElementsAreArrayTest, CanBeCreatedWithVector) { - const int a[] = { 1, 2, 3 }; - vector test_vector(std::begin(a), std::end(a)); - const vector expected(std::begin(a), std::end(a)); - EXPECT_THAT(test_vector, ElementsAreArray(expected)); - test_vector.push_back(4); - EXPECT_THAT(test_vector, Not(ElementsAreArray(expected))); -} - - -TEST(ElementsAreArrayTest, TakesInitializerList) { - const int a[5] = { 1, 2, 3, 4, 5 }; - EXPECT_THAT(a, ElementsAreArray({ 1, 2, 3, 4, 5 })); - EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 5, 4 }))); - EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 4, 6 }))); -} - -TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) { - const std::string a[5] = {"a", "b", "c", "d", "e"}; - EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" })); - EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" }))); - EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" }))); -} - -TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { - const int a[5] = { 1, 2, 3, 4, 5 }; - EXPECT_THAT(a, ElementsAreArray( - { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) })); - EXPECT_THAT(a, Not(ElementsAreArray( - { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) }))); -} - -TEST(ElementsAreArrayTest, - TakesInitializerListOfDifferentTypedMatchers) { - const int a[5] = { 1, 2, 3, 4, 5 }; - // The compiler cannot infer the type of the initializer list if its - // elements have different types. We must explicitly specify the - // unified element type in this case. - EXPECT_THAT(a, ElementsAreArray >( - { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) })); - EXPECT_THAT(a, Not(ElementsAreArray >( - { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) }))); -} - - -TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) { - const int a[] = { 1, 2, 3 }; - const Matcher kMatchers[] = { Eq(1), Eq(2), Eq(3) }; - vector test_vector(std::begin(a), std::end(a)); - const vector> expected(std::begin(kMatchers), - std::end(kMatchers)); - EXPECT_THAT(test_vector, ElementsAreArray(expected)); - test_vector.push_back(4); - EXPECT_THAT(test_vector, Not(ElementsAreArray(expected))); -} - -TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) { - const int a[] = { 1, 2, 3 }; - const vector test_vector(std::begin(a), std::end(a)); - const vector expected(std::begin(a), std::end(a)); - EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end())); - // Pointers are iterators, too. - EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a))); - // The empty range of NULL pointers should also be okay. - int* const null_int = nullptr; - EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int))); - EXPECT_THAT((vector()), ElementsAreArray(null_int, null_int)); -} - -// Since ElementsAre() and ElementsAreArray() share much of the -// implementation, we only do a sanity test for native arrays here. -TEST(ElementsAreArrayTest, WorksWithNativeArray) { - ::std::string a[] = { "hi", "ho" }; - ::std::string b[] = { "hi", "ho" }; - - EXPECT_THAT(a, ElementsAreArray(b)); - EXPECT_THAT(a, ElementsAreArray(b, 2)); - EXPECT_THAT(a, Not(ElementsAreArray(b, 1))); -} - -TEST(ElementsAreArrayTest, SourceLifeSpan) { - const int a[] = { 1, 2, 3 }; - vector test_vector(std::begin(a), std::end(a)); - vector expect(std::begin(a), std::end(a)); - ElementsAreArrayMatcher matcher_maker = - ElementsAreArray(expect.begin(), expect.end()); - EXPECT_THAT(test_vector, matcher_maker); - // Changing in place the values that initialized matcher_maker should not - // affect matcher_maker anymore. It should have made its own copy of them. - typedef vector::iterator Iter; - for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 10; } - EXPECT_THAT(test_vector, matcher_maker); - test_vector.push_back(3); - EXPECT_THAT(test_vector, Not(matcher_maker)); -} - -// Tests for the MATCHER*() macro family. - -// Tests that a simple MATCHER() definition works. - -MATCHER(IsEven, "") { return (arg % 2) == 0; } - -TEST(MatcherMacroTest, Works) { - const Matcher m = IsEven(); - EXPECT_TRUE(m.Matches(6)); - EXPECT_FALSE(m.Matches(7)); - - EXPECT_EQ("is even", Describe(m)); - EXPECT_EQ("not (is even)", DescribeNegation(m)); - EXPECT_EQ("", Explain(m, 6)); - EXPECT_EQ("", Explain(m, 7)); -} - -// This also tests that the description string can reference 'negation'. -MATCHER(IsEven2, negation ? "is odd" : "is even") { - if ((arg % 2) == 0) { - // Verifies that we can stream to result_listener, a listener - // supplied by the MATCHER macro implicitly. - *result_listener << "OK"; - return true; - } else { - *result_listener << "% 2 == " << (arg % 2); - return false; - } -} - -// This also tests that the description string can reference matcher -// parameters. -MATCHER_P2(EqSumOf, x, y, std::string(negation ? "doesn't equal" : "equals") + - " the sum of " + PrintToString(x) + " and " + - PrintToString(y)) { - if (arg == (x + y)) { - *result_listener << "OK"; - return true; - } else { - // Verifies that we can stream to the underlying stream of - // result_listener. - if (result_listener->stream() != nullptr) { - *result_listener->stream() << "diff == " << (x + y - arg); - } - return false; - } -} - -// Tests that the matcher description can reference 'negation' and the -// matcher parameters. -TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) { - const Matcher m1 = IsEven2(); - EXPECT_EQ("is even", Describe(m1)); - EXPECT_EQ("is odd", DescribeNegation(m1)); - - const Matcher m2 = EqSumOf(5, 9); - EXPECT_EQ("equals the sum of 5 and 9", Describe(m2)); - EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2)); -} - -// Tests explaining match result in a MATCHER* macro. -TEST(MatcherMacroTest, CanExplainMatchResult) { - const Matcher m1 = IsEven2(); - EXPECT_EQ("OK", Explain(m1, 4)); - EXPECT_EQ("% 2 == 1", Explain(m1, 5)); - - const Matcher m2 = EqSumOf(1, 2); - EXPECT_EQ("OK", Explain(m2, 3)); - EXPECT_EQ("diff == -1", Explain(m2, 4)); -} - -// Tests that the body of MATCHER() can reference the type of the -// value being matched. - -MATCHER(IsEmptyString, "") { - StaticAssertTypeEq< ::std::string, arg_type>(); - return arg == ""; -} - -MATCHER(IsEmptyStringByRef, "") { - StaticAssertTypeEq(); - return arg == ""; -} - -TEST(MatcherMacroTest, CanReferenceArgType) { - const Matcher< ::std::string> m1 = IsEmptyString(); - EXPECT_TRUE(m1.Matches("")); - - const Matcher m2 = IsEmptyStringByRef(); - EXPECT_TRUE(m2.Matches("")); -} - -// Tests that MATCHER() can be used in a namespace. - -namespace matcher_test { -MATCHER(IsOdd, "") { return (arg % 2) != 0; } -} // namespace matcher_test - -TEST(MatcherMacroTest, WorksInNamespace) { - Matcher m = matcher_test::IsOdd(); - EXPECT_FALSE(m.Matches(4)); - EXPECT_TRUE(m.Matches(5)); -} - -// Tests that Value() can be used to compose matchers. -MATCHER(IsPositiveOdd, "") { - return Value(arg, matcher_test::IsOdd()) && arg > 0; -} - -TEST(MatcherMacroTest, CanBeComposedUsingValue) { - EXPECT_THAT(3, IsPositiveOdd()); - EXPECT_THAT(4, Not(IsPositiveOdd())); - EXPECT_THAT(-1, Not(IsPositiveOdd())); -} - -// Tests that a simple MATCHER_P() definition works. - -MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; } - -TEST(MatcherPMacroTest, Works) { - const Matcher m = IsGreaterThan32And(5); - EXPECT_TRUE(m.Matches(36)); - EXPECT_FALSE(m.Matches(5)); - - EXPECT_EQ("is greater than 32 and 5", Describe(m)); - EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m)); - EXPECT_EQ("", Explain(m, 36)); - EXPECT_EQ("", Explain(m, 5)); -} - -// Tests that the description is calculated correctly from the matcher name. -MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; } - -TEST(MatcherPMacroTest, GeneratesCorrectDescription) { - const Matcher m = _is_Greater_Than32and_(5); - - EXPECT_EQ("is greater than 32 and 5", Describe(m)); - EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m)); - EXPECT_EQ("", Explain(m, 36)); - EXPECT_EQ("", Explain(m, 5)); -} - -// Tests that a MATCHER_P matcher can be explicitly instantiated with -// a reference parameter type. - -class UncopyableFoo { - public: - explicit UncopyableFoo(char value) : value_(value) {} - private: - UncopyableFoo(const UncopyableFoo&); - void operator=(const UncopyableFoo&); - - char value_; -}; - -MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; } - -TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) { - UncopyableFoo foo1('1'), foo2('2'); - const Matcher m = - ReferencesUncopyable(foo1); - - EXPECT_TRUE(m.Matches(foo1)); - EXPECT_FALSE(m.Matches(foo2)); - - // We don't want the address of the parameter printed, as most - // likely it will just annoy the user. If the address is - // interesting, the user should consider passing the parameter by - // pointer instead. - EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m)); -} - - -// Tests that the body of MATCHER_Pn() can reference the parameter -// types. - -MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") { - StaticAssertTypeEq(); - StaticAssertTypeEq(); // NOLINT - StaticAssertTypeEq(); - return arg == 0; -} - -TEST(MatcherPnMacroTest, CanReferenceParamTypes) { - EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a')); -} - -// Tests that a MATCHER_Pn matcher can be explicitly instantiated with -// reference parameter types. - -MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") { - return &arg == &variable1 || &arg == &variable2; -} - -TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) { - UncopyableFoo foo1('1'), foo2('2'), foo3('3'); - const Matcher m = - ReferencesAnyOf(foo1, foo2); - - EXPECT_TRUE(m.Matches(foo1)); - EXPECT_TRUE(m.Matches(foo2)); - EXPECT_FALSE(m.Matches(foo3)); -} - -TEST(MatcherPnMacroTest, - GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) { - UncopyableFoo foo1('1'), foo2('2'); - const Matcher m = - ReferencesAnyOf(foo1, foo2); - - // We don't want the addresses of the parameters printed, as most - // likely they will just annoy the user. If the addresses are - // interesting, the user should consider passing the parameters by - // pointers instead. - EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)", - Describe(m)); -} - -// Tests that a simple MATCHER_P2() definition works. - -MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; } - -TEST(MatcherPnMacroTest, Works) { - const Matcher m = IsNotInClosedRange(10, 20); // NOLINT - EXPECT_TRUE(m.Matches(36L)); - EXPECT_FALSE(m.Matches(15L)); - - EXPECT_EQ("is not in closed range (10, 20)", Describe(m)); - EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m)); - EXPECT_EQ("", Explain(m, 36L)); - EXPECT_EQ("", Explain(m, 15L)); -} - -// Tests that MATCHER*() definitions can be overloaded on the number -// of parameters; also tests MATCHER_Pn() where n >= 3. - -MATCHER(EqualsSumOf, "") { return arg == 0; } -MATCHER_P(EqualsSumOf, a, "") { return arg == a; } -MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; } -MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; } -MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; } -MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; } -MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") { - return arg == a + b + c + d + e + f; -} -MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") { - return arg == a + b + c + d + e + f + g; -} -MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") { - return arg == a + b + c + d + e + f + g + h; -} -MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") { - return arg == a + b + c + d + e + f + g + h + i; -} -MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") { - return arg == a + b + c + d + e + f + g + h + i + j; -} - -TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) { - EXPECT_THAT(0, EqualsSumOf()); - EXPECT_THAT(1, EqualsSumOf(1)); - EXPECT_THAT(12, EqualsSumOf(10, 2)); - EXPECT_THAT(123, EqualsSumOf(100, 20, 3)); - EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4)); - EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5)); - EXPECT_THAT("abcdef", - EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')); - EXPECT_THAT("abcdefg", - EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g')); - EXPECT_THAT("abcdefgh", - EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', - "h")); - EXPECT_THAT("abcdefghi", - EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', - "h", 'i')); - EXPECT_THAT("abcdefghij", - EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', - "h", 'i', ::std::string("j"))); - - EXPECT_THAT(1, Not(EqualsSumOf())); - EXPECT_THAT(-1, Not(EqualsSumOf(1))); - EXPECT_THAT(-12, Not(EqualsSumOf(10, 2))); - EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3))); - EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4))); - EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5))); - EXPECT_THAT("abcdef ", - Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'))); - EXPECT_THAT("abcdefg ", - Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', - 'g'))); - EXPECT_THAT("abcdefgh ", - Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', - "h"))); - EXPECT_THAT("abcdefghi ", - Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', - "h", 'i'))); - EXPECT_THAT("abcdefghij ", - Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', - "h", 'i', ::std::string("j")))); -} - -// Tests that a MATCHER_Pn() definition can be instantiated with any -// compatible parameter types. -TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) { - EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast(3))); - EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d")); - - EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast(3)))); - EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d"))); -} - -// Tests that the matcher body can promote the parameter types. - -MATCHER_P2(EqConcat, prefix, suffix, "") { - // The following lines promote the two parameters to desired types. - std::string prefix_str(prefix); - char suffix_char = static_cast(suffix); - return arg == prefix_str + suffix_char; -} - -TEST(MatcherPnMacroTest, SimpleTypePromotion) { - Matcher no_promo = - EqConcat(std::string("foo"), 't'); - Matcher promo = - EqConcat("foo", static_cast('t')); - EXPECT_FALSE(no_promo.Matches("fool")); - EXPECT_FALSE(promo.Matches("fool")); - EXPECT_TRUE(no_promo.Matches("foot")); - EXPECT_TRUE(promo.Matches("foot")); -} - -// Verifies the type of a MATCHER*. - -TEST(MatcherPnMacroTest, TypesAreCorrect) { - // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable. - EqualsSumOfMatcher a0 = EqualsSumOf(); - - // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable. - EqualsSumOfMatcherP a1 = EqualsSumOf(1); - - // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk - // variable, and so on. - EqualsSumOfMatcherP2 a2 = EqualsSumOf(1, '2'); - EqualsSumOfMatcherP3 a3 = EqualsSumOf(1, 2, '3'); - EqualsSumOfMatcherP4 a4 = EqualsSumOf(1, 2, 3, '4'); - EqualsSumOfMatcherP5 a5 = - EqualsSumOf(1, 2, 3, 4, '5'); - EqualsSumOfMatcherP6 a6 = - EqualsSumOf(1, 2, 3, 4, 5, '6'); - EqualsSumOfMatcherP7 a7 = - EqualsSumOf(1, 2, 3, 4, 5, 6, '7'); - EqualsSumOfMatcherP8 a8 = - EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8'); - EqualsSumOfMatcherP9 a9 = - EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9'); - EqualsSumOfMatcherP10 a10 = - EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0'); - - // Avoid "unused variable" warnings. - (void)a0; - (void)a1; - (void)a2; - (void)a3; - (void)a4; - (void)a5; - (void)a6; - (void)a7; - (void)a8; - (void)a9; - (void)a10; -} - -// Tests that matcher-typed parameters can be used in Value() inside a -// MATCHER_Pn definition. - -// Succeeds if arg matches exactly 2 of the 3 matchers. -MATCHER_P3(TwoOf, m1, m2, m3, "") { - const int count = static_cast(Value(arg, m1)) - + static_cast(Value(arg, m2)) + static_cast(Value(arg, m3)); - return count == 2; -} - -TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) { - EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10))); - EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0)))); -} - -// Tests Contains(). - -TEST(ContainsTest, ListMatchesWhenElementIsInContainer) { - list some_list; - some_list.push_back(3); - some_list.push_back(1); - some_list.push_back(2); - EXPECT_THAT(some_list, Contains(1)); - EXPECT_THAT(some_list, Contains(Gt(2.5))); - EXPECT_THAT(some_list, Contains(Eq(2.0f))); - - list another_list; - another_list.push_back("fee"); - another_list.push_back("fie"); - another_list.push_back("foe"); - another_list.push_back("fum"); - EXPECT_THAT(another_list, Contains(std::string("fee"))); -} - -TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) { - list some_list; - some_list.push_back(3); - some_list.push_back(1); - EXPECT_THAT(some_list, Not(Contains(4))); -} - -TEST(ContainsTest, SetMatchesWhenElementIsInContainer) { - set some_set; - some_set.insert(3); - some_set.insert(1); - some_set.insert(2); - EXPECT_THAT(some_set, Contains(Eq(1.0))); - EXPECT_THAT(some_set, Contains(Eq(3.0f))); - EXPECT_THAT(some_set, Contains(2)); - - set another_set; - another_set.insert("fee"); - another_set.insert("fie"); - another_set.insert("foe"); - another_set.insert("fum"); - EXPECT_THAT(another_set, Contains(Eq(std::string("fum")))); -} - -TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) { - set some_set; - some_set.insert(3); - some_set.insert(1); - EXPECT_THAT(some_set, Not(Contains(4))); - - set c_string_set; - c_string_set.insert("hello"); - EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str()))); -} - -TEST(ContainsTest, ExplainsMatchResultCorrectly) { - const int a[2] = { 1, 2 }; - Matcher m = Contains(2); - EXPECT_EQ("whose element #1 matches", Explain(m, a)); - - m = Contains(3); - EXPECT_EQ("", Explain(m, a)); - - m = Contains(GreaterThan(0)); - EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a)); - - m = Contains(GreaterThan(10)); - EXPECT_EQ("", Explain(m, a)); -} - -TEST(ContainsTest, DescribesItselfCorrectly) { - Matcher > m = Contains(1); - EXPECT_EQ("contains at least one element that is equal to 1", Describe(m)); - - Matcher > m2 = Not(m); - EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2)); -} - -TEST(ContainsTest, MapMatchesWhenElementIsInContainer) { - map my_map; - const char* bar = "a string"; - my_map[bar] = 2; - EXPECT_THAT(my_map, Contains(pair(bar, 2))); - - map another_map; - another_map["fee"] = 1; - another_map["fie"] = 2; - another_map["foe"] = 3; - another_map["fum"] = 4; - EXPECT_THAT(another_map, - Contains(pair(std::string("fee"), 1))); - EXPECT_THAT(another_map, Contains(pair("fie", 2))); -} - -TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) { - map some_map; - some_map[1] = 11; - some_map[2] = 22; - EXPECT_THAT(some_map, Not(Contains(pair(2, 23)))); -} - -TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) { - const char* string_array[] = { "fee", "fie", "foe", "fum" }; - EXPECT_THAT(string_array, Contains(Eq(std::string("fum")))); -} - -TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) { - int int_array[] = { 1, 2, 3, 4 }; - EXPECT_THAT(int_array, Not(Contains(5))); -} - -TEST(ContainsTest, AcceptsMatcher) { - const int a[] = { 1, 2, 3 }; - EXPECT_THAT(a, Contains(Gt(2))); - EXPECT_THAT(a, Not(Contains(Gt(4)))); -} - -TEST(ContainsTest, WorksForNativeArrayAsTuple) { - const int a[] = { 1, 2 }; - const int* const pointer = a; - EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1)); - EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3)))); -} - -TEST(ContainsTest, WorksForTwoDimensionalNativeArray) { - int a[][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; - EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6))); - EXPECT_THAT(a, Contains(Contains(5))); - EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5)))); - EXPECT_THAT(a, Contains(Not(Contains(5)))); -} - -TEST(AllOfArrayTest, BasicForms) { - // Iterator - std::vector v0{}; - std::vector v1{1}; - std::vector v2{2, 3}; - std::vector v3{4, 4, 4}; - EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end())); - EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end())); - EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end()))); - EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end()))); - EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end())); - // Pointer + size - int ar[6] = {1, 2, 3, 4, 4, 4}; - EXPECT_THAT(0, AllOfArray(ar, 0)); - EXPECT_THAT(1, AllOfArray(ar, 1)); - EXPECT_THAT(2, Not(AllOfArray(ar, 1))); - EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3))); - EXPECT_THAT(4, AllOfArray(ar + 3, 3)); - // Array - // int ar0[0]; Not usable - int ar1[1] = {1}; - int ar2[2] = {2, 3}; - int ar3[3] = {4, 4, 4}; - // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work - EXPECT_THAT(1, AllOfArray(ar1)); - EXPECT_THAT(2, Not(AllOfArray(ar1))); - EXPECT_THAT(3, Not(AllOfArray(ar2))); - EXPECT_THAT(4, AllOfArray(ar3)); - // Container - EXPECT_THAT(0, AllOfArray(v0)); - EXPECT_THAT(1, AllOfArray(v1)); - EXPECT_THAT(2, Not(AllOfArray(v1))); - EXPECT_THAT(3, Not(AllOfArray(v2))); - EXPECT_THAT(4, AllOfArray(v3)); - // Initializer - EXPECT_THAT(0, AllOfArray({})); // Requires template arg. - EXPECT_THAT(1, AllOfArray({1})); - EXPECT_THAT(2, Not(AllOfArray({1}))); - EXPECT_THAT(3, Not(AllOfArray({2, 3}))); - EXPECT_THAT(4, AllOfArray({4, 4, 4})); -} - -TEST(AllOfArrayTest, Matchers) { - // vector - std::vector> matchers{Ge(1), Lt(2)}; - EXPECT_THAT(0, Not(AllOfArray(matchers))); - EXPECT_THAT(1, AllOfArray(matchers)); - EXPECT_THAT(2, Not(AllOfArray(matchers))); - // initializer_list - EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)}))); - EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)})); -} - -TEST(AnyOfArrayTest, BasicForms) { - // Iterator - std::vector v0{}; - std::vector v1{1}; - std::vector v2{2, 3}; - EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end()))); - EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end())); - EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end()))); - EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end())); - EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end()))); - // Pointer + size - int ar[3] = {1, 2, 3}; - EXPECT_THAT(0, Not(AnyOfArray(ar, 0))); - EXPECT_THAT(1, AnyOfArray(ar, 1)); - EXPECT_THAT(2, Not(AnyOfArray(ar, 1))); - EXPECT_THAT(3, AnyOfArray(ar + 1, 2)); - EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2))); - // Array - // int ar0[0]; Not usable - int ar1[1] = {1}; - int ar2[2] = {2, 3}; - // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work - EXPECT_THAT(1, AnyOfArray(ar1)); - EXPECT_THAT(2, Not(AnyOfArray(ar1))); - EXPECT_THAT(3, AnyOfArray(ar2)); - EXPECT_THAT(4, Not(AnyOfArray(ar2))); - // Container - EXPECT_THAT(0, Not(AnyOfArray(v0))); - EXPECT_THAT(1, AnyOfArray(v1)); - EXPECT_THAT(2, Not(AnyOfArray(v1))); - EXPECT_THAT(3, AnyOfArray(v2)); - EXPECT_THAT(4, Not(AnyOfArray(v2))); - // Initializer - EXPECT_THAT(0, Not(AnyOfArray({}))); // Requires template arg. - EXPECT_THAT(1, AnyOfArray({1})); - EXPECT_THAT(2, Not(AnyOfArray({1}))); - EXPECT_THAT(3, AnyOfArray({2, 3})); - EXPECT_THAT(4, Not(AnyOfArray({2, 3}))); -} - -TEST(AnyOfArrayTest, Matchers) { - // We negate test AllOfArrayTest.Matchers. - // vector - std::vector> matchers{Lt(1), Ge(2)}; - EXPECT_THAT(0, AnyOfArray(matchers)); - EXPECT_THAT(1, Not(AnyOfArray(matchers))); - EXPECT_THAT(2, AnyOfArray(matchers)); - // initializer_list - EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)})); - EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)}))); -} - -TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) { - // AnyOfArray and AllOfArry use the same underlying template-template, - // thus it is sufficient to test one here. - const std::vector v0{}; - const std::vector v1{1}; - const std::vector v2{2, 3}; - const Matcher m0 = AnyOfArray(v0); - const Matcher m1 = AnyOfArray(v1); - const Matcher m2 = AnyOfArray(v2); - EXPECT_EQ("", Explain(m0, 0)); - EXPECT_EQ("", Explain(m1, 1)); - EXPECT_EQ("", Explain(m1, 2)); - EXPECT_EQ("", Explain(m2, 3)); - EXPECT_EQ("", Explain(m2, 4)); - EXPECT_EQ("()", Describe(m0)); - EXPECT_EQ("(is equal to 1)", Describe(m1)); - EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2)); - EXPECT_EQ("()", DescribeNegation(m0)); - EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1)); - EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2)); - // Explain with matchers - const Matcher g1 = AnyOfArray({GreaterThan(1)}); - const Matcher g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)}); - // Explains the first positiv match and all prior negative matches... - EXPECT_EQ("which is 1 less than 1", Explain(g1, 0)); - EXPECT_EQ("which is the same as 1", Explain(g1, 1)); - EXPECT_EQ("which is 1 more than 1", Explain(g1, 2)); - EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2", - Explain(g2, 0)); - EXPECT_EQ("which is the same as 1, and which is 1 less than 2", - Explain(g2, 1)); - EXPECT_EQ("which is 1 more than 1", // Only the first - Explain(g2, 2)); -} - -TEST(AllOfTest, HugeMatcher) { - // Verify that using AllOf with many arguments doesn't cause - // the compiler to exceed template instantiation depth limit. - EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _, - testing::AllOf(_, _, _, _, _, _, _, _, _, _))); -} - -TEST(AnyOfTest, HugeMatcher) { - // Verify that using AnyOf with many arguments doesn't cause - // the compiler to exceed template instantiation depth limit. - EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _, - testing::AnyOf(_, _, _, _, _, _, _, _, _, _))); -} - -namespace adl_test { - -// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf -// don't issue unqualified recursive calls. If they do, the argument dependent -// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found -// as a candidate and the compilation will break due to an ambiguous overload. - -// The matcher must be in the same namespace as AllOf/AnyOf to make argument -// dependent lookup find those. -MATCHER(M, "") { return true; } - -template -bool AllOf(const T1& /*t1*/, const T2& /*t2*/) { return true; } - -TEST(AllOfTest, DoesNotCallAllOfUnqualified) { - EXPECT_THAT(42, testing::AllOf( - M(), M(), M(), M(), M(), M(), M(), M(), M(), M())); -} - -template bool -AnyOf(const T1& t1, const T2& t2) { return true; } - -TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) { - EXPECT_THAT(42, testing::AnyOf( - M(), M(), M(), M(), M(), M(), M(), M(), M(), M())); -} - -} // namespace adl_test - - -TEST(AllOfTest, WorksOnMoveOnlyType) { - std::unique_ptr p(new int(3)); - EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5)))); - EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3))))); -} - -TEST(AnyOfTest, WorksOnMoveOnlyType) { - std::unique_ptr p(new int(3)); - EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5)))); - EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5))))); -} - -MATCHER(IsNotNull, "") { - return arg != nullptr; -} - -// Verifies that a matcher defined using MATCHER() can work on -// move-only types. -TEST(MatcherMacroTest, WorksOnMoveOnlyType) { - std::unique_ptr p(new int(3)); - EXPECT_THAT(p, IsNotNull()); - EXPECT_THAT(std::unique_ptr(), Not(IsNotNull())); -} - -MATCHER_P(UniquePointee, pointee, "") { - return *arg == pointee; -} - -// Verifies that a matcher defined using MATCHER_P*() can work on -// move-only types. -TEST(MatcherPMacroTest, WorksOnMoveOnlyType) { - std::unique_ptr p(new int(3)); - EXPECT_THAT(p, UniquePointee(3)); - EXPECT_THAT(p, Not(UniquePointee(2))); -} - - -} // namespace - -#ifdef _MSC_VER -# pragma warning(pop) -#endif diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-matchers_test.cc b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-matchers_test.cc deleted file mode 100644 index e6e8c8f40..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-matchers_test.cc +++ /dev/null @@ -1,6909 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file tests some commonly used argument matchers. - -// Silence warning C4244: 'initializing': conversion from 'int' to 'short', -// possible loss of data and C4100, unreferenced local parameter -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4244) -# pragma warning(disable:4100) -#endif - -#include "gmock/gmock-matchers.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gmock/gmock-more-matchers.h" -#include "gmock/gmock.h" -#include "gtest/gtest-spi.h" -#include "gtest/gtest.h" - -namespace testing { -namespace gmock_matchers_test { -namespace { - -using std::greater; -using std::less; -using std::list; -using std::make_pair; -using std::map; -using std::multimap; -using std::multiset; -using std::ostream; -using std::pair; -using std::set; -using std::stringstream; -using std::vector; -using testing::internal::DummyMatchResultListener; -using testing::internal::ElementMatcherPair; -using testing::internal::ElementMatcherPairs; -using testing::internal::ExplainMatchFailureTupleTo; -using testing::internal::FloatingEqMatcher; -using testing::internal::FormatMatcherDescription; -using testing::internal::IsReadableTypeName; -using testing::internal::MatchMatrix; -using testing::internal::PredicateFormatterFromMatcher; -using testing::internal::RE; -using testing::internal::StreamMatchResultListener; -using testing::internal::Strings; - -// Helper for testing container-valued matchers in mock method context. It is -// important to test matchers in this context, since it requires additional type -// deduction beyond what EXPECT_THAT does, thus making it more restrictive. -struct ContainerHelper { - MOCK_METHOD1(Call, void(std::vector>)); -}; - -std::vector> MakeUniquePtrs(const std::vector& ints) { - std::vector> pointers; - for (int i : ints) pointers.emplace_back(new int(i)); - return pointers; -} - -// For testing ExplainMatchResultTo(). -class GreaterThanMatcher : public MatcherInterface { - public: - explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} - - void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; } - - bool MatchAndExplain(int lhs, MatchResultListener* listener) const override { - const int diff = lhs - rhs_; - if (diff > 0) { - *listener << "which is " << diff << " more than " << rhs_; - } else if (diff == 0) { - *listener << "which is the same as " << rhs_; - } else { - *listener << "which is " << -diff << " less than " << rhs_; - } - - return lhs > rhs_; - } - - private: - int rhs_; -}; - -Matcher GreaterThan(int n) { - return MakeMatcher(new GreaterThanMatcher(n)); -} - -std::string OfType(const std::string& type_name) { -#if GTEST_HAS_RTTI - return " (of type " + type_name + ")"; -#else - return ""; -#endif -} - -// Returns the description of the given matcher. -template -std::string Describe(const Matcher& m) { - return DescribeMatcher(m); -} - -// Returns the description of the negation of the given matcher. -template -std::string DescribeNegation(const Matcher& m) { - return DescribeMatcher(m, true); -} - -// Returns the reason why x matches, or doesn't match, m. -template -std::string Explain(const MatcherType& m, const Value& x) { - StringMatchResultListener listener; - ExplainMatchResult(m, x, &listener); - return listener.str(); -} - -TEST(MonotonicMatcherTest, IsPrintable) { - stringstream ss; - ss << GreaterThan(5); - EXPECT_EQ("is > 5", ss.str()); -} - -TEST(MatchResultListenerTest, StreamingWorks) { - StringMatchResultListener listener; - listener << "hi" << 5; - EXPECT_EQ("hi5", listener.str()); - - listener.Clear(); - EXPECT_EQ("", listener.str()); - - listener << 42; - EXPECT_EQ("42", listener.str()); - - // Streaming shouldn't crash when the underlying ostream is NULL. - DummyMatchResultListener dummy; - dummy << "hi" << 5; -} - -TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { - EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr); - EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr); - - EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); -} - -TEST(MatchResultListenerTest, IsInterestedWorks) { - EXPECT_TRUE(StringMatchResultListener().IsInterested()); - EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); - - EXPECT_FALSE(DummyMatchResultListener().IsInterested()); - EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested()); -} - -// Makes sure that the MatcherInterface interface doesn't -// change. -class EvenMatcherImpl : public MatcherInterface { - public: - bool MatchAndExplain(int x, - MatchResultListener* /* listener */) const override { - return x % 2 == 0; - } - - void DescribeTo(ostream* os) const override { *os << "is an even number"; } - - // We deliberately don't define DescribeNegationTo() and - // ExplainMatchResultTo() here, to make sure the definition of these - // two methods is optional. -}; - -// Makes sure that the MatcherInterface API doesn't change. -TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) { - EvenMatcherImpl m; -} - -// Tests implementing a monomorphic matcher using MatchAndExplain(). - -class NewEvenMatcherImpl : public MatcherInterface { - public: - bool MatchAndExplain(int x, MatchResultListener* listener) const override { - const bool match = x % 2 == 0; - // Verifies that we can stream to a listener directly. - *listener << "value % " << 2; - if (listener->stream() != nullptr) { - // Verifies that we can stream to a listener's underlying stream - // too. - *listener->stream() << " == " << (x % 2); - } - return match; - } - - void DescribeTo(ostream* os) const override { *os << "is an even number"; } -}; - -TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) { - Matcher m = MakeMatcher(new NewEvenMatcherImpl); - EXPECT_TRUE(m.Matches(2)); - EXPECT_FALSE(m.Matches(3)); - EXPECT_EQ("value % 2 == 0", Explain(m, 2)); - EXPECT_EQ("value % 2 == 1", Explain(m, 3)); -} - -// Tests default-constructing a matcher. -TEST(MatcherTest, CanBeDefaultConstructed) { - Matcher m; -} - -// Tests that Matcher can be constructed from a MatcherInterface*. -TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { - const MatcherInterface* impl = new EvenMatcherImpl; - Matcher m(impl); - EXPECT_TRUE(m.Matches(4)); - EXPECT_FALSE(m.Matches(5)); -} - -// Tests that value can be used in place of Eq(value). -TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) { - Matcher m1 = 5; - EXPECT_TRUE(m1.Matches(5)); - EXPECT_FALSE(m1.Matches(6)); -} - -// Tests that NULL can be used in place of Eq(NULL). -TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { - Matcher m1 = nullptr; - EXPECT_TRUE(m1.Matches(nullptr)); - int n = 0; - EXPECT_FALSE(m1.Matches(&n)); -} - -// Tests that matchers can be constructed from a variable that is not properly -// defined. This should be illegal, but many users rely on this accidentally. -struct Undefined { - virtual ~Undefined() = 0; - static const int kInt = 1; -}; - -TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) { - Matcher m1 = Undefined::kInt; - EXPECT_TRUE(m1.Matches(1)); - EXPECT_FALSE(m1.Matches(2)); -} - -// Test that a matcher parameterized with an abstract class compiles. -TEST(MatcherTest, CanAcceptAbstractClass) { Matcher m = _; } - -// Tests that matchers are copyable. -TEST(MatcherTest, IsCopyable) { - // Tests the copy constructor. - Matcher m1 = Eq(false); - EXPECT_TRUE(m1.Matches(false)); - EXPECT_FALSE(m1.Matches(true)); - - // Tests the assignment operator. - m1 = Eq(true); - EXPECT_TRUE(m1.Matches(true)); - EXPECT_FALSE(m1.Matches(false)); -} - -// Tests that Matcher::DescribeTo() calls -// MatcherInterface::DescribeTo(). -TEST(MatcherTest, CanDescribeItself) { - EXPECT_EQ("is an even number", - Describe(Matcher(new EvenMatcherImpl))); -} - -// Tests Matcher::MatchAndExplain(). -TEST(MatcherTest, MatchAndExplain) { - Matcher m = GreaterThan(0); - StringMatchResultListener listener1; - EXPECT_TRUE(m.MatchAndExplain(42, &listener1)); - EXPECT_EQ("which is 42 more than 0", listener1.str()); - - StringMatchResultListener listener2; - EXPECT_FALSE(m.MatchAndExplain(-9, &listener2)); - EXPECT_EQ("which is 9 less than 0", listener2.str()); -} - -// Tests that a C-string literal can be implicitly converted to a -// Matcher or Matcher. -TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher m1 = "hi"; - EXPECT_TRUE(m1.Matches("hi")); - EXPECT_FALSE(m1.Matches("hello")); - - Matcher m2 = "hi"; - EXPECT_TRUE(m2.Matches("hi")); - EXPECT_FALSE(m2.Matches("hello")); -} - -// Tests that a string object can be implicitly converted to a -// Matcher or Matcher. -TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher m1 = std::string("hi"); - EXPECT_TRUE(m1.Matches("hi")); - EXPECT_FALSE(m1.Matches("hello")); - - Matcher m2 = std::string("hi"); - EXPECT_TRUE(m2.Matches("hi")); - EXPECT_FALSE(m2.Matches("hello")); -} - -#if GTEST_HAS_ABSL -// Tests that a C-string literal can be implicitly converted to a -// Matcher or Matcher. -TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { - Matcher m1 = "cats"; - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher m2 = "cats"; - EXPECT_TRUE(m2.Matches("cats")); - EXPECT_FALSE(m2.Matches("dogs")); -} - -// Tests that a std::string object can be implicitly converted to a -// Matcher or Matcher. -TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { - Matcher m1 = std::string("cats"); - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher m2 = std::string("cats"); - EXPECT_TRUE(m2.Matches("cats")); - EXPECT_FALSE(m2.Matches("dogs")); -} - -// Tests that a absl::string_view object can be implicitly converted to a -// Matcher or Matcher. -TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { - Matcher m1 = absl::string_view("cats"); - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher m2 = absl::string_view("cats"); - EXPECT_TRUE(m2.Matches("cats")); - EXPECT_FALSE(m2.Matches("dogs")); -} -#endif // GTEST_HAS_ABSL - -// Tests that a std::reference_wrapper object can be implicitly -// converted to a Matcher or Matcher via Eq(). -TEST(StringMatcherTest, - CanBeImplicitlyConstructedFromEqReferenceWrapperString) { - std::string value = "cats"; - Matcher m1 = Eq(std::ref(value)); - EXPECT_TRUE(m1.Matches("cats")); - EXPECT_FALSE(m1.Matches("dogs")); - - Matcher m2 = Eq(std::ref(value)); - EXPECT_TRUE(m2.Matches("cats")); - EXPECT_FALSE(m2.Matches("dogs")); -} - -// Tests that MakeMatcher() constructs a Matcher from a -// MatcherInterface* without requiring the user to explicitly -// write the type. -TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { - const MatcherInterface* dummy_impl = nullptr; - Matcher m = MakeMatcher(dummy_impl); -} - -// Tests that MakePolymorphicMatcher() can construct a polymorphic -// matcher from its implementation using the old API. -const int g_bar = 1; -class ReferencesBarOrIsZeroImpl { - public: - template - bool MatchAndExplain(const T& x, - MatchResultListener* /* listener */) const { - const void* p = &x; - return p == &g_bar || x == 0; - } - - void DescribeTo(ostream* os) const { *os << "g_bar or zero"; } - - void DescribeNegationTo(ostream* os) const { - *os << "doesn't reference g_bar and is not zero"; - } -}; - -// This function verifies that MakePolymorphicMatcher() returns a -// PolymorphicMatcher where T is the argument's type. -PolymorphicMatcher ReferencesBarOrIsZero() { - return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl()); -} - -TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { - // Using a polymorphic matcher to match a reference type. - Matcher m1 = ReferencesBarOrIsZero(); - EXPECT_TRUE(m1.Matches(0)); - // Verifies that the identity of a by-reference argument is preserved. - EXPECT_TRUE(m1.Matches(g_bar)); - EXPECT_FALSE(m1.Matches(1)); - EXPECT_EQ("g_bar or zero", Describe(m1)); - - // Using a polymorphic matcher to match a value type. - Matcher m2 = ReferencesBarOrIsZero(); - EXPECT_TRUE(m2.Matches(0.0)); - EXPECT_FALSE(m2.Matches(0.1)); - EXPECT_EQ("g_bar or zero", Describe(m2)); -} - -// Tests implementing a polymorphic matcher using MatchAndExplain(). - -class PolymorphicIsEvenImpl { - public: - void DescribeTo(ostream* os) const { *os << "is even"; } - - void DescribeNegationTo(ostream* os) const { - *os << "is odd"; - } - - template - bool MatchAndExplain(const T& x, MatchResultListener* listener) const { - // Verifies that we can stream to the listener directly. - *listener << "% " << 2; - if (listener->stream() != nullptr) { - // Verifies that we can stream to the listener's underlying stream - // too. - *listener->stream() << " == " << (x % 2); - } - return (x % 2) == 0; - } -}; - -PolymorphicMatcher PolymorphicIsEven() { - return MakePolymorphicMatcher(PolymorphicIsEvenImpl()); -} - -TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) { - // Using PolymorphicIsEven() as a Matcher. - const Matcher m1 = PolymorphicIsEven(); - EXPECT_TRUE(m1.Matches(42)); - EXPECT_FALSE(m1.Matches(43)); - EXPECT_EQ("is even", Describe(m1)); - - const Matcher not_m1 = Not(m1); - EXPECT_EQ("is odd", Describe(not_m1)); - - EXPECT_EQ("% 2 == 0", Explain(m1, 42)); - - // Using PolymorphicIsEven() as a Matcher. - const Matcher m2 = PolymorphicIsEven(); - EXPECT_TRUE(m2.Matches('\x42')); - EXPECT_FALSE(m2.Matches('\x43')); - EXPECT_EQ("is even", Describe(m2)); - - const Matcher not_m2 = Not(m2); - EXPECT_EQ("is odd", Describe(not_m2)); - - EXPECT_EQ("% 2 == 0", Explain(m2, '\x42')); -} - -// Tests that MatcherCast(m) works when m is a polymorphic matcher. -TEST(MatcherCastTest, FromPolymorphicMatcher) { - Matcher m = MatcherCast(Eq(5)); - EXPECT_TRUE(m.Matches(5)); - EXPECT_FALSE(m.Matches(6)); -} - -// For testing casting matchers between compatible types. -class IntValue { - public: - // An int can be statically (although not implicitly) cast to a - // IntValue. - explicit IntValue(int a_value) : value_(a_value) {} - - int value() const { return value_; } - private: - int value_; -}; - -// For testing casting matchers between compatible types. -bool IsPositiveIntValue(const IntValue& foo) { - return foo.value() > 0; -} - -// Tests that MatcherCast(m) works when m is a Matcher where T -// can be statically converted to U. -TEST(MatcherCastTest, FromCompatibleType) { - Matcher m1 = Eq(2.0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(2)); - EXPECT_FALSE(m2.Matches(3)); - - Matcher m3 = Truly(IsPositiveIntValue); - Matcher m4 = MatcherCast(m3); - // In the following, the arguments 1 and 0 are statically converted - // to IntValue objects, and then tested by the IsPositiveIntValue() - // predicate. - EXPECT_TRUE(m4.Matches(1)); - EXPECT_FALSE(m4.Matches(0)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromConstReferenceToNonReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromReferenceToNonReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromNonReferenceToConstReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromNonReferenceToReference) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - int n = 0; - EXPECT_TRUE(m2.Matches(n)); - n = 1; - EXPECT_FALSE(m2.Matches(n)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(MatcherCastTest, FromSameType) { - Matcher m1 = Eq(0); - Matcher m2 = MatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that MatcherCast(m) works when m is a value of the same type as the -// value type of the Matcher. -TEST(MatcherCastTest, FromAValue) { - Matcher m = MatcherCast(42); - EXPECT_TRUE(m.Matches(42)); - EXPECT_FALSE(m.Matches(239)); -} - -// Tests that MatcherCast(m) works when m is a value of the type implicitly -// convertible to the value type of the Matcher. -TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) { - const int kExpected = 'c'; - Matcher m = MatcherCast('c'); - EXPECT_TRUE(m.Matches(kExpected)); - EXPECT_FALSE(m.Matches(kExpected + 1)); -} - -struct NonImplicitlyConstructibleTypeWithOperatorEq { - friend bool operator==( - const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */, - int rhs) { - return 42 == rhs; - } - friend bool operator==( - int lhs, - const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) { - return lhs == 42; - } -}; - -// Tests that MatcherCast(m) works when m is a neither a matcher nor -// implicitly convertible to the value type of the Matcher, but the value type -// of the matcher has operator==() overload accepting m. -TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) { - Matcher m1 = - MatcherCast(42); - EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); - - Matcher m2 = - MatcherCast(239); - EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); - - // When updating the following lines please also change the comment to - // namespace convertible_from_any. - Matcher m3 = - MatcherCast(NonImplicitlyConstructibleTypeWithOperatorEq()); - EXPECT_TRUE(m3.Matches(42)); - EXPECT_FALSE(m3.Matches(239)); -} - -// ConvertibleFromAny does not work with MSVC. resulting in -// error C2440: 'initializing': cannot convert from 'Eq' to 'M' -// No constructor could take the source type, or constructor overload -// resolution was ambiguous - -#if !defined _MSC_VER - -// The below ConvertibleFromAny struct is implicitly constructible from anything -// and when in the same namespace can interact with other tests. In particular, -// if it is in the same namespace as other tests and one removes -// NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...); -// then the corresponding test still compiles (and it should not!) by implicitly -// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny -// in m3.Matcher(). -namespace convertible_from_any { -// Implicitly convertible from any type. -struct ConvertibleFromAny { - ConvertibleFromAny(int a_value) : value(a_value) {} - template - ConvertibleFromAny(const T& /*a_value*/) : value(-1) { - ADD_FAILURE() << "Conversion constructor called"; - } - int value; -}; - -bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) { - return a.value == b.value; -} - -ostream& operator<<(ostream& os, const ConvertibleFromAny& a) { - return os << a.value; -} - -TEST(MatcherCastTest, ConversionConstructorIsUsed) { - Matcher m = MatcherCast(1); - EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); - EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); -} - -TEST(MatcherCastTest, FromConvertibleFromAny) { - Matcher m = - MatcherCast(Eq(ConvertibleFromAny(1))); - EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); - EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); -} -} // namespace convertible_from_any - -#endif // !defined _MSC_VER - -struct IntReferenceWrapper { - IntReferenceWrapper(const int& a_value) : value(&a_value) {} - const int* value; -}; - -bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) { - return a.value == b.value; -} - -TEST(MatcherCastTest, ValueIsNotCopied) { - int n = 42; - Matcher m = MatcherCast(n); - // Verify that the matcher holds a reference to n, not to its temporary copy. - EXPECT_TRUE(m.Matches(n)); -} - -class Base { - public: - virtual ~Base() {} - Base() {} - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(Base); -}; - -class Derived : public Base { - public: - Derived() : Base() {} - int i; -}; - -class OtherDerived : public Base {}; - -// Tests that SafeMatcherCast(m) works when m is a polymorphic matcher. -TEST(SafeMatcherCastTest, FromPolymorphicMatcher) { - Matcher m2 = SafeMatcherCast(Eq(32)); - EXPECT_TRUE(m2.Matches(' ')); - EXPECT_FALSE(m2.Matches('\n')); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher where -// T and U are arithmetic types and T can be losslessly converted to -// U. -TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) { - Matcher m1 = DoubleEq(1.0); - Matcher m2 = SafeMatcherCast(m1); - EXPECT_TRUE(m2.Matches(1.0f)); - EXPECT_FALSE(m2.Matches(2.0f)); - - Matcher m3 = SafeMatcherCast(TypedEq('a')); - EXPECT_TRUE(m3.Matches('a')); - EXPECT_FALSE(m3.Matches('b')); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher where T and U -// are pointers or references to a derived and a base class, correspondingly. -TEST(SafeMatcherCastTest, FromBaseClass) { - Derived d, d2; - Matcher m1 = Eq(&d); - Matcher m2 = SafeMatcherCast(m1); - EXPECT_TRUE(m2.Matches(&d)); - EXPECT_FALSE(m2.Matches(&d2)); - - Matcher m3 = Ref(d); - Matcher m4 = SafeMatcherCast(m3); - EXPECT_TRUE(m4.Matches(d)); - EXPECT_FALSE(m4.Matches(d2)); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromConstReferenceToReference) { - int n = 0; - Matcher m1 = Ref(n); - Matcher m2 = SafeMatcherCast(m1); - int n1 = 0; - EXPECT_TRUE(m2.Matches(n)); - EXPECT_FALSE(m2.Matches(n1)); -} - -// Tests that MatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { - Matcher m1 = Eq(0); - Matcher m2 = SafeMatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromNonReferenceToReference) { - Matcher m1 = Eq(0); - Matcher m2 = SafeMatcherCast(m1); - int n = 0; - EXPECT_TRUE(m2.Matches(n)); - n = 1; - EXPECT_FALSE(m2.Matches(n)); -} - -// Tests that SafeMatcherCast(m) works when m is a Matcher. -TEST(SafeMatcherCastTest, FromSameType) { - Matcher m1 = Eq(0); - Matcher m2 = SafeMatcherCast(m1); - EXPECT_TRUE(m2.Matches(0)); - EXPECT_FALSE(m2.Matches(1)); -} - -#if !defined _MSC_VER - -namespace convertible_from_any { -TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { - Matcher m = SafeMatcherCast(1); - EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); - EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); -} - -TEST(SafeMatcherCastTest, FromConvertibleFromAny) { - Matcher m = - SafeMatcherCast(Eq(ConvertibleFromAny(1))); - EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); - EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); -} -} // namespace convertible_from_any - -#endif // !defined _MSC_VER - -TEST(SafeMatcherCastTest, ValueIsNotCopied) { - int n = 42; - Matcher m = SafeMatcherCast(n); - // Verify that the matcher holds a reference to n, not to its temporary copy. - EXPECT_TRUE(m.Matches(n)); -} - -TEST(ExpectThat, TakesLiterals) { - EXPECT_THAT(1, 1); - EXPECT_THAT(1.0, 1.0); - EXPECT_THAT(std::string(), ""); -} - -TEST(ExpectThat, TakesFunctions) { - struct Helper { - static void Func() {} - }; - void (*func)() = Helper::Func; - EXPECT_THAT(func, Helper::Func); - EXPECT_THAT(func, &Helper::Func); -} - -// Tests that A() matches any value of type T. -TEST(ATest, MatchesAnyValue) { - // Tests a matcher for a value type. - Matcher m1 = A(); - EXPECT_TRUE(m1.Matches(91.43)); - EXPECT_TRUE(m1.Matches(-15.32)); - - // Tests a matcher for a reference type. - int a = 2; - int b = -6; - Matcher m2 = A(); - EXPECT_TRUE(m2.Matches(a)); - EXPECT_TRUE(m2.Matches(b)); -} - -TEST(ATest, WorksForDerivedClass) { - Base base; - Derived derived; - EXPECT_THAT(&base, A()); - // This shouldn't compile: EXPECT_THAT(&base, A()); - EXPECT_THAT(&derived, A()); - EXPECT_THAT(&derived, A()); -} - -// Tests that A() describes itself properly. -TEST(ATest, CanDescribeSelf) { - EXPECT_EQ("is anything", Describe(A())); -} - -// Tests that An() matches any value of type T. -TEST(AnTest, MatchesAnyValue) { - // Tests a matcher for a value type. - Matcher m1 = An(); - EXPECT_TRUE(m1.Matches(9143)); - EXPECT_TRUE(m1.Matches(-1532)); - - // Tests a matcher for a reference type. - int a = 2; - int b = -6; - Matcher m2 = An(); - EXPECT_TRUE(m2.Matches(a)); - EXPECT_TRUE(m2.Matches(b)); -} - -// Tests that An() describes itself properly. -TEST(AnTest, CanDescribeSelf) { - EXPECT_EQ("is anything", Describe(An())); -} - -// Tests that _ can be used as a matcher for any type and matches any -// value of that type. -TEST(UnderscoreTest, MatchesAnyValue) { - // Uses _ as a matcher for a value type. - Matcher m1 = _; - EXPECT_TRUE(m1.Matches(123)); - EXPECT_TRUE(m1.Matches(-242)); - - // Uses _ as a matcher for a reference type. - bool a = false; - const bool b = true; - Matcher m2 = _; - EXPECT_TRUE(m2.Matches(a)); - EXPECT_TRUE(m2.Matches(b)); -} - -// Tests that _ describes itself properly. -TEST(UnderscoreTest, CanDescribeSelf) { - Matcher m = _; - EXPECT_EQ("is anything", Describe(m)); -} - -// Tests that Eq(x) matches any value equal to x. -TEST(EqTest, MatchesEqualValue) { - // 2 C-strings with same content but different addresses. - const char a1[] = "hi"; - const char a2[] = "hi"; - - Matcher m1 = Eq(a1); - EXPECT_TRUE(m1.Matches(a1)); - EXPECT_FALSE(m1.Matches(a2)); -} - -// Tests that Eq(v) describes itself properly. - -class Unprintable { - public: - Unprintable() : c_('a') {} - - bool operator==(const Unprintable& /* rhs */) const { return true; } - // -Wunused-private-field: dummy accessor for `c_`. - char dummy_c() { return c_; } - private: - char c_; -}; - -TEST(EqTest, CanDescribeSelf) { - Matcher m = Eq(Unprintable()); - EXPECT_EQ("is equal to 1-byte object <61>", Describe(m)); -} - -// Tests that Eq(v) can be used to match any type that supports -// comparing with type T, where T is v's type. -TEST(EqTest, IsPolymorphic) { - Matcher m1 = Eq(1); - EXPECT_TRUE(m1.Matches(1)); - EXPECT_FALSE(m1.Matches(2)); - - Matcher m2 = Eq(1); - EXPECT_TRUE(m2.Matches('\1')); - EXPECT_FALSE(m2.Matches('a')); -} - -// Tests that TypedEq(v) matches values of type T that's equal to v. -TEST(TypedEqTest, ChecksEqualityForGivenType) { - Matcher m1 = TypedEq('a'); - EXPECT_TRUE(m1.Matches('a')); - EXPECT_FALSE(m1.Matches('b')); - - Matcher m2 = TypedEq(6); - EXPECT_TRUE(m2.Matches(6)); - EXPECT_FALSE(m2.Matches(7)); -} - -// Tests that TypedEq(v) describes itself properly. -TEST(TypedEqTest, CanDescribeSelf) { - EXPECT_EQ("is equal to 2", Describe(TypedEq(2))); -} - -// Tests that TypedEq(v) has type Matcher. - -// Type::IsTypeOf(v) compiles if and only if the type of value v is T, where -// T is a "bare" type (i.e. not in the form of const U or U&). If v's type is -// not T, the compiler will generate a message about "undefined reference". -template -struct Type { - static bool IsTypeOf(const T& /* v */) { return true; } - - template - static void IsTypeOf(T2 v); -}; - -TEST(TypedEqTest, HasSpecifiedType) { - // Verfies that the type of TypedEq(v) is Matcher. - Type >::IsTypeOf(TypedEq(5)); - Type >::IsTypeOf(TypedEq(5)); -} - -// Tests that Ge(v) matches anything >= v. -TEST(GeTest, ImplementsGreaterThanOrEqual) { - Matcher m1 = Ge(0); - EXPECT_TRUE(m1.Matches(1)); - EXPECT_TRUE(m1.Matches(0)); - EXPECT_FALSE(m1.Matches(-1)); -} - -// Tests that Ge(v) describes itself properly. -TEST(GeTest, CanDescribeSelf) { - Matcher m = Ge(5); - EXPECT_EQ("is >= 5", Describe(m)); -} - -// Tests that Gt(v) matches anything > v. -TEST(GtTest, ImplementsGreaterThan) { - Matcher m1 = Gt(0); - EXPECT_TRUE(m1.Matches(1.0)); - EXPECT_FALSE(m1.Matches(0.0)); - EXPECT_FALSE(m1.Matches(-1.0)); -} - -// Tests that Gt(v) describes itself properly. -TEST(GtTest, CanDescribeSelf) { - Matcher m = Gt(5); - EXPECT_EQ("is > 5", Describe(m)); -} - -// Tests that Le(v) matches anything <= v. -TEST(LeTest, ImplementsLessThanOrEqual) { - Matcher m1 = Le('b'); - EXPECT_TRUE(m1.Matches('a')); - EXPECT_TRUE(m1.Matches('b')); - EXPECT_FALSE(m1.Matches('c')); -} - -// Tests that Le(v) describes itself properly. -TEST(LeTest, CanDescribeSelf) { - Matcher m = Le(5); - EXPECT_EQ("is <= 5", Describe(m)); -} - -// Tests that Lt(v) matches anything < v. -TEST(LtTest, ImplementsLessThan) { - Matcher m1 = Lt("Hello"); - EXPECT_TRUE(m1.Matches("Abc")); - EXPECT_FALSE(m1.Matches("Hello")); - EXPECT_FALSE(m1.Matches("Hello, world!")); -} - -// Tests that Lt(v) describes itself properly. -TEST(LtTest, CanDescribeSelf) { - Matcher m = Lt(5); - EXPECT_EQ("is < 5", Describe(m)); -} - -// Tests that Ne(v) matches anything != v. -TEST(NeTest, ImplementsNotEqual) { - Matcher m1 = Ne(0); - EXPECT_TRUE(m1.Matches(1)); - EXPECT_TRUE(m1.Matches(-1)); - EXPECT_FALSE(m1.Matches(0)); -} - -// Tests that Ne(v) describes itself properly. -TEST(NeTest, CanDescribeSelf) { - Matcher m = Ne(5); - EXPECT_EQ("isn't equal to 5", Describe(m)); -} - -class MoveOnly { - public: - explicit MoveOnly(int i) : i_(i) {} - MoveOnly(const MoveOnly&) = delete; - MoveOnly(MoveOnly&&) = default; - MoveOnly& operator=(const MoveOnly&) = delete; - MoveOnly& operator=(MoveOnly&&) = default; - - bool operator==(const MoveOnly& other) const { return i_ == other.i_; } - bool operator!=(const MoveOnly& other) const { return i_ != other.i_; } - bool operator<(const MoveOnly& other) const { return i_ < other.i_; } - bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; } - bool operator>(const MoveOnly& other) const { return i_ > other.i_; } - bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; } - - private: - int i_; -}; - -struct MoveHelper { - MOCK_METHOD1(Call, void(MoveOnly)); -}; - -TEST(ComparisonBaseTest, WorksWithMoveOnly) { - MoveOnly m{0}; - MoveHelper helper; - - EXPECT_CALL(helper, Call(Eq(ByRef(m)))); - helper.Call(MoveOnly(0)); - EXPECT_CALL(helper, Call(Ne(ByRef(m)))); - helper.Call(MoveOnly(1)); - EXPECT_CALL(helper, Call(Le(ByRef(m)))); - helper.Call(MoveOnly(0)); - EXPECT_CALL(helper, Call(Lt(ByRef(m)))); - helper.Call(MoveOnly(-1)); - EXPECT_CALL(helper, Call(Ge(ByRef(m)))); - helper.Call(MoveOnly(0)); - EXPECT_CALL(helper, Call(Gt(ByRef(m)))); - helper.Call(MoveOnly(1)); -} - -// Tests that IsNull() matches any NULL pointer of any type. -TEST(IsNullTest, MatchesNullPointer) { - Matcher m1 = IsNull(); - int* p1 = nullptr; - int n = 0; - EXPECT_TRUE(m1.Matches(p1)); - EXPECT_FALSE(m1.Matches(&n)); - - Matcher m2 = IsNull(); - const char* p2 = nullptr; - EXPECT_TRUE(m2.Matches(p2)); - EXPECT_FALSE(m2.Matches("hi")); - - Matcher m3 = IsNull(); - void* p3 = nullptr; - EXPECT_TRUE(m3.Matches(p3)); - EXPECT_FALSE(m3.Matches(reinterpret_cast(0xbeef))); -} - -TEST(IsNullTest, StdFunction) { - const Matcher> m = IsNull(); - - EXPECT_TRUE(m.Matches(std::function())); - EXPECT_FALSE(m.Matches([]{})); -} - -// Tests that IsNull() describes itself properly. -TEST(IsNullTest, CanDescribeSelf) { - Matcher m = IsNull(); - EXPECT_EQ("is NULL", Describe(m)); - EXPECT_EQ("isn't NULL", DescribeNegation(m)); -} - -// Tests that NotNull() matches any non-NULL pointer of any type. -TEST(NotNullTest, MatchesNonNullPointer) { - Matcher m1 = NotNull(); - int* p1 = nullptr; - int n = 0; - EXPECT_FALSE(m1.Matches(p1)); - EXPECT_TRUE(m1.Matches(&n)); - - Matcher m2 = NotNull(); - const char* p2 = nullptr; - EXPECT_FALSE(m2.Matches(p2)); - EXPECT_TRUE(m2.Matches("hi")); -} - -TEST(NotNullTest, LinkedPtr) { - const Matcher> m = NotNull(); - const std::shared_ptr null_p; - const std::shared_ptr non_null_p(new int); - - EXPECT_FALSE(m.Matches(null_p)); - EXPECT_TRUE(m.Matches(non_null_p)); -} - -TEST(NotNullTest, ReferenceToConstLinkedPtr) { - const Matcher&> m = NotNull(); - const std::shared_ptr null_p; - const std::shared_ptr non_null_p(new double); - - EXPECT_FALSE(m.Matches(null_p)); - EXPECT_TRUE(m.Matches(non_null_p)); -} - -TEST(NotNullTest, StdFunction) { - const Matcher> m = NotNull(); - - EXPECT_TRUE(m.Matches([]{})); - EXPECT_FALSE(m.Matches(std::function())); -} - -// Tests that NotNull() describes itself properly. -TEST(NotNullTest, CanDescribeSelf) { - Matcher m = NotNull(); - EXPECT_EQ("isn't NULL", Describe(m)); -} - -// Tests that Ref(variable) matches an argument that references -// 'variable'. -TEST(RefTest, MatchesSameVariable) { - int a = 0; - int b = 0; - Matcher m = Ref(a); - EXPECT_TRUE(m.Matches(a)); - EXPECT_FALSE(m.Matches(b)); -} - -// Tests that Ref(variable) describes itself properly. -TEST(RefTest, CanDescribeSelf) { - int n = 5; - Matcher m = Ref(n); - stringstream ss; - ss << "references the variable @" << &n << " 5"; - EXPECT_EQ(ss.str(), Describe(m)); -} - -// Test that Ref(non_const_varialbe) can be used as a matcher for a -// const reference. -TEST(RefTest, CanBeUsedAsMatcherForConstReference) { - int a = 0; - int b = 0; - Matcher m = Ref(a); - EXPECT_TRUE(m.Matches(a)); - EXPECT_FALSE(m.Matches(b)); -} - -// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be -// used wherever Ref(base) can be used (Ref(derived) is a sub-type -// of Ref(base), but not vice versa. - -TEST(RefTest, IsCovariant) { - Base base, base2; - Derived derived; - Matcher m1 = Ref(base); - EXPECT_TRUE(m1.Matches(base)); - EXPECT_FALSE(m1.Matches(base2)); - EXPECT_FALSE(m1.Matches(derived)); - - m1 = Ref(derived); - EXPECT_TRUE(m1.Matches(derived)); - EXPECT_FALSE(m1.Matches(base)); - EXPECT_FALSE(m1.Matches(base2)); -} - -TEST(RefTest, ExplainsResult) { - int n = 0; - EXPECT_THAT(Explain(Matcher(Ref(n)), n), - StartsWith("which is located @")); - - int m = 0; - EXPECT_THAT(Explain(Matcher(Ref(n)), m), - StartsWith("which is located @")); -} - -// Tests string comparison matchers. - -TEST(StrEqTest, MatchesEqualString) { - Matcher m = StrEq(std::string("Hello")); - EXPECT_TRUE(m.Matches("Hello")); - EXPECT_FALSE(m.Matches("hello")); - EXPECT_FALSE(m.Matches(nullptr)); - - Matcher m2 = StrEq("Hello"); - EXPECT_TRUE(m2.Matches("Hello")); - EXPECT_FALSE(m2.Matches("Hi")); - -#if GTEST_HAS_ABSL - Matcher m3 = StrEq("Hello"); - EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); - EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); - EXPECT_FALSE(m3.Matches(absl::string_view())); - - Matcher m_empty = StrEq(""); - EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); - EXPECT_TRUE(m_empty.Matches(absl::string_view())); - EXPECT_FALSE(m_empty.Matches(absl::string_view("hello"))); -#endif // GTEST_HAS_ABSL -} - -TEST(StrEqTest, CanDescribeSelf) { - Matcher m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3"); - EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"", - Describe(m)); - - std::string str("01204500800"); - str[3] = '\0'; - Matcher m2 = StrEq(str); - EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2)); - str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; - Matcher m3 = StrEq(str); - EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3)); -} - -TEST(StrNeTest, MatchesUnequalString) { - Matcher m = StrNe("Hello"); - EXPECT_TRUE(m.Matches("")); - EXPECT_TRUE(m.Matches(nullptr)); - EXPECT_FALSE(m.Matches("Hello")); - - Matcher m2 = StrNe(std::string("Hello")); - EXPECT_TRUE(m2.Matches("hello")); - EXPECT_FALSE(m2.Matches("Hello")); - -#if GTEST_HAS_ABSL - Matcher m3 = StrNe("Hello"); - EXPECT_TRUE(m3.Matches(absl::string_view(""))); - EXPECT_TRUE(m3.Matches(absl::string_view())); - EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); -#endif // GTEST_HAS_ABSL -} - -TEST(StrNeTest, CanDescribeSelf) { - Matcher m = StrNe("Hi"); - EXPECT_EQ("isn't equal to \"Hi\"", Describe(m)); -} - -TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { - Matcher m = StrCaseEq(std::string("Hello")); - EXPECT_TRUE(m.Matches("Hello")); - EXPECT_TRUE(m.Matches("hello")); - EXPECT_FALSE(m.Matches("Hi")); - EXPECT_FALSE(m.Matches(nullptr)); - - Matcher m2 = StrCaseEq("Hello"); - EXPECT_TRUE(m2.Matches("hello")); - EXPECT_FALSE(m2.Matches("Hi")); - -#if GTEST_HAS_ABSL - Matcher m3 = StrCaseEq(std::string("Hello")); - EXPECT_TRUE(m3.Matches(absl::string_view("Hello"))); - EXPECT_TRUE(m3.Matches(absl::string_view("hello"))); - EXPECT_FALSE(m3.Matches(absl::string_view("Hi"))); - EXPECT_FALSE(m3.Matches(absl::string_view())); -#endif // GTEST_HAS_ABSL -} - -TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { - std::string str1("oabocdooeoo"); - std::string str2("OABOCDOOEOO"); - Matcher m0 = StrCaseEq(str1); - EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); - - str1[3] = str2[3] = '\0'; - Matcher m1 = StrCaseEq(str1); - EXPECT_TRUE(m1.Matches(str2)); - - str1[0] = str1[6] = str1[7] = str1[10] = '\0'; - str2[0] = str2[6] = str2[7] = str2[10] = '\0'; - Matcher m2 = StrCaseEq(str1); - str1[9] = str2[9] = '\0'; - EXPECT_FALSE(m2.Matches(str2)); - - Matcher m3 = StrCaseEq(str1); - EXPECT_TRUE(m3.Matches(str2)); - - EXPECT_FALSE(m3.Matches(str2 + "x")); - str2.append(1, '\0'); - EXPECT_FALSE(m3.Matches(str2)); - EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9))); -} - -TEST(StrCaseEqTest, CanDescribeSelf) { - Matcher m = StrCaseEq("Hi"); - EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m)); -} - -TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { - Matcher m = StrCaseNe("Hello"); - EXPECT_TRUE(m.Matches("Hi")); - EXPECT_TRUE(m.Matches(nullptr)); - EXPECT_FALSE(m.Matches("Hello")); - EXPECT_FALSE(m.Matches("hello")); - - Matcher m2 = StrCaseNe(std::string("Hello")); - EXPECT_TRUE(m2.Matches("")); - EXPECT_FALSE(m2.Matches("Hello")); - -#if GTEST_HAS_ABSL - Matcher m3 = StrCaseNe("Hello"); - EXPECT_TRUE(m3.Matches(absl::string_view("Hi"))); - EXPECT_TRUE(m3.Matches(absl::string_view())); - EXPECT_FALSE(m3.Matches(absl::string_view("Hello"))); - EXPECT_FALSE(m3.Matches(absl::string_view("hello"))); -#endif // GTEST_HAS_ABSL -} - -TEST(StrCaseNeTest, CanDescribeSelf) { - Matcher m = StrCaseNe("Hi"); - EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m)); -} - -// Tests that HasSubstr() works for matching string-typed values. -TEST(HasSubstrTest, WorksForStringClasses) { - const Matcher m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(std::string("I love food."))); - EXPECT_FALSE(m1.Matches(std::string("tofo"))); - - const Matcher m2 = HasSubstr("foo"); - EXPECT_TRUE(m2.Matches(std::string("I love food."))); - EXPECT_FALSE(m2.Matches(std::string("tofo"))); - - const Matcher m_empty = HasSubstr(""); - EXPECT_TRUE(m_empty.Matches(std::string())); - EXPECT_TRUE(m_empty.Matches(std::string("not empty"))); -} - -// Tests that HasSubstr() works for matching C-string-typed values. -TEST(HasSubstrTest, WorksForCStrings) { - const Matcher m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(const_cast("I love food."))); - EXPECT_FALSE(m1.Matches(const_cast("tofo"))); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = HasSubstr("foo"); - EXPECT_TRUE(m2.Matches("I love food.")); - EXPECT_FALSE(m2.Matches("tofo")); - EXPECT_FALSE(m2.Matches(nullptr)); - - const Matcher m_empty = HasSubstr(""); - EXPECT_TRUE(m_empty.Matches("not empty")); - EXPECT_TRUE(m_empty.Matches("")); - EXPECT_FALSE(m_empty.Matches(nullptr)); -} - -#if GTEST_HAS_ABSL -// Tests that HasSubstr() works for matching absl::string_view-typed values. -TEST(HasSubstrTest, WorksForStringViewClasses) { - const Matcher m1 = HasSubstr("foo"); - EXPECT_TRUE(m1.Matches(absl::string_view("I love food."))); - EXPECT_FALSE(m1.Matches(absl::string_view("tofo"))); - EXPECT_FALSE(m1.Matches(absl::string_view())); - - const Matcher m2 = HasSubstr("foo"); - EXPECT_TRUE(m2.Matches(absl::string_view("I love food."))); - EXPECT_FALSE(m2.Matches(absl::string_view("tofo"))); - EXPECT_FALSE(m2.Matches(absl::string_view())); - - const Matcher m3 = HasSubstr(""); - EXPECT_TRUE(m3.Matches(absl::string_view("foo"))); - EXPECT_TRUE(m3.Matches(absl::string_view(""))); - EXPECT_TRUE(m3.Matches(absl::string_view())); -} -#endif // GTEST_HAS_ABSL - -// Tests that HasSubstr(s) describes itself properly. -TEST(HasSubstrTest, CanDescribeSelf) { - Matcher m = HasSubstr("foo\n\""); - EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m)); -} - -TEST(KeyTest, CanDescribeSelf) { - Matcher&> m = Key("foo"); - EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m)); - EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m)); -} - -TEST(KeyTest, ExplainsResult) { - Matcher > m = Key(GreaterThan(10)); - EXPECT_EQ("whose first field is a value which is 5 less than 10", - Explain(m, make_pair(5, true))); - EXPECT_EQ("whose first field is a value which is 5 more than 10", - Explain(m, make_pair(15, true))); -} - -TEST(KeyTest, MatchesCorrectly) { - pair p(25, "foo"); - EXPECT_THAT(p, Key(25)); - EXPECT_THAT(p, Not(Key(42))); - EXPECT_THAT(p, Key(Ge(20))); - EXPECT_THAT(p, Not(Key(Lt(25)))); -} - -TEST(KeyTest, WorksWithMoveOnly) { - pair, std::unique_ptr> p; - EXPECT_THAT(p, Key(Eq(nullptr))); -} - -template -struct Tag {}; - -struct PairWithGet { - int member_1; - std::string member_2; - using first_type = int; - using second_type = std::string; - - const int& GetImpl(Tag<0>) const { return member_1; } - const std::string& GetImpl(Tag<1>) const { return member_2; } -}; -template -auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag())) { - return value.GetImpl(Tag()); -} -TEST(PairTest, MatchesPairWithGetCorrectly) { - PairWithGet p{25, "foo"}; - EXPECT_THAT(p, Key(25)); - EXPECT_THAT(p, Not(Key(42))); - EXPECT_THAT(p, Key(Ge(20))); - EXPECT_THAT(p, Not(Key(Lt(25)))); - - std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; - EXPECT_THAT(v, Contains(Key(29))); -} - -TEST(KeyTest, SafelyCastsInnerMatcher) { - Matcher is_positive = Gt(0); - Matcher is_negative = Lt(0); - pair p('a', true); - EXPECT_THAT(p, Key(is_positive)); - EXPECT_THAT(p, Not(Key(is_negative))); -} - -TEST(KeyTest, InsideContainsUsingMap) { - map container; - container.insert(make_pair(1, 'a')); - container.insert(make_pair(2, 'b')); - container.insert(make_pair(4, 'c')); - EXPECT_THAT(container, Contains(Key(1))); - EXPECT_THAT(container, Not(Contains(Key(3)))); -} - -TEST(KeyTest, InsideContainsUsingMultimap) { - multimap container; - container.insert(make_pair(1, 'a')); - container.insert(make_pair(2, 'b')); - container.insert(make_pair(4, 'c')); - - EXPECT_THAT(container, Not(Contains(Key(25)))); - container.insert(make_pair(25, 'd')); - EXPECT_THAT(container, Contains(Key(25))); - container.insert(make_pair(25, 'e')); - EXPECT_THAT(container, Contains(Key(25))); - - EXPECT_THAT(container, Contains(Key(1))); - EXPECT_THAT(container, Not(Contains(Key(3)))); -} - -TEST(PairTest, Typing) { - // Test verifies the following type conversions can be compiled. - Matcher&> m1 = Pair("foo", 42); - Matcher > m2 = Pair("foo", 42); - Matcher > m3 = Pair("foo", 42); - - Matcher > m4 = Pair(25, "42"); - Matcher > m5 = Pair("25", 42); -} - -TEST(PairTest, CanDescribeSelf) { - Matcher&> m1 = Pair("foo", 42); - EXPECT_EQ("has a first field that is equal to \"foo\"" - ", and has a second field that is equal to 42", - Describe(m1)); - EXPECT_EQ("has a first field that isn't equal to \"foo\"" - ", or has a second field that isn't equal to 42", - DescribeNegation(m1)); - // Double and triple negation (1 or 2 times not and description of negation). - Matcher&> m2 = Not(Pair(Not(13), 42)); - EXPECT_EQ("has a first field that isn't equal to 13" - ", and has a second field that is equal to 42", - DescribeNegation(m2)); -} - -TEST(PairTest, CanExplainMatchResultTo) { - // If neither field matches, Pair() should explain about the first - // field. - const Matcher > m = Pair(GreaterThan(0), GreaterThan(0)); - EXPECT_EQ("whose first field does not match, which is 1 less than 0", - Explain(m, make_pair(-1, -2))); - - // If the first field matches but the second doesn't, Pair() should - // explain about the second field. - EXPECT_EQ("whose second field does not match, which is 2 less than 0", - Explain(m, make_pair(1, -2))); - - // If the first field doesn't match but the second does, Pair() - // should explain about the first field. - EXPECT_EQ("whose first field does not match, which is 1 less than 0", - Explain(m, make_pair(-1, 2))); - - // If both fields match, Pair() should explain about them both. - EXPECT_EQ("whose both fields match, where the first field is a value " - "which is 1 more than 0, and the second field is a value " - "which is 2 more than 0", - Explain(m, make_pair(1, 2))); - - // If only the first match has an explanation, only this explanation should - // be printed. - const Matcher > explain_first = Pair(GreaterThan(0), 0); - EXPECT_EQ("whose both fields match, where the first field is a value " - "which is 1 more than 0", - Explain(explain_first, make_pair(1, 0))); - - // If only the second match has an explanation, only this explanation should - // be printed. - const Matcher > explain_second = Pair(0, GreaterThan(0)); - EXPECT_EQ("whose both fields match, where the second field is a value " - "which is 1 more than 0", - Explain(explain_second, make_pair(0, 1))); -} - -TEST(PairTest, MatchesCorrectly) { - pair p(25, "foo"); - - // Both fields match. - EXPECT_THAT(p, Pair(25, "foo")); - EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o"))); - - // 'first' doesnt' match, but 'second' matches. - EXPECT_THAT(p, Not(Pair(42, "foo"))); - EXPECT_THAT(p, Not(Pair(Lt(25), "foo"))); - - // 'first' matches, but 'second' doesn't match. - EXPECT_THAT(p, Not(Pair(25, "bar"))); - EXPECT_THAT(p, Not(Pair(25, Not("foo")))); - - // Neither field matches. - EXPECT_THAT(p, Not(Pair(13, "bar"))); - EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a")))); -} - -TEST(PairTest, WorksWithMoveOnly) { - pair, std::unique_ptr> p; - p.second.reset(new int(7)); - EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr))); -} - -TEST(PairTest, SafelyCastsInnerMatchers) { - Matcher is_positive = Gt(0); - Matcher is_negative = Lt(0); - pair p('a', true); - EXPECT_THAT(p, Pair(is_positive, _)); - EXPECT_THAT(p, Not(Pair(is_negative, _))); - EXPECT_THAT(p, Pair(_, is_positive)); - EXPECT_THAT(p, Not(Pair(_, is_negative))); -} - -TEST(PairTest, InsideContainsUsingMap) { - map container; - container.insert(make_pair(1, 'a')); - container.insert(make_pair(2, 'b')); - container.insert(make_pair(4, 'c')); - EXPECT_THAT(container, Contains(Pair(1, 'a'))); - EXPECT_THAT(container, Contains(Pair(1, _))); - EXPECT_THAT(container, Contains(Pair(_, 'a'))); - EXPECT_THAT(container, Not(Contains(Pair(3, _)))); -} - -TEST(ContainsTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(Contains(Pointee(2)))); - helper.Call(MakeUniquePtrs({1, 2})); -} - -TEST(PairTest, UseGetInsteadOfMembers) { - PairWithGet pair{7, "ABC"}; - EXPECT_THAT(pair, Pair(7, "ABC")); - EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB"))); - EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC"))); - - std::vector v = {{11, "Foo"}, {29, "gMockIsBestMock"}}; - EXPECT_THAT(v, - ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not("")))); -} - -// Tests StartsWith(s). - -TEST(StartsWithTest, MatchesStringWithGivenPrefix) { - const Matcher m1 = StartsWith(std::string("")); - EXPECT_TRUE(m1.Matches("Hi")); - EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = StartsWith("Hi"); - EXPECT_TRUE(m2.Matches("Hi")); - EXPECT_TRUE(m2.Matches("Hi Hi!")); - EXPECT_TRUE(m2.Matches("High")); - EXPECT_FALSE(m2.Matches("H")); - EXPECT_FALSE(m2.Matches(" Hi")); - -#if GTEST_HAS_ABSL - const Matcher m_empty = StartsWith(""); - EXPECT_TRUE(m_empty.Matches(absl::string_view())); - EXPECT_TRUE(m_empty.Matches(absl::string_view(""))); - EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty"))); -#endif // GTEST_HAS_ABSL -} - -TEST(StartsWithTest, CanDescribeSelf) { - Matcher m = StartsWith("Hi"); - EXPECT_EQ("starts with \"Hi\"", Describe(m)); -} - -// Tests EndsWith(s). - -TEST(EndsWithTest, MatchesStringWithGivenSuffix) { - const Matcher m1 = EndsWith(""); - EXPECT_TRUE(m1.Matches("Hi")); - EXPECT_TRUE(m1.Matches("")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = EndsWith(std::string("Hi")); - EXPECT_TRUE(m2.Matches("Hi")); - EXPECT_TRUE(m2.Matches("Wow Hi Hi")); - EXPECT_TRUE(m2.Matches("Super Hi")); - EXPECT_FALSE(m2.Matches("i")); - EXPECT_FALSE(m2.Matches("Hi ")); - -#if GTEST_HAS_ABSL - const Matcher m4 = EndsWith(""); - EXPECT_TRUE(m4.Matches("Hi")); - EXPECT_TRUE(m4.Matches("")); - EXPECT_TRUE(m4.Matches(absl::string_view())); - EXPECT_TRUE(m4.Matches(absl::string_view(""))); -#endif // GTEST_HAS_ABSL -} - -TEST(EndsWithTest, CanDescribeSelf) { - Matcher m = EndsWith("Hi"); - EXPECT_EQ("ends with \"Hi\"", Describe(m)); -} - -// Tests MatchesRegex(). - -TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { - const Matcher m1 = MatchesRegex("a.*z"); - EXPECT_TRUE(m1.Matches("az")); - EXPECT_TRUE(m1.Matches("abcz")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = MatchesRegex(new RE("a.*z")); - EXPECT_TRUE(m2.Matches("azbz")); - EXPECT_FALSE(m2.Matches("az1")); - EXPECT_FALSE(m2.Matches("1az")); - -#if GTEST_HAS_ABSL - const Matcher m3 = MatchesRegex("a.*z"); - EXPECT_TRUE(m3.Matches(absl::string_view("az"))); - EXPECT_TRUE(m3.Matches(absl::string_view("abcz"))); - EXPECT_FALSE(m3.Matches(absl::string_view("1az"))); - EXPECT_FALSE(m3.Matches(absl::string_view())); - const Matcher m4 = MatchesRegex(""); - EXPECT_TRUE(m4.Matches(absl::string_view(""))); - EXPECT_TRUE(m4.Matches(absl::string_view())); -#endif // GTEST_HAS_ABSL -} - -TEST(MatchesRegexTest, CanDescribeSelf) { - Matcher m1 = MatchesRegex(std::string("Hi.*")); - EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1)); - - Matcher m2 = MatchesRegex(new RE("a.*")); - EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2)); - -#if GTEST_HAS_ABSL - Matcher m3 = MatchesRegex(new RE("0.*")); - EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3)); -#endif // GTEST_HAS_ABSL -} - -// Tests ContainsRegex(). - -TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { - const Matcher m1 = ContainsRegex(std::string("a.*z")); - EXPECT_TRUE(m1.Matches("az")); - EXPECT_TRUE(m1.Matches("0abcz1")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = ContainsRegex(new RE("a.*z")); - EXPECT_TRUE(m2.Matches("azbz")); - EXPECT_TRUE(m2.Matches("az1")); - EXPECT_FALSE(m2.Matches("1a")); - -#if GTEST_HAS_ABSL - const Matcher m3 = ContainsRegex(new RE("a.*z")); - EXPECT_TRUE(m3.Matches(absl::string_view("azbz"))); - EXPECT_TRUE(m3.Matches(absl::string_view("az1"))); - EXPECT_FALSE(m3.Matches(absl::string_view("1a"))); - EXPECT_FALSE(m3.Matches(absl::string_view())); - const Matcher m4 = ContainsRegex(""); - EXPECT_TRUE(m4.Matches(absl::string_view(""))); - EXPECT_TRUE(m4.Matches(absl::string_view())); -#endif // GTEST_HAS_ABSL -} - -TEST(ContainsRegexTest, CanDescribeSelf) { - Matcher m1 = ContainsRegex("Hi.*"); - EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1)); - - Matcher m2 = ContainsRegex(new RE("a.*")); - EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2)); - -#if GTEST_HAS_ABSL - Matcher m3 = ContainsRegex(new RE("0.*")); - EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3)); -#endif // GTEST_HAS_ABSL -} - -// Tests for wide strings. -#if GTEST_HAS_STD_WSTRING -TEST(StdWideStrEqTest, MatchesEqual) { - Matcher m = StrEq(::std::wstring(L"Hello")); - EXPECT_TRUE(m.Matches(L"Hello")); - EXPECT_FALSE(m.Matches(L"hello")); - EXPECT_FALSE(m.Matches(nullptr)); - - Matcher m2 = StrEq(L"Hello"); - EXPECT_TRUE(m2.Matches(L"Hello")); - EXPECT_FALSE(m2.Matches(L"Hi")); - - Matcher m3 = StrEq(L"\xD3\x576\x8D3\xC74D"); - EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D")); - EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E")); - - ::std::wstring str(L"01204500800"); - str[3] = L'\0'; - Matcher m4 = StrEq(str); - EXPECT_TRUE(m4.Matches(str)); - str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; - Matcher m5 = StrEq(str); - EXPECT_TRUE(m5.Matches(str)); -} - -TEST(StdWideStrEqTest, CanDescribeSelf) { - Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v"); - EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"", - Describe(m)); - - Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D"); - EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"", - Describe(m2)); - - ::std::wstring str(L"01204500800"); - str[3] = L'\0'; - Matcher m4 = StrEq(str); - EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4)); - str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; - Matcher m5 = StrEq(str); - EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5)); -} - -TEST(StdWideStrNeTest, MatchesUnequalString) { - Matcher m = StrNe(L"Hello"); - EXPECT_TRUE(m.Matches(L"")); - EXPECT_TRUE(m.Matches(nullptr)); - EXPECT_FALSE(m.Matches(L"Hello")); - - Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello")); - EXPECT_TRUE(m2.Matches(L"hello")); - EXPECT_FALSE(m2.Matches(L"Hello")); -} - -TEST(StdWideStrNeTest, CanDescribeSelf) { - Matcher m = StrNe(L"Hi"); - EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m)); -} - -TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { - Matcher m = StrCaseEq(::std::wstring(L"Hello")); - EXPECT_TRUE(m.Matches(L"Hello")); - EXPECT_TRUE(m.Matches(L"hello")); - EXPECT_FALSE(m.Matches(L"Hi")); - EXPECT_FALSE(m.Matches(nullptr)); - - Matcher m2 = StrCaseEq(L"Hello"); - EXPECT_TRUE(m2.Matches(L"hello")); - EXPECT_FALSE(m2.Matches(L"Hi")); -} - -TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { - ::std::wstring str1(L"oabocdooeoo"); - ::std::wstring str2(L"OABOCDOOEOO"); - Matcher m0 = StrCaseEq(str1); - EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0'))); - - str1[3] = str2[3] = L'\0'; - Matcher m1 = StrCaseEq(str1); - EXPECT_TRUE(m1.Matches(str2)); - - str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; - str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; - Matcher m2 = StrCaseEq(str1); - str1[9] = str2[9] = L'\0'; - EXPECT_FALSE(m2.Matches(str2)); - - Matcher m3 = StrCaseEq(str1); - EXPECT_TRUE(m3.Matches(str2)); - - EXPECT_FALSE(m3.Matches(str2 + L"x")); - str2.append(1, L'\0'); - EXPECT_FALSE(m3.Matches(str2)); - EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9))); -} - -TEST(StdWideStrCaseEqTest, CanDescribeSelf) { - Matcher< ::std::wstring> m = StrCaseEq(L"Hi"); - EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m)); -} - -TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { - Matcher m = StrCaseNe(L"Hello"); - EXPECT_TRUE(m.Matches(L"Hi")); - EXPECT_TRUE(m.Matches(nullptr)); - EXPECT_FALSE(m.Matches(L"Hello")); - EXPECT_FALSE(m.Matches(L"hello")); - - Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello")); - EXPECT_TRUE(m2.Matches(L"")); - EXPECT_FALSE(m2.Matches(L"Hello")); -} - -TEST(StdWideStrCaseNeTest, CanDescribeSelf) { - Matcher m = StrCaseNe(L"Hi"); - EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m)); -} - -// Tests that HasSubstr() works for matching wstring-typed values. -TEST(StdWideHasSubstrTest, WorksForStringClasses) { - const Matcher< ::std::wstring> m1 = HasSubstr(L"foo"); - EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food."))); - EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo"))); - - const Matcher m2 = HasSubstr(L"foo"); - EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food."))); - EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo"))); -} - -// Tests that HasSubstr() works for matching C-wide-string-typed values. -TEST(StdWideHasSubstrTest, WorksForCStrings) { - const Matcher m1 = HasSubstr(L"foo"); - EXPECT_TRUE(m1.Matches(const_cast(L"I love food."))); - EXPECT_FALSE(m1.Matches(const_cast(L"tofo"))); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = HasSubstr(L"foo"); - EXPECT_TRUE(m2.Matches(L"I love food.")); - EXPECT_FALSE(m2.Matches(L"tofo")); - EXPECT_FALSE(m2.Matches(nullptr)); -} - -// Tests that HasSubstr(s) describes itself properly. -TEST(StdWideHasSubstrTest, CanDescribeSelf) { - Matcher< ::std::wstring> m = HasSubstr(L"foo\n\""); - EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m)); -} - -// Tests StartsWith(s). - -TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) { - const Matcher m1 = StartsWith(::std::wstring(L"")); - EXPECT_TRUE(m1.Matches(L"Hi")); - EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = StartsWith(L"Hi"); - EXPECT_TRUE(m2.Matches(L"Hi")); - EXPECT_TRUE(m2.Matches(L"Hi Hi!")); - EXPECT_TRUE(m2.Matches(L"High")); - EXPECT_FALSE(m2.Matches(L"H")); - EXPECT_FALSE(m2.Matches(L" Hi")); -} - -TEST(StdWideStartsWithTest, CanDescribeSelf) { - Matcher m = StartsWith(L"Hi"); - EXPECT_EQ("starts with L\"Hi\"", Describe(m)); -} - -// Tests EndsWith(s). - -TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { - const Matcher m1 = EndsWith(L""); - EXPECT_TRUE(m1.Matches(L"Hi")); - EXPECT_TRUE(m1.Matches(L"")); - EXPECT_FALSE(m1.Matches(nullptr)); - - const Matcher m2 = EndsWith(::std::wstring(L"Hi")); - EXPECT_TRUE(m2.Matches(L"Hi")); - EXPECT_TRUE(m2.Matches(L"Wow Hi Hi")); - EXPECT_TRUE(m2.Matches(L"Super Hi")); - EXPECT_FALSE(m2.Matches(L"i")); - EXPECT_FALSE(m2.Matches(L"Hi ")); -} - -TEST(StdWideEndsWithTest, CanDescribeSelf) { - Matcher m = EndsWith(L"Hi"); - EXPECT_EQ("ends with L\"Hi\"", Describe(m)); -} - -#endif // GTEST_HAS_STD_WSTRING - -typedef ::std::tuple Tuple2; // NOLINT - -// Tests that Eq() matches a 2-tuple where the first field == the -// second field. -TEST(Eq2Test, MatchesEqualArguments) { - Matcher m = Eq(); - EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); -} - -// Tests that Eq() describes itself properly. -TEST(Eq2Test, CanDescribeSelf) { - Matcher m = Eq(); - EXPECT_EQ("are an equal pair", Describe(m)); -} - -// Tests that Ge() matches a 2-tuple where the first field >= the -// second field. -TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) { - Matcher m = Ge(); - EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); - EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); -} - -// Tests that Ge() describes itself properly. -TEST(Ge2Test, CanDescribeSelf) { - Matcher m = Ge(); - EXPECT_EQ("are a pair where the first >= the second", Describe(m)); -} - -// Tests that Gt() matches a 2-tuple where the first field > the -// second field. -TEST(Gt2Test, MatchesGreaterThanArguments) { - Matcher m = Gt(); - EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); -} - -// Tests that Gt() describes itself properly. -TEST(Gt2Test, CanDescribeSelf) { - Matcher m = Gt(); - EXPECT_EQ("are a pair where the first > the second", Describe(m)); -} - -// Tests that Le() matches a 2-tuple where the first field <= the -// second field. -TEST(Le2Test, MatchesLessThanOrEqualArguments) { - Matcher m = Le(); - EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); - EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); -} - -// Tests that Le() describes itself properly. -TEST(Le2Test, CanDescribeSelf) { - Matcher m = Le(); - EXPECT_EQ("are a pair where the first <= the second", Describe(m)); -} - -// Tests that Lt() matches a 2-tuple where the first field < the -// second field. -TEST(Lt2Test, MatchesLessThanArguments) { - Matcher m = Lt(); - EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); -} - -// Tests that Lt() describes itself properly. -TEST(Lt2Test, CanDescribeSelf) { - Matcher m = Lt(); - EXPECT_EQ("are a pair where the first < the second", Describe(m)); -} - -// Tests that Ne() matches a 2-tuple where the first field != the -// second field. -TEST(Ne2Test, MatchesUnequalArguments) { - Matcher m = Ne(); - EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); - EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); - EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); -} - -// Tests that Ne() describes itself properly. -TEST(Ne2Test, CanDescribeSelf) { - Matcher m = Ne(); - EXPECT_EQ("are an unequal pair", Describe(m)); -} - -TEST(PairMatchBaseTest, WorksWithMoveOnly) { - using Pointers = std::tuple, std::unique_ptr>; - Matcher matcher = Eq(); - Pointers pointers; - // Tested values don't matter; the point is that matcher does not copy the - // matched values. - EXPECT_TRUE(matcher.Matches(pointers)); -} - -// Tests that IsNan() matches a NaN, with float. -TEST(IsNan, FloatMatchesNan) { - float quiet_nan = std::numeric_limits::quiet_NaN(); - float other_nan = std::nanf("1"); - float real_value = 1.0f; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher m_ref = IsNan(); - EXPECT_TRUE(m_ref.Matches(quiet_nan)); - EXPECT_TRUE(m_ref.Matches(other_nan)); - EXPECT_FALSE(m_ref.Matches(real_value)); - - Matcher m_cref = IsNan(); - EXPECT_TRUE(m_cref.Matches(quiet_nan)); - EXPECT_TRUE(m_cref.Matches(other_nan)); - EXPECT_FALSE(m_cref.Matches(real_value)); -} - -// Tests that IsNan() matches a NaN, with double. -TEST(IsNan, DoubleMatchesNan) { - double quiet_nan = std::numeric_limits::quiet_NaN(); - double other_nan = std::nan("1"); - double real_value = 1.0; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher m_ref = IsNan(); - EXPECT_TRUE(m_ref.Matches(quiet_nan)); - EXPECT_TRUE(m_ref.Matches(other_nan)); - EXPECT_FALSE(m_ref.Matches(real_value)); - - Matcher m_cref = IsNan(); - EXPECT_TRUE(m_cref.Matches(quiet_nan)); - EXPECT_TRUE(m_cref.Matches(other_nan)); - EXPECT_FALSE(m_cref.Matches(real_value)); -} - -// Tests that IsNan() matches a NaN, with long double. -TEST(IsNan, LongDoubleMatchesNan) { - long double quiet_nan = std::numeric_limits::quiet_NaN(); - long double other_nan = std::nan("1"); - long double real_value = 1.0; - - Matcher m = IsNan(); - EXPECT_TRUE(m.Matches(quiet_nan)); - EXPECT_TRUE(m.Matches(other_nan)); - EXPECT_FALSE(m.Matches(real_value)); - - Matcher m_ref = IsNan(); - EXPECT_TRUE(m_ref.Matches(quiet_nan)); - EXPECT_TRUE(m_ref.Matches(other_nan)); - EXPECT_FALSE(m_ref.Matches(real_value)); - - Matcher m_cref = IsNan(); - EXPECT_TRUE(m_cref.Matches(quiet_nan)); - EXPECT_TRUE(m_cref.Matches(other_nan)); - EXPECT_FALSE(m_cref.Matches(real_value)); -} - -// Tests that IsNan() works with Not. -TEST(IsNan, NotMatchesNan) { - Matcher mf = Not(IsNan()); - EXPECT_FALSE(mf.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(mf.Matches(std::nanf("1"))); - EXPECT_TRUE(mf.Matches(1.0)); - - Matcher md = Not(IsNan()); - EXPECT_FALSE(md.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(md.Matches(std::nan("1"))); - EXPECT_TRUE(md.Matches(1.0)); - - Matcher mld = Not(IsNan()); - EXPECT_FALSE(mld.Matches(std::numeric_limits::quiet_NaN())); - EXPECT_FALSE(mld.Matches(std::nanl("1"))); - EXPECT_TRUE(mld.Matches(1.0)); -} - -// Tests that IsNan() can describe itself. -TEST(IsNan, CanDescribeSelf) { - Matcher mf = IsNan(); - EXPECT_EQ("is NaN", Describe(mf)); - - Matcher md = IsNan(); - EXPECT_EQ("is NaN", Describe(md)); - - Matcher mld = IsNan(); - EXPECT_EQ("is NaN", Describe(mld)); -} - -// Tests that IsNan() can describe itself with Not. -TEST(IsNan, CanDescribeSelfWithNot) { - Matcher mf = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(mf)); - - Matcher md = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(md)); - - Matcher mld = Not(IsNan()); - EXPECT_EQ("isn't NaN", Describe(mld)); -} - -// Tests that FloatEq() matches a 2-tuple where -// FloatEq(first field) matches the second field. -TEST(FloatEq2Test, MatchesEqualArguments) { - typedef ::std::tuple Tpl; - Matcher m = FloatEq(); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f))); - EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); -} - -// Tests that FloatEq() describes itself properly. -TEST(FloatEq2Test, CanDescribeSelf) { - Matcher&> m = FloatEq(); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that NanSensitiveFloatEq() matches a 2-tuple where -// NanSensitiveFloatEq(first field) matches the second field. -TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) { - typedef ::std::tuple Tpl; - Matcher m = NanSensitiveFloatEq(); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that NanSensitiveFloatEq() describes itself properly. -TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { - Matcher&> m = NanSensitiveFloatEq(); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that DoubleEq() matches a 2-tuple where -// DoubleEq(first field) matches the second field. -TEST(DoubleEq2Test, MatchesEqualArguments) { - typedef ::std::tuple Tpl; - Matcher m = DoubleEq(); - EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); - EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1))); - EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0))); -} - -// Tests that DoubleEq() describes itself properly. -TEST(DoubleEq2Test, CanDescribeSelf) { - Matcher&> m = DoubleEq(); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that NanSensitiveDoubleEq() matches a 2-tuple where -// NanSensitiveDoubleEq(first field) matches the second field. -TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) { - typedef ::std::tuple Tpl; - Matcher m = NanSensitiveDoubleEq(); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that DoubleEq() describes itself properly. -TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { - Matcher&> m = NanSensitiveDoubleEq(); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that FloatEq() matches a 2-tuple where -// FloatNear(first field, max_abs_error) matches the second field. -TEST(FloatNear2Test, MatchesEqualArguments) { - typedef ::std::tuple Tpl; - Matcher m = FloatNear(0.5f); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f))); -} - -// Tests that FloatNear() describes itself properly. -TEST(FloatNear2Test, CanDescribeSelf) { - Matcher&> m = FloatNear(0.5f); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that NanSensitiveFloatNear() matches a 2-tuple where -// NanSensitiveFloatNear(first field) matches the second field. -TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) { - typedef ::std::tuple Tpl; - Matcher m = NanSensitiveFloatNear(0.5f); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that NanSensitiveFloatNear() describes itself properly. -TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { - Matcher&> m = NanSensitiveFloatNear(0.5f); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that FloatEq() matches a 2-tuple where -// DoubleNear(first field, max_abs_error) matches the second field. -TEST(DoubleNear2Test, MatchesEqualArguments) { - typedef ::std::tuple Tpl; - Matcher m = DoubleNear(0.5); - EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); - EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0))); - EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0))); -} - -// Tests that DoubleNear() describes itself properly. -TEST(DoubleNear2Test, CanDescribeSelf) { - Matcher&> m = DoubleNear(0.5); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that NanSensitiveDoubleNear() matches a 2-tuple where -// NanSensitiveDoubleNear(first field) matches the second field. -TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) { - typedef ::std::tuple Tpl; - Matcher m = NanSensitiveDoubleNear(0.5f); - EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); - EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), - std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); - EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits::quiet_NaN()))); - EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits::quiet_NaN(), 1.0f))); -} - -// Tests that NanSensitiveDoubleNear() describes itself properly. -TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { - Matcher&> m = NanSensitiveDoubleNear(0.5f); - EXPECT_EQ("are an almost-equal pair", Describe(m)); -} - -// Tests that Not(m) matches any value that doesn't match m. -TEST(NotTest, NegatesMatcher) { - Matcher m; - m = Not(Eq(2)); - EXPECT_TRUE(m.Matches(3)); - EXPECT_FALSE(m.Matches(2)); -} - -// Tests that Not(m) describes itself properly. -TEST(NotTest, CanDescribeSelf) { - Matcher m = Not(Eq(5)); - EXPECT_EQ("isn't equal to 5", Describe(m)); -} - -// Tests that monomorphic matchers are safely cast by the Not matcher. -TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) { - // greater_than_5 is a monomorphic matcher. - Matcher greater_than_5 = Gt(5); - - Matcher m = Not(greater_than_5); - Matcher m2 = Not(greater_than_5); - Matcher m3 = Not(m); -} - -// Helper to allow easy testing of AllOf matchers with num parameters. -void AllOfMatches(int num, const Matcher& m) { - SCOPED_TRACE(Describe(m)); - EXPECT_TRUE(m.Matches(0)); - for (int i = 1; i <= num; ++i) { - EXPECT_FALSE(m.Matches(i)); - } - EXPECT_TRUE(m.Matches(num + 1)); -} - -// Tests that AllOf(m1, ..., mn) matches any value that matches all of -// the given matchers. -TEST(AllOfTest, MatchesWhenAllMatch) { - Matcher m; - m = AllOf(Le(2), Ge(1)); - EXPECT_TRUE(m.Matches(1)); - EXPECT_TRUE(m.Matches(2)); - EXPECT_FALSE(m.Matches(0)); - EXPECT_FALSE(m.Matches(3)); - - m = AllOf(Gt(0), Ne(1), Ne(2)); - EXPECT_TRUE(m.Matches(3)); - EXPECT_FALSE(m.Matches(2)); - EXPECT_FALSE(m.Matches(1)); - EXPECT_FALSE(m.Matches(0)); - - m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); - EXPECT_TRUE(m.Matches(4)); - EXPECT_FALSE(m.Matches(3)); - EXPECT_FALSE(m.Matches(2)); - EXPECT_FALSE(m.Matches(1)); - EXPECT_FALSE(m.Matches(0)); - - m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); - EXPECT_TRUE(m.Matches(0)); - EXPECT_TRUE(m.Matches(1)); - EXPECT_FALSE(m.Matches(3)); - - // The following tests for varying number of sub-matchers. Due to the way - // the sub-matchers are handled it is enough to test every sub-matcher once - // with sub-matchers using the same matcher type. Varying matcher types are - // checked for above. - AllOfMatches(2, AllOf(Ne(1), Ne(2))); - AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3))); - AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4))); - AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5))); - AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6))); - AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7))); - AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), - Ne(8))); - AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), - Ne(8), Ne(9))); - AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), - Ne(9), Ne(10))); - AllOfMatches( - 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), - Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17), - Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25), - Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33), - Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), - Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), - Ne(50))); -} - - -// Tests that AllOf(m1, ..., mn) describes itself properly. -TEST(AllOfTest, CanDescribeSelf) { - Matcher m; - m = AllOf(Le(2), Ge(1)); - EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m)); - - m = AllOf(Gt(0), Ne(1), Ne(2)); - std::string expected_descr1 = - "(is > 0) and (isn't equal to 1) and (isn't equal to 2)"; - EXPECT_EQ(expected_descr1, Describe(m)); - - m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); - std::string expected_descr2 = - "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal " - "to 3)"; - EXPECT_EQ(expected_descr2, Describe(m)); - - m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); - std::string expected_descr3 = - "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) " - "and (isn't equal to 7)"; - EXPECT_EQ(expected_descr3, Describe(m)); -} - -// Tests that AllOf(m1, ..., mn) describes its negation properly. -TEST(AllOfTest, CanDescribeNegation) { - Matcher m; - m = AllOf(Le(2), Ge(1)); - std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)"; - EXPECT_EQ(expected_descr4, DescribeNegation(m)); - - m = AllOf(Gt(0), Ne(1), Ne(2)); - std::string expected_descr5 = - "(isn't > 0) or (is equal to 1) or (is equal to 2)"; - EXPECT_EQ(expected_descr5, DescribeNegation(m)); - - m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); - std::string expected_descr6 = - "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)"; - EXPECT_EQ(expected_descr6, DescribeNegation(m)); - - m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); - std::string expected_desr7 = - "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or " - "(is equal to 7)"; - EXPECT_EQ(expected_desr7, DescribeNegation(m)); - - m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), - Ne(10), Ne(11)); - AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)")); - AllOfMatches(11, m); -} - -// Tests that monomorphic matchers are safely cast by the AllOf matcher. -TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) { - // greater_than_5 and less_than_10 are monomorphic matchers. - Matcher greater_than_5 = Gt(5); - Matcher less_than_10 = Lt(10); - - Matcher m = AllOf(greater_than_5, less_than_10); - Matcher m2 = AllOf(greater_than_5, less_than_10); - Matcher m3 = AllOf(greater_than_5, m2); - - // Tests that BothOf works when composing itself. - Matcher m4 = AllOf(greater_than_5, less_than_10, less_than_10); - Matcher m5 = AllOf(greater_than_5, less_than_10, less_than_10); -} - -TEST(AllOfTest, ExplainsResult) { - Matcher m; - - // Successful match. Both matchers need to explain. The second - // matcher doesn't give an explanation, so only the first matcher's - // explanation is printed. - m = AllOf(GreaterThan(10), Lt(30)); - EXPECT_EQ("which is 15 more than 10", Explain(m, 25)); - - // Successful match. Both matchers need to explain. - m = AllOf(GreaterThan(10), GreaterThan(20)); - EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20", - Explain(m, 30)); - - // Successful match. All matchers need to explain. The second - // matcher doesn't given an explanation. - m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20)); - EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20", - Explain(m, 25)); - - // Successful match. All matchers need to explain. - m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); - EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, " - "and which is 10 more than 30", - Explain(m, 40)); - - // Failed match. The first matcher, which failed, needs to - // explain. - m = AllOf(GreaterThan(10), GreaterThan(20)); - EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); - - // Failed match. The second matcher, which failed, needs to - // explain. Since it doesn't given an explanation, nothing is - // printed. - m = AllOf(GreaterThan(10), Lt(30)); - EXPECT_EQ("", Explain(m, 40)); - - // Failed match. The second matcher, which failed, needs to - // explain. - m = AllOf(GreaterThan(10), GreaterThan(20)); - EXPECT_EQ("which is 5 less than 20", Explain(m, 15)); -} - -// Helper to allow easy testing of AnyOf matchers with num parameters. -static void AnyOfMatches(int num, const Matcher& m) { - SCOPED_TRACE(Describe(m)); - EXPECT_FALSE(m.Matches(0)); - for (int i = 1; i <= num; ++i) { - EXPECT_TRUE(m.Matches(i)); - } - EXPECT_FALSE(m.Matches(num + 1)); -} - -static void AnyOfStringMatches(int num, const Matcher& m) { - SCOPED_TRACE(Describe(m)); - EXPECT_FALSE(m.Matches(std::to_string(0))); - - for (int i = 1; i <= num; ++i) { - EXPECT_TRUE(m.Matches(std::to_string(i))); - } - EXPECT_FALSE(m.Matches(std::to_string(num + 1))); -} - -// Tests that AnyOf(m1, ..., mn) matches any value that matches at -// least one of the given matchers. -TEST(AnyOfTest, MatchesWhenAnyMatches) { - Matcher m; - m = AnyOf(Le(1), Ge(3)); - EXPECT_TRUE(m.Matches(1)); - EXPECT_TRUE(m.Matches(4)); - EXPECT_FALSE(m.Matches(2)); - - m = AnyOf(Lt(0), Eq(1), Eq(2)); - EXPECT_TRUE(m.Matches(-1)); - EXPECT_TRUE(m.Matches(1)); - EXPECT_TRUE(m.Matches(2)); - EXPECT_FALSE(m.Matches(0)); - - m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); - EXPECT_TRUE(m.Matches(-1)); - EXPECT_TRUE(m.Matches(1)); - EXPECT_TRUE(m.Matches(2)); - EXPECT_TRUE(m.Matches(3)); - EXPECT_FALSE(m.Matches(0)); - - m = AnyOf(Le(0), Gt(10), 3, 5, 7); - EXPECT_TRUE(m.Matches(0)); - EXPECT_TRUE(m.Matches(11)); - EXPECT_TRUE(m.Matches(3)); - EXPECT_FALSE(m.Matches(2)); - - // The following tests for varying number of sub-matchers. Due to the way - // the sub-matchers are handled it is enough to test every sub-matcher once - // with sub-matchers using the same matcher type. Varying matcher types are - // checked for above. - AnyOfMatches(2, AnyOf(1, 2)); - AnyOfMatches(3, AnyOf(1, 2, 3)); - AnyOfMatches(4, AnyOf(1, 2, 3, 4)); - AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5)); - AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6)); - AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7)); - AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8)); - AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9)); - AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); -} - -// Tests the variadic version of the AnyOfMatcher. -TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { - // Also make sure AnyOf is defined in the right namespace and does not depend - // on ADL. - Matcher m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); - - EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)")); - AnyOfMatches(11, m); - AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); - AnyOfStringMatches( - 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", - "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", - "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", - "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", - "43", "44", "45", "46", "47", "48", "49", "50")); -} - -// Tests the variadic version of the ElementsAreMatcher -TEST(ElementsAreTest, HugeMatcher) { - vector test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; - - EXPECT_THAT(test_vector, - ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), - Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); -} - -// Tests the variadic version of the UnorderedElementsAreMatcher -TEST(ElementsAreTest, HugeMatcherStr) { - vector test_vector{ - "literal_string", "", "", "", "", "", "", "", "", "", "", ""}; - - EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _, - _, _, _, _, _, _)); -} - -// Tests the variadic version of the UnorderedElementsAreMatcher -TEST(ElementsAreTest, HugeMatcherUnordered) { - vector test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; - - EXPECT_THAT(test_vector, UnorderedElementsAre( - Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), - Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); -} - - -// Tests that AnyOf(m1, ..., mn) describes itself properly. -TEST(AnyOfTest, CanDescribeSelf) { - Matcher m; - m = AnyOf(Le(1), Ge(3)); - - EXPECT_EQ("(is <= 1) or (is >= 3)", - Describe(m)); - - m = AnyOf(Lt(0), Eq(1), Eq(2)); - EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m)); - - m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); - EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)", - Describe(m)); - - m = AnyOf(Le(0), Gt(10), 3, 5, 7); - EXPECT_EQ( - "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is " - "equal to 7)", - Describe(m)); -} - -// Tests that AnyOf(m1, ..., mn) describes its negation properly. -TEST(AnyOfTest, CanDescribeNegation) { - Matcher m; - m = AnyOf(Le(1), Ge(3)); - EXPECT_EQ("(isn't <= 1) and (isn't >= 3)", - DescribeNegation(m)); - - m = AnyOf(Lt(0), Eq(1), Eq(2)); - EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)", - DescribeNegation(m)); - - m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); - EXPECT_EQ( - "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't " - "equal to 3)", - DescribeNegation(m)); - - m = AnyOf(Le(0), Gt(10), 3, 5, 7); - EXPECT_EQ( - "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal " - "to 5) and (isn't equal to 7)", - DescribeNegation(m)); -} - -// Tests that monomorphic matchers are safely cast by the AnyOf matcher. -TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) { - // greater_than_5 and less_than_10 are monomorphic matchers. - Matcher greater_than_5 = Gt(5); - Matcher less_than_10 = Lt(10); - - Matcher m = AnyOf(greater_than_5, less_than_10); - Matcher m2 = AnyOf(greater_than_5, less_than_10); - Matcher m3 = AnyOf(greater_than_5, m2); - - // Tests that EitherOf works when composing itself. - Matcher m4 = AnyOf(greater_than_5, less_than_10, less_than_10); - Matcher m5 = AnyOf(greater_than_5, less_than_10, less_than_10); -} - -TEST(AnyOfTest, ExplainsResult) { - Matcher m; - - // Failed match. Both matchers need to explain. The second - // matcher doesn't give an explanation, so only the first matcher's - // explanation is printed. - m = AnyOf(GreaterThan(10), Lt(0)); - EXPECT_EQ("which is 5 less than 10", Explain(m, 5)); - - // Failed match. Both matchers need to explain. - m = AnyOf(GreaterThan(10), GreaterThan(20)); - EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20", - Explain(m, 5)); - - // Failed match. All matchers need to explain. The second - // matcher doesn't given an explanation. - m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30)); - EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30", - Explain(m, 5)); - - // Failed match. All matchers need to explain. - m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); - EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, " - "and which is 25 less than 30", - Explain(m, 5)); - - // Successful match. The first matcher, which succeeded, needs to - // explain. - m = AnyOf(GreaterThan(10), GreaterThan(20)); - EXPECT_EQ("which is 5 more than 10", Explain(m, 15)); - - // Successful match. The second matcher, which succeeded, needs to - // explain. Since it doesn't given an explanation, nothing is - // printed. - m = AnyOf(GreaterThan(10), Lt(30)); - EXPECT_EQ("", Explain(m, 0)); - - // Successful match. The second matcher, which succeeded, needs to - // explain. - m = AnyOf(GreaterThan(30), GreaterThan(20)); - EXPECT_EQ("which is 5 more than 20", Explain(m, 25)); -} - -// The following predicate function and predicate functor are for -// testing the Truly(predicate) matcher. - -// Returns non-zero if the input is positive. Note that the return -// type of this function is not bool. It's OK as Truly() accepts any -// unary function or functor whose return type can be implicitly -// converted to bool. -int IsPositive(double x) { - return x > 0 ? 1 : 0; -} - -// This functor returns true if the input is greater than the given -// number. -class IsGreaterThan { - public: - explicit IsGreaterThan(int threshold) : threshold_(threshold) {} - - bool operator()(int n) const { return n > threshold_; } - - private: - int threshold_; -}; - -// For testing Truly(). -const int foo = 0; - -// This predicate returns true if and only if the argument references foo and -// has a zero value. -bool ReferencesFooAndIsZero(const int& n) { - return (&n == &foo) && (n == 0); -} - -// Tests that Truly(predicate) matches what satisfies the given -// predicate. -TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) { - Matcher m = Truly(IsPositive); - EXPECT_TRUE(m.Matches(2.0)); - EXPECT_FALSE(m.Matches(-1.5)); -} - -// Tests that Truly(predicate_functor) works too. -TEST(TrulyTest, CanBeUsedWithFunctor) { - Matcher m = Truly(IsGreaterThan(5)); - EXPECT_TRUE(m.Matches(6)); - EXPECT_FALSE(m.Matches(4)); -} - -// A class that can be implicitly converted to bool. -class ConvertibleToBool { - public: - explicit ConvertibleToBool(int number) : number_(number) {} - operator bool() const { return number_ != 0; } - - private: - int number_; -}; - -ConvertibleToBool IsNotZero(int number) { - return ConvertibleToBool(number); -} - -// Tests that the predicate used in Truly() may return a class that's -// implicitly convertible to bool, even when the class has no -// operator!(). -TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) { - Matcher m = Truly(IsNotZero); - EXPECT_TRUE(m.Matches(1)); - EXPECT_FALSE(m.Matches(0)); -} - -// Tests that Truly(predicate) can describe itself properly. -TEST(TrulyTest, CanDescribeSelf) { - Matcher m = Truly(IsPositive); - EXPECT_EQ("satisfies the given predicate", - Describe(m)); -} - -// Tests that Truly(predicate) works when the matcher takes its -// argument by reference. -TEST(TrulyTest, WorksForByRefArguments) { - Matcher m = Truly(ReferencesFooAndIsZero); - EXPECT_TRUE(m.Matches(foo)); - int n = 0; - EXPECT_FALSE(m.Matches(n)); -} - -// Tests that Matches(m) is a predicate satisfied by whatever that -// matches matcher m. -TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) { - EXPECT_TRUE(Matches(Ge(0))(1)); - EXPECT_FALSE(Matches(Eq('a'))('b')); -} - -// Tests that Matches(m) works when the matcher takes its argument by -// reference. -TEST(MatchesTest, WorksOnByRefArguments) { - int m = 0, n = 0; - EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n)); - EXPECT_FALSE(Matches(Ref(m))(n)); -} - -// Tests that a Matcher on non-reference type can be used in -// Matches(). -TEST(MatchesTest, WorksWithMatcherOnNonRefType) { - Matcher eq5 = Eq(5); - EXPECT_TRUE(Matches(eq5)(5)); - EXPECT_FALSE(Matches(eq5)(2)); -} - -// Tests Value(value, matcher). Since Value() is a simple wrapper for -// Matches(), which has been tested already, we don't spend a lot of -// effort on testing Value(). -TEST(ValueTest, WorksWithPolymorphicMatcher) { - EXPECT_TRUE(Value("hi", StartsWith("h"))); - EXPECT_FALSE(Value(5, Gt(10))); -} - -TEST(ValueTest, WorksWithMonomorphicMatcher) { - const Matcher is_zero = Eq(0); - EXPECT_TRUE(Value(0, is_zero)); - EXPECT_FALSE(Value('a', is_zero)); - - int n = 0; - const Matcher ref_n = Ref(n); - EXPECT_TRUE(Value(n, ref_n)); - EXPECT_FALSE(Value(1, ref_n)); -} - -TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) { - StringMatchResultListener listener1; - EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1)); - EXPECT_EQ("% 2 == 0", listener1.str()); - - StringMatchResultListener listener2; - EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2)); - EXPECT_EQ("", listener2.str()); -} - -TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) { - const Matcher is_even = PolymorphicIsEven(); - StringMatchResultListener listener1; - EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1)); - EXPECT_EQ("% 2 == 0", listener1.str()); - - const Matcher is_zero = Eq(0); - StringMatchResultListener listener2; - EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2)); - EXPECT_EQ("", listener2.str()); -} - -MATCHER_P(Really, inner_matcher, "") { - return ExplainMatchResult(inner_matcher, arg, result_listener); -} - -TEST(ExplainMatchResultTest, WorksInsideMATCHER) { - EXPECT_THAT(0, Really(Eq(0))); -} - -TEST(DescribeMatcherTest, WorksWithValue) { - EXPECT_EQ("is equal to 42", DescribeMatcher(42)); - EXPECT_EQ("isn't equal to 42", DescribeMatcher(42, true)); -} - -TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { - const Matcher monomorphic = Le(0); - EXPECT_EQ("is <= 0", DescribeMatcher(monomorphic)); - EXPECT_EQ("isn't <= 0", DescribeMatcher(monomorphic, true)); -} - -TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { - EXPECT_EQ("is even", DescribeMatcher(PolymorphicIsEven())); - EXPECT_EQ("is odd", DescribeMatcher(PolymorphicIsEven(), true)); -} - -TEST(AllArgsTest, WorksForTuple) { - EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt())); - EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt()))); -} - -TEST(AllArgsTest, WorksForNonTuple) { - EXPECT_THAT(42, AllArgs(Gt(0))); - EXPECT_THAT('a', Not(AllArgs(Eq('b')))); -} - -class AllArgsHelper { - public: - AllArgsHelper() {} - - MOCK_METHOD2(Helper, int(char x, int y)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper); -}; - -TEST(AllArgsTest, WorksInWithClause) { - AllArgsHelper helper; - ON_CALL(helper, Helper(_, _)) - .With(AllArgs(Lt())) - .WillByDefault(Return(1)); - EXPECT_CALL(helper, Helper(_, _)); - EXPECT_CALL(helper, Helper(_, _)) - .With(AllArgs(Gt())) - .WillOnce(Return(2)); - - EXPECT_EQ(1, helper.Helper('\1', 2)); - EXPECT_EQ(2, helper.Helper('a', 1)); -} - -class OptionalMatchersHelper { - public: - OptionalMatchersHelper() {} - - MOCK_METHOD0(NoArgs, int()); - - MOCK_METHOD1(OneArg, int(int y)); - - MOCK_METHOD2(TwoArgs, int(char x, int y)); - - MOCK_METHOD1(Overloaded, int(char x)); - MOCK_METHOD2(Overloaded, int(char x, int y)); - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); -}; - -TEST(AllArgsTest, WorksWithoutMatchers) { - OptionalMatchersHelper helper; - - ON_CALL(helper, NoArgs).WillByDefault(Return(10)); - ON_CALL(helper, OneArg).WillByDefault(Return(20)); - ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); - - EXPECT_EQ(10, helper.NoArgs()); - EXPECT_EQ(20, helper.OneArg(1)); - EXPECT_EQ(30, helper.TwoArgs('\1', 2)); - - EXPECT_CALL(helper, NoArgs).Times(1); - EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); - EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); - EXPECT_CALL(helper, TwoArgs).Times(0); - - EXPECT_EQ(10, helper.NoArgs()); - EXPECT_EQ(100, helper.OneArg(1)); - EXPECT_EQ(200, helper.OneArg(17)); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value -// matches the matcher. -TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { - ASSERT_THAT(5, Ge(2)) << "This should succeed."; - ASSERT_THAT("Foo", EndsWith("oo")); - EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too."; - EXPECT_THAT("Hello", StartsWith("Hell")); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value -// doesn't match the matcher. -TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { - // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(), - // which cannot reference auto variables. - static unsigned short n; // NOLINT - n = 5; - - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)), - "Value of: n\n" - "Expected: is > 10\n" - " Actual: 5" + OfType("unsigned short")); - n = 0; - EXPECT_NONFATAL_FAILURE( - EXPECT_THAT(n, AllOf(Le(7), Ge(5))), - "Value of: n\n" - "Expected: (is <= 7) and (is >= 5)\n" - " Actual: 0" + OfType("unsigned short")); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument -// has a reference type. -TEST(MatcherAssertionTest, WorksForByRefArguments) { - // We use a static variable here as EXPECT_FATAL_FAILURE() cannot - // reference auto variables. - static int n; - n = 0; - EXPECT_THAT(n, AllOf(Le(7), Ref(n))); - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), - "Value of: n\n" - "Expected: does not reference the variable @"); - // Tests the "Actual" part. - EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))), - "Actual: 0" + OfType("int") + ", which is located @"); -} - -// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is -// monomorphic. -TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { - Matcher starts_with_he = StartsWith("he"); - ASSERT_THAT("hello", starts_with_he); - - Matcher ends_with_ok = EndsWith("ok"); - ASSERT_THAT("book", ends_with_ok); - const std::string bad = "bad"; - EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), - "Value of: bad\n" - "Expected: ends with \"ok\"\n" - " Actual: \"bad\""); - Matcher is_greater_than_5 = Gt(5); - EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5), - "Value of: 5\n" - "Expected: is > 5\n" - " Actual: 5" + OfType("int")); -} - -// Tests floating-point matchers. -template -class FloatingPointTest : public testing::Test { - protected: - typedef testing::internal::FloatingPoint Floating; - typedef typename Floating::Bits Bits; - - FloatingPointTest() - : max_ulps_(Floating::kMaxUlps), - zero_bits_(Floating(0).bits()), - one_bits_(Floating(1).bits()), - infinity_bits_(Floating(Floating::Infinity()).bits()), - close_to_positive_zero_( - Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), - close_to_negative_zero_( - -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), - further_from_negative_zero_(-Floating::ReinterpretBits( - zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), - close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), - further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), - infinity_(Floating::Infinity()), - close_to_infinity_( - Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), - further_from_infinity_( - Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), - max_(Floating::Max()), - nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), - nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { - } - - void TestSize() { - EXPECT_EQ(sizeof(RawType), sizeof(Bits)); - } - - // A battery of tests for FloatingEqMatcher::Matches. - // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. - void TestMatches( - testing::internal::FloatingEqMatcher (*matcher_maker)(RawType)) { - Matcher m1 = matcher_maker(0.0); - EXPECT_TRUE(m1.Matches(-0.0)); - EXPECT_TRUE(m1.Matches(close_to_positive_zero_)); - EXPECT_TRUE(m1.Matches(close_to_negative_zero_)); - EXPECT_FALSE(m1.Matches(1.0)); - - Matcher m2 = matcher_maker(close_to_positive_zero_); - EXPECT_FALSE(m2.Matches(further_from_negative_zero_)); - - Matcher m3 = matcher_maker(1.0); - EXPECT_TRUE(m3.Matches(close_to_one_)); - EXPECT_FALSE(m3.Matches(further_from_one_)); - - // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above. - EXPECT_FALSE(m3.Matches(0.0)); - - Matcher m4 = matcher_maker(-infinity_); - EXPECT_TRUE(m4.Matches(-close_to_infinity_)); - - Matcher m5 = matcher_maker(infinity_); - EXPECT_TRUE(m5.Matches(close_to_infinity_)); - - // This is interesting as the representations of infinity_ and nan1_ - // are only 1 DLP apart. - EXPECT_FALSE(m5.Matches(nan1_)); - - // matcher_maker can produce a Matcher, which is needed in - // some cases. - Matcher m6 = matcher_maker(0.0); - EXPECT_TRUE(m6.Matches(-0.0)); - EXPECT_TRUE(m6.Matches(close_to_positive_zero_)); - EXPECT_FALSE(m6.Matches(1.0)); - - // matcher_maker can produce a Matcher, which is needed in some - // cases. - Matcher m7 = matcher_maker(0.0); - RawType x = 0.0; - EXPECT_TRUE(m7.Matches(x)); - x = 0.01f; - EXPECT_FALSE(m7.Matches(x)); - } - - // Pre-calculated numbers to be used by the tests. - - const Bits max_ulps_; - - const Bits zero_bits_; // The bits that represent 0.0. - const Bits one_bits_; // The bits that represent 1.0. - const Bits infinity_bits_; // The bits that represent +infinity. - - // Some numbers close to 0.0. - const RawType close_to_positive_zero_; - const RawType close_to_negative_zero_; - const RawType further_from_negative_zero_; - - // Some numbers close to 1.0. - const RawType close_to_one_; - const RawType further_from_one_; - - // Some numbers close to +infinity. - const RawType infinity_; - const RawType close_to_infinity_; - const RawType further_from_infinity_; - - // Maximum representable value that's not infinity. - const RawType max_; - - // Some NaNs. - const RawType nan1_; - const RawType nan2_; -}; - -// Tests floating-point matchers with fixed epsilons. -template -class FloatingPointNearTest : public FloatingPointTest { - protected: - typedef FloatingPointTest ParentType; - - // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon. - // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. - void TestNearMatches( - testing::internal::FloatingEqMatcher - (*matcher_maker)(RawType, RawType)) { - Matcher m1 = matcher_maker(0.0, 0.0); - EXPECT_TRUE(m1.Matches(0.0)); - EXPECT_TRUE(m1.Matches(-0.0)); - EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_)); - EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_)); - EXPECT_FALSE(m1.Matches(1.0)); - - Matcher m2 = matcher_maker(0.0, 1.0); - EXPECT_TRUE(m2.Matches(0.0)); - EXPECT_TRUE(m2.Matches(-0.0)); - EXPECT_TRUE(m2.Matches(1.0)); - EXPECT_TRUE(m2.Matches(-1.0)); - EXPECT_FALSE(m2.Matches(ParentType::close_to_one_)); - EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_)); - - // Check that inf matches inf, regardless of the of the specified max - // absolute error. - Matcher m3 = matcher_maker(ParentType::infinity_, 0.0); - EXPECT_TRUE(m3.Matches(ParentType::infinity_)); - EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_)); - EXPECT_FALSE(m3.Matches(-ParentType::infinity_)); - - Matcher m4 = matcher_maker(-ParentType::infinity_, 0.0); - EXPECT_TRUE(m4.Matches(-ParentType::infinity_)); - EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_)); - EXPECT_FALSE(m4.Matches(ParentType::infinity_)); - - // Test various overflow scenarios. - Matcher m5 = matcher_maker(ParentType::max_, ParentType::max_); - EXPECT_TRUE(m5.Matches(ParentType::max_)); - EXPECT_FALSE(m5.Matches(-ParentType::max_)); - - Matcher m6 = matcher_maker(-ParentType::max_, ParentType::max_); - EXPECT_FALSE(m6.Matches(ParentType::max_)); - EXPECT_TRUE(m6.Matches(-ParentType::max_)); - - Matcher m7 = matcher_maker(ParentType::max_, 0); - EXPECT_TRUE(m7.Matches(ParentType::max_)); - EXPECT_FALSE(m7.Matches(-ParentType::max_)); - - Matcher m8 = matcher_maker(-ParentType::max_, 0); - EXPECT_FALSE(m8.Matches(ParentType::max_)); - EXPECT_TRUE(m8.Matches(-ParentType::max_)); - - // The difference between max() and -max() normally overflows to infinity, - // but it should still match if the max_abs_error is also infinity. - Matcher m9 = matcher_maker( - ParentType::max_, ParentType::infinity_); - EXPECT_TRUE(m8.Matches(-ParentType::max_)); - - // matcher_maker can produce a Matcher, which is needed in - // some cases. - Matcher m10 = matcher_maker(0.0, 1.0); - EXPECT_TRUE(m10.Matches(-0.0)); - EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_)); - EXPECT_FALSE(m10.Matches(ParentType::close_to_one_)); - - // matcher_maker can produce a Matcher, which is needed in some - // cases. - Matcher m11 = matcher_maker(0.0, 1.0); - RawType x = 0.0; - EXPECT_TRUE(m11.Matches(x)); - x = 1.0f; - EXPECT_TRUE(m11.Matches(x)); - x = -1.0f; - EXPECT_TRUE(m11.Matches(x)); - x = 1.1f; - EXPECT_FALSE(m11.Matches(x)); - x = -1.1f; - EXPECT_FALSE(m11.Matches(x)); - } -}; - -// Instantiate FloatingPointTest for testing floats. -typedef FloatingPointTest FloatTest; - -TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { - TestMatches(&FloatEq); -} - -TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { - TestMatches(&NanSensitiveFloatEq); -} - -TEST_F(FloatTest, FloatEqCannotMatchNaN) { - // FloatEq never matches NaN. - Matcher m = FloatEq(nan1_); - EXPECT_FALSE(m.Matches(nan1_)); - EXPECT_FALSE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) { - // NanSensitiveFloatEq will match NaN. - Matcher m = NanSensitiveFloatEq(nan1_); - EXPECT_TRUE(m.Matches(nan1_)); - EXPECT_TRUE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(FloatTest, FloatEqCanDescribeSelf) { - Matcher m1 = FloatEq(2.0f); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = FloatEq(0.5f); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher m3 = FloatEq(nan1_); - EXPECT_EQ("never matches", Describe(m3)); - EXPECT_EQ("is anything", DescribeNegation(m3)); -} - -TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { - Matcher m1 = NanSensitiveFloatEq(2.0f); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = NanSensitiveFloatEq(0.5f); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher m3 = NanSensitiveFloatEq(nan1_); - EXPECT_EQ("is NaN", Describe(m3)); - EXPECT_EQ("isn't NaN", DescribeNegation(m3)); -} - -// Instantiate FloatingPointTest for testing floats with a user-specified -// max absolute error. -typedef FloatingPointNearTest FloatNearTest; - -TEST_F(FloatNearTest, FloatNearMatches) { - TestNearMatches(&FloatNear); -} - -TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { - TestNearMatches(&NanSensitiveFloatNear); -} - -TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { - Matcher m1 = FloatNear(2.0f, 0.5f); - EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); - - Matcher m2 = FloatNear(0.5f, 0.5f); - EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); - - Matcher m3 = FloatNear(nan1_, 0.0); - EXPECT_EQ("never matches", Describe(m3)); - EXPECT_EQ("is anything", DescribeNegation(m3)); -} - -TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { - Matcher m1 = NanSensitiveFloatNear(2.0f, 0.5f); - EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); - - Matcher m2 = NanSensitiveFloatNear(0.5f, 0.5f); - EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); - - Matcher m3 = NanSensitiveFloatNear(nan1_, 0.1f); - EXPECT_EQ("is NaN", Describe(m3)); - EXPECT_EQ("isn't NaN", DescribeNegation(m3)); -} - -TEST_F(FloatNearTest, FloatNearCannotMatchNaN) { - // FloatNear never matches NaN. - Matcher m = FloatNear(ParentType::nan1_, 0.1f); - EXPECT_FALSE(m.Matches(nan1_)); - EXPECT_FALSE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) { - // NanSensitiveFloatNear will match NaN. - Matcher m = NanSensitiveFloatNear(nan1_, 0.1f); - EXPECT_TRUE(m.Matches(nan1_)); - EXPECT_TRUE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -// Instantiate FloatingPointTest for testing doubles. -typedef FloatingPointTest DoubleTest; - -TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) { - TestMatches(&DoubleEq); -} - -TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) { - TestMatches(&NanSensitiveDoubleEq); -} - -TEST_F(DoubleTest, DoubleEqCannotMatchNaN) { - // DoubleEq never matches NaN. - Matcher m = DoubleEq(nan1_); - EXPECT_FALSE(m.Matches(nan1_)); - EXPECT_FALSE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) { - // NanSensitiveDoubleEq will match NaN. - Matcher m = NanSensitiveDoubleEq(nan1_); - EXPECT_TRUE(m.Matches(nan1_)); - EXPECT_TRUE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(DoubleTest, DoubleEqCanDescribeSelf) { - Matcher m1 = DoubleEq(2.0); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = DoubleEq(0.5); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher m3 = DoubleEq(nan1_); - EXPECT_EQ("never matches", Describe(m3)); - EXPECT_EQ("is anything", DescribeNegation(m3)); -} - -TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { - Matcher m1 = NanSensitiveDoubleEq(2.0); - EXPECT_EQ("is approximately 2", Describe(m1)); - EXPECT_EQ("isn't approximately 2", DescribeNegation(m1)); - - Matcher m2 = NanSensitiveDoubleEq(0.5); - EXPECT_EQ("is approximately 0.5", Describe(m2)); - EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2)); - - Matcher m3 = NanSensitiveDoubleEq(nan1_); - EXPECT_EQ("is NaN", Describe(m3)); - EXPECT_EQ("isn't NaN", DescribeNegation(m3)); -} - -// Instantiate FloatingPointTest for testing floats with a user-specified -// max absolute error. -typedef FloatingPointNearTest DoubleNearTest; - -TEST_F(DoubleNearTest, DoubleNearMatches) { - TestNearMatches(&DoubleNear); -} - -TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { - TestNearMatches(&NanSensitiveDoubleNear); -} - -TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { - Matcher m1 = DoubleNear(2.0, 0.5); - EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); - - Matcher m2 = DoubleNear(0.5, 0.5); - EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); - - Matcher m3 = DoubleNear(nan1_, 0.0); - EXPECT_EQ("never matches", Describe(m3)); - EXPECT_EQ("is anything", DescribeNegation(m3)); -} - -TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) { - EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05)); - EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2)); - EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7)); - - const std::string explanation = - Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); - // Different C++ implementations may print floating-point numbers - // slightly differently. - EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC - explanation == "which is 1.2e-010 from 2.1") // MSVC - << " where explanation is \"" << explanation << "\"."; -} - -TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) { - Matcher m1 = NanSensitiveDoubleNear(2.0, 0.5); - EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1)); - EXPECT_EQ( - "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1)); - - Matcher m2 = NanSensitiveDoubleNear(0.5, 0.5); - EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2)); - EXPECT_EQ( - "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2)); - - Matcher m3 = NanSensitiveDoubleNear(nan1_, 0.1); - EXPECT_EQ("is NaN", Describe(m3)); - EXPECT_EQ("isn't NaN", DescribeNegation(m3)); -} - -TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) { - // DoubleNear never matches NaN. - Matcher m = DoubleNear(ParentType::nan1_, 0.1); - EXPECT_FALSE(m.Matches(nan1_)); - EXPECT_FALSE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) { - // NanSensitiveDoubleNear will match NaN. - Matcher m = NanSensitiveDoubleNear(nan1_, 0.1); - EXPECT_TRUE(m.Matches(nan1_)); - EXPECT_TRUE(m.Matches(nan2_)); - EXPECT_FALSE(m.Matches(1.0)); -} - -TEST(PointeeTest, RawPointer) { - const Matcher m = Pointee(Ge(0)); - - int n = 1; - EXPECT_TRUE(m.Matches(&n)); - n = -1; - EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(nullptr)); -} - -TEST(PointeeTest, RawPointerToConst) { - const Matcher m = Pointee(Ge(0)); - - double x = 1; - EXPECT_TRUE(m.Matches(&x)); - x = -1; - EXPECT_FALSE(m.Matches(&x)); - EXPECT_FALSE(m.Matches(nullptr)); -} - -TEST(PointeeTest, ReferenceToConstRawPointer) { - const Matcher m = Pointee(Ge(0)); - - int n = 1; - EXPECT_TRUE(m.Matches(&n)); - n = -1; - EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(nullptr)); -} - -TEST(PointeeTest, ReferenceToNonConstRawPointer) { - const Matcher m = Pointee(Ge(0)); - - double x = 1.0; - double* p = &x; - EXPECT_TRUE(m.Matches(p)); - x = -1; - EXPECT_FALSE(m.Matches(p)); - p = nullptr; - EXPECT_FALSE(m.Matches(p)); -} - -MATCHER_P(FieldIIs, inner_matcher, "") { - return ExplainMatchResult(inner_matcher, arg.i, result_listener); -} - -#if GTEST_HAS_RTTI -TEST(WhenDynamicCastToTest, SameType) { - Derived derived; - derived.i = 4; - - // Right type. A pointer is passed down. - Base* as_base_ptr = &derived; - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(Not(IsNull()))); - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(Pointee(FieldIIs(4)))); - EXPECT_THAT(as_base_ptr, - Not(WhenDynamicCastTo(Pointee(FieldIIs(5))))); -} - -TEST(WhenDynamicCastToTest, WrongTypes) { - Base base; - Derived derived; - OtherDerived other_derived; - - // Wrong types. NULL is passed. - EXPECT_THAT(&base, Not(WhenDynamicCastTo(Pointee(_)))); - EXPECT_THAT(&base, WhenDynamicCastTo(IsNull())); - Base* as_base_ptr = &derived; - EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); - as_base_ptr = &other_derived; - EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo(Pointee(_)))); - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); -} - -TEST(WhenDynamicCastToTest, AlreadyNull) { - // Already NULL. - Base* as_base_ptr = nullptr; - EXPECT_THAT(as_base_ptr, WhenDynamicCastTo(IsNull())); -} - -struct AmbiguousCastTypes { - class VirtualDerived : public virtual Base {}; - class DerivedSub1 : public VirtualDerived {}; - class DerivedSub2 : public VirtualDerived {}; - class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {}; -}; - -TEST(WhenDynamicCastToTest, AmbiguousCast) { - AmbiguousCastTypes::DerivedSub1 sub1; - AmbiguousCastTypes::ManyDerivedInHierarchy many_derived; - // Multiply derived from Base. dynamic_cast<> returns NULL. - Base* as_base_ptr = - static_cast(&many_derived); - EXPECT_THAT(as_base_ptr, - WhenDynamicCastTo(IsNull())); - as_base_ptr = &sub1; - EXPECT_THAT( - as_base_ptr, - WhenDynamicCastTo(Not(IsNull()))); -} - -TEST(WhenDynamicCastToTest, Describe) { - Matcher matcher = WhenDynamicCastTo(Pointee(_)); - const std::string prefix = - "when dynamic_cast to " + internal::GetTypeName() + ", "; - EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher)); - EXPECT_EQ(prefix + "does not point to a value that is anything", - DescribeNegation(matcher)); -} - -TEST(WhenDynamicCastToTest, Explain) { - Matcher matcher = WhenDynamicCastTo(Pointee(_)); - Base* null = nullptr; - EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL")); - Derived derived; - EXPECT_TRUE(matcher.Matches(&derived)); - EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to ")); - - // With references, the matcher itself can fail. Test for that one. - Matcher ref_matcher = WhenDynamicCastTo(_); - EXPECT_THAT(Explain(ref_matcher, derived), - HasSubstr("which cannot be dynamic_cast")); -} - -TEST(WhenDynamicCastToTest, GoodReference) { - Derived derived; - derived.i = 4; - Base& as_base_ref = derived; - EXPECT_THAT(as_base_ref, WhenDynamicCastTo(FieldIIs(4))); - EXPECT_THAT(as_base_ref, WhenDynamicCastTo(Not(FieldIIs(5)))); -} - -TEST(WhenDynamicCastToTest, BadReference) { - Derived derived; - Base& as_base_ref = derived; - EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo(_))); -} -#endif // GTEST_HAS_RTTI - -// Minimal const-propagating pointer. -template -class ConstPropagatingPtr { - public: - typedef T element_type; - - ConstPropagatingPtr() : val_() {} - explicit ConstPropagatingPtr(T* t) : val_(t) {} - ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {} - - T* get() { return val_; } - T& operator*() { return *val_; } - // Most smart pointers return non-const T* and T& from the next methods. - const T* get() const { return val_; } - const T& operator*() const { return *val_; } - - private: - T* val_; -}; - -TEST(PointeeTest, WorksWithConstPropagatingPointers) { - const Matcher< ConstPropagatingPtr > m = Pointee(Lt(5)); - int three = 3; - const ConstPropagatingPtr co(&three); - ConstPropagatingPtr o(&three); - EXPECT_TRUE(m.Matches(o)); - EXPECT_TRUE(m.Matches(co)); - *o = 6; - EXPECT_FALSE(m.Matches(o)); - EXPECT_FALSE(m.Matches(ConstPropagatingPtr())); -} - -TEST(PointeeTest, NeverMatchesNull) { - const Matcher m = Pointee(_); - EXPECT_FALSE(m.Matches(nullptr)); -} - -// Tests that we can write Pointee(value) instead of Pointee(Eq(value)). -TEST(PointeeTest, MatchesAgainstAValue) { - const Matcher m = Pointee(5); - - int n = 5; - EXPECT_TRUE(m.Matches(&n)); - n = -1; - EXPECT_FALSE(m.Matches(&n)); - EXPECT_FALSE(m.Matches(nullptr)); -} - -TEST(PointeeTest, CanDescribeSelf) { - const Matcher m = Pointee(Gt(3)); - EXPECT_EQ("points to a value that is > 3", Describe(m)); - EXPECT_EQ("does not point to a value that is > 3", - DescribeNegation(m)); -} - -TEST(PointeeTest, CanExplainMatchResult) { - const Matcher m = Pointee(StartsWith("Hi")); - - EXPECT_EQ("", Explain(m, static_cast(nullptr))); - - const Matcher m2 = Pointee(GreaterThan(1)); // NOLINT - long n = 3; // NOLINT - EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1", - Explain(m2, &n)); -} - -TEST(PointeeTest, AlwaysExplainsPointee) { - const Matcher m = Pointee(0); - int n = 42; - EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n)); -} - -// An uncopyable class. -class Uncopyable { - public: - Uncopyable() : value_(-1) {} - explicit Uncopyable(int a_value) : value_(a_value) {} - - int value() const { return value_; } - void set_value(int i) { value_ = i; } - - private: - int value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable); -}; - -// Returns true if and only if x.value() is positive. -bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } - -MATCHER_P(UncopyableIs, inner_matcher, "") { - return ExplainMatchResult(inner_matcher, arg.value(), result_listener); -} - -// A user-defined struct for testing Field(). -struct AStruct { - AStruct() : x(0), y(1.0), z(5), p(nullptr) {} - AStruct(const AStruct& rhs) - : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} - - int x; // A non-const field. - const double y; // A const field. - Uncopyable z; // An uncopyable field. - const char* p; // A pointer field. - - private: - GTEST_DISALLOW_ASSIGN_(AStruct); -}; - -// A derived struct for testing Field(). -struct DerivedStruct : public AStruct { - char ch; - - private: - GTEST_DISALLOW_ASSIGN_(DerivedStruct); -}; - -// Tests that Field(&Foo::field, ...) works when field is non-const. -TEST(FieldTest, WorksForNonConstField) { - Matcher m = Field(&AStruct::x, Ge(0)); - Matcher m_with_name = Field("x", &AStruct::x, Ge(0)); - - AStruct a; - EXPECT_TRUE(m.Matches(a)); - EXPECT_TRUE(m_with_name.Matches(a)); - a.x = -1; - EXPECT_FALSE(m.Matches(a)); - EXPECT_FALSE(m_with_name.Matches(a)); -} - -// Tests that Field(&Foo::field, ...) works when field is const. -TEST(FieldTest, WorksForConstField) { - AStruct a; - - Matcher m = Field(&AStruct::y, Ge(0.0)); - Matcher m_with_name = Field("y", &AStruct::y, Ge(0.0)); - EXPECT_TRUE(m.Matches(a)); - EXPECT_TRUE(m_with_name.Matches(a)); - m = Field(&AStruct::y, Le(0.0)); - m_with_name = Field("y", &AStruct::y, Le(0.0)); - EXPECT_FALSE(m.Matches(a)); - EXPECT_FALSE(m_with_name.Matches(a)); -} - -// Tests that Field(&Foo::field, ...) works when field is not copyable. -TEST(FieldTest, WorksForUncopyableField) { - AStruct a; - - Matcher m = Field(&AStruct::z, Truly(ValueIsPositive)); - EXPECT_TRUE(m.Matches(a)); - m = Field(&AStruct::z, Not(Truly(ValueIsPositive))); - EXPECT_FALSE(m.Matches(a)); -} - -// Tests that Field(&Foo::field, ...) works when field is a pointer. -TEST(FieldTest, WorksForPointerField) { - // Matching against NULL. - Matcher m = Field(&AStruct::p, static_cast(nullptr)); - AStruct a; - EXPECT_TRUE(m.Matches(a)); - a.p = "hi"; - EXPECT_FALSE(m.Matches(a)); - - // Matching a pointer that is not NULL. - m = Field(&AStruct::p, StartsWith("hi")); - a.p = "hill"; - EXPECT_TRUE(m.Matches(a)); - a.p = "hole"; - EXPECT_FALSE(m.Matches(a)); -} - -// Tests that Field() works when the object is passed by reference. -TEST(FieldTest, WorksForByRefArgument) { - Matcher m = Field(&AStruct::x, Ge(0)); - - AStruct a; - EXPECT_TRUE(m.Matches(a)); - a.x = -1; - EXPECT_FALSE(m.Matches(a)); -} - -// Tests that Field(&Foo::field, ...) works when the argument's type -// is a sub-type of Foo. -TEST(FieldTest, WorksForArgumentOfSubType) { - // Note that the matcher expects DerivedStruct but we say AStruct - // inside Field(). - Matcher m = Field(&AStruct::x, Ge(0)); - - DerivedStruct d; - EXPECT_TRUE(m.Matches(d)); - d.x = -1; - EXPECT_FALSE(m.Matches(d)); -} - -// Tests that Field(&Foo::field, m) works when field's type and m's -// argument type are compatible but not the same. -TEST(FieldTest, WorksForCompatibleMatcherType) { - // The field is an int, but the inner matcher expects a signed char. - Matcher m = Field(&AStruct::x, - Matcher(Ge(0))); - - AStruct a; - EXPECT_TRUE(m.Matches(a)); - a.x = -1; - EXPECT_FALSE(m.Matches(a)); -} - -// Tests that Field() can describe itself. -TEST(FieldTest, CanDescribeSelf) { - Matcher m = Field(&AStruct::x, Ge(0)); - - EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); - EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); -} - -TEST(FieldTest, CanDescribeSelfWithFieldName) { - Matcher m = Field("field_name", &AStruct::x, Ge(0)); - - EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); - EXPECT_EQ("is an object whose field `field_name` isn't >= 0", - DescribeNegation(m)); -} - -// Tests that Field() can explain the match result. -TEST(FieldTest, CanExplainMatchResult) { - Matcher m = Field(&AStruct::x, Ge(0)); - - AStruct a; - a.x = 1; - EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a)); - - m = Field(&AStruct::x, GreaterThan(0)); - EXPECT_EQ( - "whose given field is 1" + OfType("int") + ", which is 1 more than 0", - Explain(m, a)); -} - -TEST(FieldTest, CanExplainMatchResultWithFieldName) { - Matcher m = Field("field_name", &AStruct::x, Ge(0)); - - AStruct a; - a.x = 1; - EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a)); - - m = Field("field_name", &AStruct::x, GreaterThan(0)); - EXPECT_EQ("whose field `field_name` is 1" + OfType("int") + - ", which is 1 more than 0", - Explain(m, a)); -} - -// Tests that Field() works when the argument is a pointer to const. -TEST(FieldForPointerTest, WorksForPointerToConst) { - Matcher m = Field(&AStruct::x, Ge(0)); - - AStruct a; - EXPECT_TRUE(m.Matches(&a)); - a.x = -1; - EXPECT_FALSE(m.Matches(&a)); -} - -// Tests that Field() works when the argument is a pointer to non-const. -TEST(FieldForPointerTest, WorksForPointerToNonConst) { - Matcher m = Field(&AStruct::x, Ge(0)); - - AStruct a; - EXPECT_TRUE(m.Matches(&a)); - a.x = -1; - EXPECT_FALSE(m.Matches(&a)); -} - -// Tests that Field() works when the argument is a reference to a const pointer. -TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { - Matcher m = Field(&AStruct::x, Ge(0)); - - AStruct a; - EXPECT_TRUE(m.Matches(&a)); - a.x = -1; - EXPECT_FALSE(m.Matches(&a)); -} - -// Tests that Field() does not match the NULL pointer. -TEST(FieldForPointerTest, DoesNotMatchNull) { - Matcher m = Field(&AStruct::x, _); - EXPECT_FALSE(m.Matches(nullptr)); -} - -// Tests that Field(&Foo::field, ...) works when the argument's type -// is a sub-type of const Foo*. -TEST(FieldForPointerTest, WorksForArgumentOfSubType) { - // Note that the matcher expects DerivedStruct but we say AStruct - // inside Field(). - Matcher m = Field(&AStruct::x, Ge(0)); - - DerivedStruct d; - EXPECT_TRUE(m.Matches(&d)); - d.x = -1; - EXPECT_FALSE(m.Matches(&d)); -} - -// Tests that Field() can describe itself when used to match a pointer. -TEST(FieldForPointerTest, CanDescribeSelf) { - Matcher m = Field(&AStruct::x, Ge(0)); - - EXPECT_EQ("is an object whose given field is >= 0", Describe(m)); - EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m)); -} - -TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { - Matcher m = Field("field_name", &AStruct::x, Ge(0)); - - EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m)); - EXPECT_EQ("is an object whose field `field_name` isn't >= 0", - DescribeNegation(m)); -} - -// Tests that Field() can explain the result of matching a pointer. -TEST(FieldForPointerTest, CanExplainMatchResult) { - Matcher m = Field(&AStruct::x, Ge(0)); - - AStruct a; - a.x = 1; - EXPECT_EQ("", Explain(m, static_cast(nullptr))); - EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"), - Explain(m, &a)); - - m = Field(&AStruct::x, GreaterThan(0)); - EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") + - ", which is 1 more than 0", Explain(m, &a)); -} - -TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { - Matcher m = Field("field_name", &AStruct::x, Ge(0)); - - AStruct a; - a.x = 1; - EXPECT_EQ("", Explain(m, static_cast(nullptr))); - EXPECT_EQ( - "which points to an object whose field `field_name` is 1" + OfType("int"), - Explain(m, &a)); - - m = Field("field_name", &AStruct::x, GreaterThan(0)); - EXPECT_EQ("which points to an object whose field `field_name` is 1" + - OfType("int") + ", which is 1 more than 0", - Explain(m, &a)); -} - -// A user-defined class for testing Property(). -class AClass { - public: - AClass() : n_(0) {} - - // A getter that returns a non-reference. - int n() const { return n_; } - - void set_n(int new_n) { n_ = new_n; } - - // A getter that returns a reference to const. - const std::string& s() const { return s_; } - - const std::string& s_ref() const & { return s_; } - - void set_s(const std::string& new_s) { s_ = new_s; } - - // A getter that returns a reference to non-const. - double& x() const { return x_; } - - private: - int n_; - std::string s_; - - static double x_; -}; - -double AClass::x_ = 0.0; - -// A derived class for testing Property(). -class DerivedClass : public AClass { - public: - int k() const { return k_; } - private: - int k_; -}; - -// Tests that Property(&Foo::property, ...) works when property() -// returns a non-reference. -TEST(PropertyTest, WorksForNonReferenceProperty) { - Matcher m = Property(&AClass::n, Ge(0)); - Matcher m_with_name = Property("n", &AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_TRUE(m.Matches(a)); - EXPECT_TRUE(m_with_name.Matches(a)); - - a.set_n(-1); - EXPECT_FALSE(m.Matches(a)); - EXPECT_FALSE(m_with_name.Matches(a)); -} - -// Tests that Property(&Foo::property, ...) works when property() -// returns a reference to const. -TEST(PropertyTest, WorksForReferenceToConstProperty) { - Matcher m = Property(&AClass::s, StartsWith("hi")); - Matcher m_with_name = - Property("s", &AClass::s, StartsWith("hi")); - - AClass a; - a.set_s("hill"); - EXPECT_TRUE(m.Matches(a)); - EXPECT_TRUE(m_with_name.Matches(a)); - - a.set_s("hole"); - EXPECT_FALSE(m.Matches(a)); - EXPECT_FALSE(m_with_name.Matches(a)); -} - -// Tests that Property(&Foo::property, ...) works when property() is -// ref-qualified. -TEST(PropertyTest, WorksForRefQualifiedProperty) { - Matcher m = Property(&AClass::s_ref, StartsWith("hi")); - Matcher m_with_name = - Property("s", &AClass::s_ref, StartsWith("hi")); - - AClass a; - a.set_s("hill"); - EXPECT_TRUE(m.Matches(a)); - EXPECT_TRUE(m_with_name.Matches(a)); - - a.set_s("hole"); - EXPECT_FALSE(m.Matches(a)); - EXPECT_FALSE(m_with_name.Matches(a)); -} - -// Tests that Property(&Foo::property, ...) works when property() -// returns a reference to non-const. -TEST(PropertyTest, WorksForReferenceToNonConstProperty) { - double x = 0.0; - AClass a; - - Matcher m = Property(&AClass::x, Ref(x)); - EXPECT_FALSE(m.Matches(a)); - - m = Property(&AClass::x, Not(Ref(x))); - EXPECT_TRUE(m.Matches(a)); -} - -// Tests that Property(&Foo::property, ...) works when the argument is -// passed by value. -TEST(PropertyTest, WorksForByValueArgument) { - Matcher m = Property(&AClass::s, StartsWith("hi")); - - AClass a; - a.set_s("hill"); - EXPECT_TRUE(m.Matches(a)); - - a.set_s("hole"); - EXPECT_FALSE(m.Matches(a)); -} - -// Tests that Property(&Foo::property, ...) works when the argument's -// type is a sub-type of Foo. -TEST(PropertyTest, WorksForArgumentOfSubType) { - // The matcher expects a DerivedClass, but inside the Property() we - // say AClass. - Matcher m = Property(&AClass::n, Ge(0)); - - DerivedClass d; - d.set_n(1); - EXPECT_TRUE(m.Matches(d)); - - d.set_n(-1); - EXPECT_FALSE(m.Matches(d)); -} - -// Tests that Property(&Foo::property, m) works when property()'s type -// and m's argument type are compatible but different. -TEST(PropertyTest, WorksForCompatibleMatcherType) { - // n() returns an int but the inner matcher expects a signed char. - Matcher m = Property(&AClass::n, - Matcher(Ge(0))); - - Matcher m_with_name = - Property("n", &AClass::n, Matcher(Ge(0))); - - AClass a; - EXPECT_TRUE(m.Matches(a)); - EXPECT_TRUE(m_with_name.Matches(a)); - a.set_n(-1); - EXPECT_FALSE(m.Matches(a)); - EXPECT_FALSE(m_with_name.Matches(a)); -} - -// Tests that Property() can describe itself. -TEST(PropertyTest, CanDescribeSelf) { - Matcher m = Property(&AClass::n, Ge(0)); - - EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); - EXPECT_EQ("is an object whose given property isn't >= 0", - DescribeNegation(m)); -} - -TEST(PropertyTest, CanDescribeSelfWithPropertyName) { - Matcher m = Property("fancy_name", &AClass::n, Ge(0)); - - EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); - EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", - DescribeNegation(m)); -} - -// Tests that Property() can explain the match result. -TEST(PropertyTest, CanExplainMatchResult) { - Matcher m = Property(&AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a)); - - m = Property(&AClass::n, GreaterThan(0)); - EXPECT_EQ( - "whose given property is 1" + OfType("int") + ", which is 1 more than 0", - Explain(m, a)); -} - -TEST(PropertyTest, CanExplainMatchResultWithPropertyName) { - Matcher m = Property("fancy_name", &AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a)); - - m = Property("fancy_name", &AClass::n, GreaterThan(0)); - EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") + - ", which is 1 more than 0", - Explain(m, a)); -} - -// Tests that Property() works when the argument is a pointer to const. -TEST(PropertyForPointerTest, WorksForPointerToConst) { - Matcher m = Property(&AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_TRUE(m.Matches(&a)); - - a.set_n(-1); - EXPECT_FALSE(m.Matches(&a)); -} - -// Tests that Property() works when the argument is a pointer to non-const. -TEST(PropertyForPointerTest, WorksForPointerToNonConst) { - Matcher m = Property(&AClass::s, StartsWith("hi")); - - AClass a; - a.set_s("hill"); - EXPECT_TRUE(m.Matches(&a)); - - a.set_s("hole"); - EXPECT_FALSE(m.Matches(&a)); -} - -// Tests that Property() works when the argument is a reference to a -// const pointer. -TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { - Matcher m = Property(&AClass::s, StartsWith("hi")); - - AClass a; - a.set_s("hill"); - EXPECT_TRUE(m.Matches(&a)); - - a.set_s("hole"); - EXPECT_FALSE(m.Matches(&a)); -} - -// Tests that Property() does not match the NULL pointer. -TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { - Matcher m = Property(&AClass::x, _); - EXPECT_FALSE(m.Matches(nullptr)); -} - -// Tests that Property(&Foo::property, ...) works when the argument's -// type is a sub-type of const Foo*. -TEST(PropertyForPointerTest, WorksForArgumentOfSubType) { - // The matcher expects a DerivedClass, but inside the Property() we - // say AClass. - Matcher m = Property(&AClass::n, Ge(0)); - - DerivedClass d; - d.set_n(1); - EXPECT_TRUE(m.Matches(&d)); - - d.set_n(-1); - EXPECT_FALSE(m.Matches(&d)); -} - -// Tests that Property() can describe itself when used to match a pointer. -TEST(PropertyForPointerTest, CanDescribeSelf) { - Matcher m = Property(&AClass::n, Ge(0)); - - EXPECT_EQ("is an object whose given property is >= 0", Describe(m)); - EXPECT_EQ("is an object whose given property isn't >= 0", - DescribeNegation(m)); -} - -TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { - Matcher m = Property("fancy_name", &AClass::n, Ge(0)); - - EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m)); - EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0", - DescribeNegation(m)); -} - -// Tests that Property() can explain the result of matching a pointer. -TEST(PropertyForPointerTest, CanExplainMatchResult) { - Matcher m = Property(&AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_EQ("", Explain(m, static_cast(nullptr))); - EXPECT_EQ( - "which points to an object whose given property is 1" + OfType("int"), - Explain(m, &a)); - - m = Property(&AClass::n, GreaterThan(0)); - EXPECT_EQ("which points to an object whose given property is 1" + - OfType("int") + ", which is 1 more than 0", - Explain(m, &a)); -} - -TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) { - Matcher m = Property("fancy_name", &AClass::n, Ge(0)); - - AClass a; - a.set_n(1); - EXPECT_EQ("", Explain(m, static_cast(nullptr))); - EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + - OfType("int"), - Explain(m, &a)); - - m = Property("fancy_name", &AClass::n, GreaterThan(0)); - EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + - OfType("int") + ", which is 1 more than 0", - Explain(m, &a)); -} - -// Tests ResultOf. - -// Tests that ResultOf(f, ...) compiles and works as expected when f is a -// function pointer. -std::string IntToStringFunction(int input) { - return input == 1 ? "foo" : "bar"; -} - -TEST(ResultOfTest, WorksForFunctionPointers) { - Matcher matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo"))); - - EXPECT_TRUE(matcher.Matches(1)); - EXPECT_FALSE(matcher.Matches(2)); -} - -// Tests that ResultOf() can describe itself. -TEST(ResultOfTest, CanDescribeItself) { - Matcher matcher = ResultOf(&IntToStringFunction, StrEq("foo")); - - EXPECT_EQ("is mapped by the given callable to a value that " - "is equal to \"foo\"", Describe(matcher)); - EXPECT_EQ("is mapped by the given callable to a value that " - "isn't equal to \"foo\"", DescribeNegation(matcher)); -} - -// Tests that ResultOf() can explain the match result. -int IntFunction(int input) { return input == 42 ? 80 : 90; } - -TEST(ResultOfTest, CanExplainMatchResult) { - Matcher matcher = ResultOf(&IntFunction, Ge(85)); - EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"), - Explain(matcher, 36)); - - matcher = ResultOf(&IntFunction, GreaterThan(85)); - EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") + - ", which is 5 more than 85", Explain(matcher, 36)); -} - -// Tests that ResultOf(f, ...) compiles and works as expected when f(x) -// returns a non-reference. -TEST(ResultOfTest, WorksForNonReferenceResults) { - Matcher matcher = ResultOf(&IntFunction, Eq(80)); - - EXPECT_TRUE(matcher.Matches(42)); - EXPECT_FALSE(matcher.Matches(36)); -} - -// Tests that ResultOf(f, ...) compiles and works as expected when f(x) -// returns a reference to non-const. -double& DoubleFunction(double& input) { return input; } // NOLINT - -Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT - return obj; -} - -TEST(ResultOfTest, WorksForReferenceToNonConstResults) { - double x = 3.14; - double x2 = x; - Matcher matcher = ResultOf(&DoubleFunction, Ref(x)); - - EXPECT_TRUE(matcher.Matches(x)); - EXPECT_FALSE(matcher.Matches(x2)); - - // Test that ResultOf works with uncopyable objects - Uncopyable obj(0); - Uncopyable obj2(0); - Matcher matcher2 = - ResultOf(&RefUncopyableFunction, Ref(obj)); - - EXPECT_TRUE(matcher2.Matches(obj)); - EXPECT_FALSE(matcher2.Matches(obj2)); -} - -// Tests that ResultOf(f, ...) compiles and works as expected when f(x) -// returns a reference to const. -const std::string& StringFunction(const std::string& input) { return input; } - -TEST(ResultOfTest, WorksForReferenceToConstResults) { - std::string s = "foo"; - std::string s2 = s; - Matcher matcher = ResultOf(&StringFunction, Ref(s)); - - EXPECT_TRUE(matcher.Matches(s)); - EXPECT_FALSE(matcher.Matches(s2)); -} - -// Tests that ResultOf(f, m) works when f(x) and m's -// argument types are compatible but different. -TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { - // IntFunction() returns int but the inner matcher expects a signed char. - Matcher matcher = ResultOf(IntFunction, Matcher(Ge(85))); - - EXPECT_TRUE(matcher.Matches(36)); - EXPECT_FALSE(matcher.Matches(42)); -} - -// Tests that the program aborts when ResultOf is passed -// a NULL function pointer. -TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { - EXPECT_DEATH_IF_SUPPORTED( - ResultOf(static_cast(nullptr), - Eq(std::string("foo"))), - "NULL function pointer is passed into ResultOf\\(\\)\\."); -} - -// Tests that ResultOf(f, ...) compiles and works as expected when f is a -// function reference. -TEST(ResultOfTest, WorksForFunctionReferences) { - Matcher matcher = ResultOf(IntToStringFunction, StrEq("foo")); - EXPECT_TRUE(matcher.Matches(1)); - EXPECT_FALSE(matcher.Matches(2)); -} - -// Tests that ResultOf(f, ...) compiles and works as expected when f is a -// function object. -struct Functor { - std::string operator()(int input) const { - return IntToStringFunction(input); - } -}; - -TEST(ResultOfTest, WorksForFunctors) { - Matcher matcher = ResultOf(Functor(), Eq(std::string("foo"))); - - EXPECT_TRUE(matcher.Matches(1)); - EXPECT_FALSE(matcher.Matches(2)); -} - -// Tests that ResultOf(f, ...) compiles and works as expected when f is a -// functor with more than one operator() defined. ResultOf() must work -// for each defined operator(). -struct PolymorphicFunctor { - typedef int result_type; - int operator()(int n) { return n; } - int operator()(const char* s) { return static_cast(strlen(s)); } - std::string operator()(int *p) { return p ? "good ptr" : "null"; } -}; - -TEST(ResultOfTest, WorksForPolymorphicFunctors) { - Matcher matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); - - EXPECT_TRUE(matcher_int.Matches(10)); - EXPECT_FALSE(matcher_int.Matches(2)); - - Matcher matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); - - EXPECT_TRUE(matcher_string.Matches("long string")); - EXPECT_FALSE(matcher_string.Matches("shrt")); -} - -TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { - Matcher matcher = ResultOf(PolymorphicFunctor(), "good ptr"); - - int n = 0; - EXPECT_TRUE(matcher.Matches(&n)); - EXPECT_FALSE(matcher.Matches(nullptr)); -} - -TEST(ResultOfTest, WorksForLambdas) { - Matcher matcher = ResultOf( - [](int str_len) { - return std::string(static_cast(str_len), 'x'); - }, - "xxx"); - EXPECT_TRUE(matcher.Matches(3)); - EXPECT_FALSE(matcher.Matches(1)); -} - -TEST(ResultOfTest, WorksForNonCopyableArguments) { - Matcher> matcher = ResultOf( - [](const std::unique_ptr& str_len) { - return std::string(static_cast(*str_len), 'x'); - }, - "xxx"); - EXPECT_TRUE(matcher.Matches(std::unique_ptr(new int(3)))); - EXPECT_FALSE(matcher.Matches(std::unique_ptr(new int(1)))); -} - -const int* ReferencingFunction(const int& n) { return &n; } - -struct ReferencingFunctor { - typedef const int* result_type; - result_type operator()(const int& n) { return &n; } -}; - -TEST(ResultOfTest, WorksForReferencingCallables) { - const int n = 1; - const int n2 = 1; - Matcher matcher2 = ResultOf(ReferencingFunction, Eq(&n)); - EXPECT_TRUE(matcher2.Matches(n)); - EXPECT_FALSE(matcher2.Matches(n2)); - - Matcher matcher3 = ResultOf(ReferencingFunctor(), Eq(&n)); - EXPECT_TRUE(matcher3.Matches(n)); - EXPECT_FALSE(matcher3.Matches(n2)); -} - -class DivisibleByImpl { - public: - explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {} - - // For testing using ExplainMatchResultTo() with polymorphic matchers. - template - bool MatchAndExplain(const T& n, MatchResultListener* listener) const { - *listener << "which is " << (n % divider_) << " modulo " - << divider_; - return (n % divider_) == 0; - } - - void DescribeTo(ostream* os) const { - *os << "is divisible by " << divider_; - } - - void DescribeNegationTo(ostream* os) const { - *os << "is not divisible by " << divider_; - } - - void set_divider(int a_divider) { divider_ = a_divider; } - int divider() const { return divider_; } - - private: - int divider_; -}; - -PolymorphicMatcher DivisibleBy(int n) { - return MakePolymorphicMatcher(DivisibleByImpl(n)); -} - -// Tests that when AllOf() fails, only the first failing matcher is -// asked to explain why. -TEST(ExplainMatchResultTest, AllOf_False_False) { - const Matcher m = AllOf(DivisibleBy(4), DivisibleBy(3)); - EXPECT_EQ("which is 1 modulo 4", Explain(m, 5)); -} - -// Tests that when AllOf() fails, only the first failing matcher is -// asked to explain why. -TEST(ExplainMatchResultTest, AllOf_False_True) { - const Matcher m = AllOf(DivisibleBy(4), DivisibleBy(3)); - EXPECT_EQ("which is 2 modulo 4", Explain(m, 6)); -} - -// Tests that when AllOf() fails, only the first failing matcher is -// asked to explain why. -TEST(ExplainMatchResultTest, AllOf_True_False) { - const Matcher m = AllOf(Ge(1), DivisibleBy(3)); - EXPECT_EQ("which is 2 modulo 3", Explain(m, 5)); -} - -// Tests that when AllOf() succeeds, all matchers are asked to explain -// why. -TEST(ExplainMatchResultTest, AllOf_True_True) { - const Matcher m = AllOf(DivisibleBy(2), DivisibleBy(3)); - EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6)); -} - -TEST(ExplainMatchResultTest, AllOf_True_True_2) { - const Matcher m = AllOf(Ge(2), Le(3)); - EXPECT_EQ("", Explain(m, 2)); -} - -TEST(ExplainmatcherResultTest, MonomorphicMatcher) { - const Matcher m = GreaterThan(5); - EXPECT_EQ("which is 1 more than 5", Explain(m, 6)); -} - -// The following two tests verify that values without a public copy -// ctor can be used as arguments to matchers like Eq(), Ge(), and etc -// with the help of ByRef(). - -class NotCopyable { - public: - explicit NotCopyable(int a_value) : value_(a_value) {} - - int value() const { return value_; } - - bool operator==(const NotCopyable& rhs) const { - return value() == rhs.value(); - } - - bool operator>=(const NotCopyable& rhs) const { - return value() >= rhs.value(); - } - private: - int value_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable); -}; - -TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) { - const NotCopyable const_value1(1); - const Matcher m = Eq(ByRef(const_value1)); - - const NotCopyable n1(1), n2(2); - EXPECT_TRUE(m.Matches(n1)); - EXPECT_FALSE(m.Matches(n2)); -} - -TEST(ByRefTest, AllowsNotCopyableValueInMatchers) { - NotCopyable value2(2); - const Matcher m = Ge(ByRef(value2)); - - NotCopyable n1(1), n2(2); - EXPECT_FALSE(m.Matches(n1)); - EXPECT_TRUE(m.Matches(n2)); -} - -TEST(IsEmptyTest, ImplementsIsEmpty) { - vector container; - EXPECT_THAT(container, IsEmpty()); - container.push_back(0); - EXPECT_THAT(container, Not(IsEmpty())); - container.push_back(1); - EXPECT_THAT(container, Not(IsEmpty())); -} - -TEST(IsEmptyTest, WorksWithString) { - std::string text; - EXPECT_THAT(text, IsEmpty()); - text = "foo"; - EXPECT_THAT(text, Not(IsEmpty())); - text = std::string("\0", 1); - EXPECT_THAT(text, Not(IsEmpty())); -} - -TEST(IsEmptyTest, CanDescribeSelf) { - Matcher > m = IsEmpty(); - EXPECT_EQ("is empty", Describe(m)); - EXPECT_EQ("isn't empty", DescribeNegation(m)); -} - -TEST(IsEmptyTest, ExplainsResult) { - Matcher > m = IsEmpty(); - vector container; - EXPECT_EQ("", Explain(m, container)); - container.push_back(0); - EXPECT_EQ("whose size is 1", Explain(m, container)); -} - -TEST(IsEmptyTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(IsEmpty())); - helper.Call({}); -} - -TEST(IsTrueTest, IsTrueIsFalse) { - EXPECT_THAT(true, IsTrue()); - EXPECT_THAT(false, IsFalse()); - EXPECT_THAT(true, Not(IsFalse())); - EXPECT_THAT(false, Not(IsTrue())); - EXPECT_THAT(0, Not(IsTrue())); - EXPECT_THAT(0, IsFalse()); - EXPECT_THAT(nullptr, Not(IsTrue())); - EXPECT_THAT(nullptr, IsFalse()); - EXPECT_THAT(-1, IsTrue()); - EXPECT_THAT(-1, Not(IsFalse())); - EXPECT_THAT(1, IsTrue()); - EXPECT_THAT(1, Not(IsFalse())); - EXPECT_THAT(2, IsTrue()); - EXPECT_THAT(2, Not(IsFalse())); - int a = 42; - EXPECT_THAT(a, IsTrue()); - EXPECT_THAT(a, Not(IsFalse())); - EXPECT_THAT(&a, IsTrue()); - EXPECT_THAT(&a, Not(IsFalse())); - EXPECT_THAT(false, Not(IsTrue())); - EXPECT_THAT(true, Not(IsFalse())); - EXPECT_THAT(std::true_type(), IsTrue()); - EXPECT_THAT(std::true_type(), Not(IsFalse())); - EXPECT_THAT(std::false_type(), IsFalse()); - EXPECT_THAT(std::false_type(), Not(IsTrue())); - EXPECT_THAT(nullptr, Not(IsTrue())); - EXPECT_THAT(nullptr, IsFalse()); - std::unique_ptr null_unique; - std::unique_ptr nonnull_unique(new int(0)); - EXPECT_THAT(null_unique, Not(IsTrue())); - EXPECT_THAT(null_unique, IsFalse()); - EXPECT_THAT(nonnull_unique, IsTrue()); - EXPECT_THAT(nonnull_unique, Not(IsFalse())); -} - -TEST(SizeIsTest, ImplementsSizeIs) { - vector container; - EXPECT_THAT(container, SizeIs(0)); - EXPECT_THAT(container, Not(SizeIs(1))); - container.push_back(0); - EXPECT_THAT(container, Not(SizeIs(0))); - EXPECT_THAT(container, SizeIs(1)); - container.push_back(0); - EXPECT_THAT(container, Not(SizeIs(0))); - EXPECT_THAT(container, SizeIs(2)); -} - -TEST(SizeIsTest, WorksWithMap) { - map container; - EXPECT_THAT(container, SizeIs(0)); - EXPECT_THAT(container, Not(SizeIs(1))); - container.insert(make_pair("foo", 1)); - EXPECT_THAT(container, Not(SizeIs(0))); - EXPECT_THAT(container, SizeIs(1)); - container.insert(make_pair("bar", 2)); - EXPECT_THAT(container, Not(SizeIs(0))); - EXPECT_THAT(container, SizeIs(2)); -} - -TEST(SizeIsTest, WorksWithReferences) { - vector container; - Matcher&> m = SizeIs(1); - EXPECT_THAT(container, Not(m)); - container.push_back(0); - EXPECT_THAT(container, m); -} - -TEST(SizeIsTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(SizeIs(3))); - helper.Call(MakeUniquePtrs({1, 2, 3})); -} - -// SizeIs should work for any type that provides a size() member function. -// For example, a size_type member type should not need to be provided. -struct MinimalistCustomType { - int size() const { return 1; } -}; -TEST(SizeIsTest, WorksWithMinimalistCustomType) { - MinimalistCustomType container; - EXPECT_THAT(container, SizeIs(1)); - EXPECT_THAT(container, Not(SizeIs(0))); -} - -TEST(SizeIsTest, CanDescribeSelf) { - Matcher > m = SizeIs(2); - EXPECT_EQ("size is equal to 2", Describe(m)); - EXPECT_EQ("size isn't equal to 2", DescribeNegation(m)); -} - -TEST(SizeIsTest, ExplainsResult) { - Matcher > m1 = SizeIs(2); - Matcher > m2 = SizeIs(Lt(2u)); - Matcher > m3 = SizeIs(AnyOf(0, 3)); - Matcher > m4 = SizeIs(GreaterThan(1)); - vector container; - EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container)); - EXPECT_EQ("whose size 0 matches", Explain(m2, container)); - EXPECT_EQ("whose size 0 matches", Explain(m3, container)); - EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1", - Explain(m4, container)); - container.push_back(0); - container.push_back(0); - EXPECT_EQ("whose size 2 matches", Explain(m1, container)); - EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container)); - EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container)); - EXPECT_EQ("whose size 2 matches, which is 1 more than 1", - Explain(m4, container)); -} - -#if GTEST_HAS_TYPED_TEST -// Tests ContainerEq with different container types, and -// different element types. - -template -class ContainerEqTest : public testing::Test {}; - -typedef testing::Types< - set, - vector, - multiset, - list > - ContainerEqTestTypes; - -TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes); - -// Tests that the filled container is equal to itself. -TYPED_TEST(ContainerEqTest, EqualsSelf) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - TypeParam my_set(vals, vals + 6); - const Matcher m = ContainerEq(my_set); - EXPECT_TRUE(m.Matches(my_set)); - EXPECT_EQ("", Explain(m, my_set)); -} - -// Tests that missing values are reported. -TYPED_TEST(ContainerEqTest, ValueMissing) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {2, 1, 8, 5}; - TypeParam my_set(vals, vals + 6); - TypeParam test_set(test_vals, test_vals + 4); - const Matcher m = ContainerEq(my_set); - EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which doesn't have these expected elements: 3", - Explain(m, test_set)); -} - -// Tests that added values are reported. -TYPED_TEST(ContainerEqTest, ValueAdded) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {1, 2, 3, 5, 8, 46}; - TypeParam my_set(vals, vals + 6); - TypeParam test_set(test_vals, test_vals + 6); - const Matcher m = ContainerEq(my_set); - EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set)); -} - -// Tests that added and missing values are reported together. -TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {1, 2, 3, 8, 46}; - TypeParam my_set(vals, vals + 6); - TypeParam test_set(test_vals, test_vals + 5); - const Matcher m = ContainerEq(my_set); - EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which has these unexpected elements: 46,\n" - "and doesn't have these expected elements: 5", - Explain(m, test_set)); -} - -// Tests duplicated value -- expect no explanation. -TYPED_TEST(ContainerEqTest, DuplicateDifference) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {1, 2, 3, 5, 8}; - TypeParam my_set(vals, vals + 6); - TypeParam test_set(test_vals, test_vals + 5); - const Matcher m = ContainerEq(my_set); - // Depending on the container, match may be true or false - // But in any case there should be no explanation. - EXPECT_EQ("", Explain(m, test_set)); -} -#endif // GTEST_HAS_TYPED_TEST - -// Tests that multiple missing values are reported. -// Using just vector here, so order is predictable. -TEST(ContainerEqExtraTest, MultipleValuesMissing) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {2, 1, 5}; - vector my_set(vals, vals + 6); - vector test_set(test_vals, test_vals + 3); - const Matcher > m = ContainerEq(my_set); - EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which doesn't have these expected elements: 3, 8", - Explain(m, test_set)); -} - -// Tests that added values are reported. -// Using just vector here, so order is predictable. -TEST(ContainerEqExtraTest, MultipleValuesAdded) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; - list my_set(vals, vals + 6); - list test_set(test_vals, test_vals + 7); - const Matcher&> m = ContainerEq(my_set); - EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which has these unexpected elements: 92, 46", - Explain(m, test_set)); -} - -// Tests that added and missing values are reported together. -TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {1, 2, 3, 92, 46}; - list my_set(vals, vals + 6); - list test_set(test_vals, test_vals + 5); - const Matcher > m = ContainerEq(my_set); - EXPECT_FALSE(m.Matches(test_set)); - EXPECT_EQ("which has these unexpected elements: 92, 46,\n" - "and doesn't have these expected elements: 5, 8", - Explain(m, test_set)); -} - -// Tests to see that duplicate elements are detected, -// but (as above) not reported in the explanation. -TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { - static const int vals[] = {1, 1, 2, 3, 5, 8}; - static const int test_vals[] = {1, 2, 3, 5, 8}; - vector my_set(vals, vals + 6); - vector test_set(test_vals, test_vals + 5); - const Matcher > m = ContainerEq(my_set); - EXPECT_TRUE(m.Matches(my_set)); - EXPECT_FALSE(m.Matches(test_set)); - // There is nothing to report when both sets contain all the same values. - EXPECT_EQ("", Explain(m, test_set)); -} - -// Tests that ContainerEq works for non-trivial associative containers, -// like maps. -TEST(ContainerEqExtraTest, WorksForMaps) { - map my_map; - my_map[0] = "a"; - my_map[1] = "b"; - - map test_map; - test_map[0] = "aa"; - test_map[1] = "b"; - - const Matcher&> m = ContainerEq(my_map); - EXPECT_TRUE(m.Matches(my_map)); - EXPECT_FALSE(m.Matches(test_map)); - - EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n" - "and doesn't have these expected elements: (0, \"a\")", - Explain(m, test_map)); -} - -TEST(ContainerEqExtraTest, WorksForNativeArray) { - int a1[] = {1, 2, 3}; - int a2[] = {1, 2, 3}; - int b[] = {1, 2, 4}; - - EXPECT_THAT(a1, ContainerEq(a2)); - EXPECT_THAT(a1, Not(ContainerEq(b))); -} - -TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) { - const char a1[][3] = {"hi", "lo"}; - const char a2[][3] = {"hi", "lo"}; - const char b[][3] = {"lo", "hi"}; - - // Tests using ContainerEq() in the first dimension. - EXPECT_THAT(a1, ContainerEq(a2)); - EXPECT_THAT(a1, Not(ContainerEq(b))); - - // Tests using ContainerEq() in the second dimension. - EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1]))); - EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1]))); -} - -TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { - const int a1[] = {1, 2, 3}; - const int a2[] = {1, 2, 3}; - const int b[] = {1, 2, 3, 4}; - - const int* const p1 = a1; - EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2)); - EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b))); - - const int c[] = {1, 3, 2}; - EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c))); -} - -TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { - std::string a1[][3] = { - {"hi", "hello", "ciao"}, - {"bye", "see you", "ciao"} - }; - - std::string a2[][3] = { - {"hi", "hello", "ciao"}, - {"bye", "see you", "ciao"} - }; - - const Matcher m = ContainerEq(a2); - EXPECT_THAT(a1, m); - - a2[0][0] = "ha"; - EXPECT_THAT(a1, m); -} - -TEST(WhenSortedByTest, WorksForEmptyContainer) { - const vector numbers; - EXPECT_THAT(numbers, WhenSortedBy(less(), ElementsAre())); - EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1)))); -} - -TEST(WhenSortedByTest, WorksForNonEmptyContainer) { - vector numbers; - numbers.push_back(3); - numbers.push_back(1); - numbers.push_back(2); - numbers.push_back(2); - EXPECT_THAT(numbers, WhenSortedBy(greater(), - ElementsAre(3, 2, 2, 1))); - EXPECT_THAT(numbers, Not(WhenSortedBy(greater(), - ElementsAre(1, 2, 2, 3)))); -} - -TEST(WhenSortedByTest, WorksForNonVectorContainer) { - list words; - words.push_back("say"); - words.push_back("hello"); - words.push_back("world"); - EXPECT_THAT(words, WhenSortedBy(less(), - ElementsAre("hello", "say", "world"))); - EXPECT_THAT(words, Not(WhenSortedBy(less(), - ElementsAre("say", "hello", "world")))); -} - -TEST(WhenSortedByTest, WorksForNativeArray) { - const int numbers[] = {1, 3, 2, 4}; - const int sorted_numbers[] = {1, 2, 3, 4}; - EXPECT_THAT(numbers, WhenSortedBy(less(), ElementsAre(1, 2, 3, 4))); - EXPECT_THAT(numbers, WhenSortedBy(less(), - ElementsAreArray(sorted_numbers))); - EXPECT_THAT(numbers, Not(WhenSortedBy(less(), ElementsAre(1, 3, 2, 4)))); -} - -TEST(WhenSortedByTest, CanDescribeSelf) { - const Matcher > m = WhenSortedBy(less(), ElementsAre(1, 2)); - EXPECT_EQ("(when sorted) has 2 elements where\n" - "element #0 is equal to 1,\n" - "element #1 is equal to 2", - Describe(m)); - EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n" - "element #0 isn't equal to 1, or\n" - "element #1 isn't equal to 2", - DescribeNegation(m)); -} - -TEST(WhenSortedByTest, ExplainsMatchResult) { - const int a[] = {2, 1}; - EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match", - Explain(WhenSortedBy(less(), ElementsAre(2, 3)), a)); - EXPECT_EQ("which is { 1, 2 } when sorted", - Explain(WhenSortedBy(less(), ElementsAre(1, 2)), a)); -} - -// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't -// need to test it as exhaustively as we test the latter. - -TEST(WhenSortedTest, WorksForEmptyContainer) { - const vector numbers; - EXPECT_THAT(numbers, WhenSorted(ElementsAre())); - EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); -} - -TEST(WhenSortedTest, WorksForNonEmptyContainer) { - list words; - words.push_back("3"); - words.push_back("1"); - words.push_back("2"); - words.push_back("2"); - EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3"))); - EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2")))); -} - -TEST(WhenSortedTest, WorksForMapTypes) { - map word_counts; - word_counts["and"] = 1; - word_counts["the"] = 1; - word_counts["buffalo"] = 2; - EXPECT_THAT(word_counts, - WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2), - Pair("the", 1)))); - EXPECT_THAT(word_counts, - Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1), - Pair("buffalo", 2))))); -} - -TEST(WhenSortedTest, WorksForMultiMapTypes) { - multimap ifib; - ifib.insert(make_pair(8, 6)); - ifib.insert(make_pair(2, 3)); - ifib.insert(make_pair(1, 1)); - ifib.insert(make_pair(3, 4)); - ifib.insert(make_pair(1, 2)); - ifib.insert(make_pair(5, 5)); - EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1), - Pair(1, 2), - Pair(2, 3), - Pair(3, 4), - Pair(5, 5), - Pair(8, 6)))); - EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6), - Pair(2, 3), - Pair(1, 1), - Pair(3, 4), - Pair(1, 2), - Pair(5, 5))))); -} - -TEST(WhenSortedTest, WorksForPolymorphicMatcher) { - std::deque d; - d.push_back(2); - d.push_back(1); - EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); - EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); -} - -TEST(WhenSortedTest, WorksForVectorConstRefMatcher) { - std::deque d; - d.push_back(2); - d.push_back(1); - Matcher&> vector_match = ElementsAre(1, 2); - EXPECT_THAT(d, WhenSorted(vector_match)); - Matcher&> not_vector_match = ElementsAre(2, 1); - EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); -} - -// Deliberately bare pseudo-container. -// Offers only begin() and end() accessors, yielding InputIterator. -template -class Streamlike { - private: - class ConstIter; - public: - typedef ConstIter const_iterator; - typedef T value_type; - - template - Streamlike(InIter first, InIter last) : remainder_(first, last) {} - - const_iterator begin() const { - return const_iterator(this, remainder_.begin()); - } - const_iterator end() const { - return const_iterator(this, remainder_.end()); - } - - private: - class ConstIter : public std::iterator { - public: - ConstIter(const Streamlike* s, - typename std::list::iterator pos) - : s_(s), pos_(pos) {} - - const value_type& operator*() const { return *pos_; } - const value_type* operator->() const { return &*pos_; } - ConstIter& operator++() { - s_->remainder_.erase(pos_++); - return *this; - } - - // *iter++ is required to work (see std::istreambuf_iterator). - // (void)iter++ is also required to work. - class PostIncrProxy { - public: - explicit PostIncrProxy(const value_type& value) : value_(value) {} - value_type operator*() const { return value_; } - private: - value_type value_; - }; - PostIncrProxy operator++(int) { - PostIncrProxy proxy(**this); - ++(*this); - return proxy; - } - - friend bool operator==(const ConstIter& a, const ConstIter& b) { - return a.s_ == b.s_ && a.pos_ == b.pos_; - } - friend bool operator!=(const ConstIter& a, const ConstIter& b) { - return !(a == b); - } - - private: - const Streamlike* s_; - typename std::list::iterator pos_; - }; - - friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { - os << "["; - typedef typename std::list::const_iterator Iter; - const char* sep = ""; - for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) { - os << sep << *it; - sep = ","; - } - os << "]"; - return os; - } - - mutable std::list remainder_; // modified by iteration -}; - -TEST(StreamlikeTest, Iteration) { - const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(a, a + 5); - Streamlike::const_iterator it = s.begin(); - const int* ip = a; - while (it != s.end()) { - SCOPED_TRACE(ip - a); - EXPECT_EQ(*ip++, *it++); - } -} - -TEST(BeginEndDistanceIsTest, WorksWithForwardList) { - std::forward_list container; - EXPECT_THAT(container, BeginEndDistanceIs(0)); - EXPECT_THAT(container, Not(BeginEndDistanceIs(1))); - container.push_front(0); - EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); - EXPECT_THAT(container, BeginEndDistanceIs(1)); - container.push_front(0); - EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); - EXPECT_THAT(container, BeginEndDistanceIs(2)); -} - -TEST(BeginEndDistanceIsTest, WorksWithNonStdList) { - const int a[5] = {1, 2, 3, 4, 5}; - Streamlike s(a, a + 5); - EXPECT_THAT(s, BeginEndDistanceIs(5)); -} - -TEST(BeginEndDistanceIsTest, CanDescribeSelf) { - Matcher > m = BeginEndDistanceIs(2); - EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m)); - EXPECT_EQ("distance between begin() and end() isn't equal to 2", - DescribeNegation(m)); -} - -TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(BeginEndDistanceIs(2))); - helper.Call(MakeUniquePtrs({1, 2})); -} - -TEST(BeginEndDistanceIsTest, ExplainsResult) { - Matcher > m1 = BeginEndDistanceIs(2); - Matcher > m2 = BeginEndDistanceIs(Lt(2)); - Matcher > m3 = BeginEndDistanceIs(AnyOf(0, 3)); - Matcher > m4 = BeginEndDistanceIs(GreaterThan(1)); - vector container; - EXPECT_EQ("whose distance between begin() and end() 0 doesn't match", - Explain(m1, container)); - EXPECT_EQ("whose distance between begin() and end() 0 matches", - Explain(m2, container)); - EXPECT_EQ("whose distance between begin() and end() 0 matches", - Explain(m3, container)); - EXPECT_EQ( - "whose distance between begin() and end() 0 doesn't match, which is 1 " - "less than 1", - Explain(m4, container)); - container.push_back(0); - container.push_back(0); - EXPECT_EQ("whose distance between begin() and end() 2 matches", - Explain(m1, container)); - EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", - Explain(m2, container)); - EXPECT_EQ("whose distance between begin() and end() 2 doesn't match", - Explain(m3, container)); - EXPECT_EQ( - "whose distance between begin() and end() 2 matches, which is 1 more " - "than 1", - Explain(m4, container)); -} - -TEST(WhenSortedTest, WorksForStreamlike) { - // Streamlike 'container' provides only minimal iterator support. - // Its iterators are tagged with input_iterator_tag. - const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(std::begin(a), std::end(a)); - EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5))); - EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); -} - -TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { - const int a[] = {2, 1, 4, 5, 3}; - Streamlike s(std::begin(a), std::end(a)); - Matcher&> vector_match = ElementsAre(1, 2, 3, 4, 5); - EXPECT_THAT(s, WhenSorted(vector_match)); - EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); -} - -TEST(IsSupersetOfTest, WorksForNativeArray) { - const int subset[] = {1, 4}; - const int superset[] = {1, 2, 4}; - const int disjoint[] = {1, 0, 3}; - EXPECT_THAT(subset, IsSupersetOf(subset)); - EXPECT_THAT(subset, Not(IsSupersetOf(superset))); - EXPECT_THAT(superset, IsSupersetOf(subset)); - EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); - EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); -} - -TEST(IsSupersetOfTest, WorksWithDuplicates) { - const int not_enough[] = {1, 2}; - const int enough[] = {1, 1, 2}; - const int expected[] = {1, 1}; - EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); - EXPECT_THAT(enough, IsSupersetOf(expected)); -} - -TEST(IsSupersetOfTest, WorksForEmpty) { - vector numbers; - vector expected; - EXPECT_THAT(numbers, IsSupersetOf(expected)); - expected.push_back(1); - EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); - expected.clear(); - numbers.push_back(1); - numbers.push_back(2); - EXPECT_THAT(numbers, IsSupersetOf(expected)); - expected.push_back(1); - EXPECT_THAT(numbers, IsSupersetOf(expected)); - expected.push_back(2); - EXPECT_THAT(numbers, IsSupersetOf(expected)); - expected.push_back(3); - EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); -} - -TEST(IsSupersetOfTest, WorksForStreamlike) { - const int a[5] = {1, 2, 3, 4, 5}; - Streamlike s(std::begin(a), std::end(a)); - - vector expected; - expected.push_back(1); - expected.push_back(2); - expected.push_back(5); - EXPECT_THAT(s, IsSupersetOf(expected)); - - expected.push_back(0); - EXPECT_THAT(s, Not(IsSupersetOf(expected))); -} - -TEST(IsSupersetOfTest, TakesStlContainer) { - const int actual[] = {3, 1, 2}; - - ::std::list expected; - expected.push_back(1); - expected.push_back(3); - EXPECT_THAT(actual, IsSupersetOf(expected)); - - expected.push_back(4); - EXPECT_THAT(actual, Not(IsSupersetOf(expected))); -} - -TEST(IsSupersetOfTest, Describe) { - typedef std::vector IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - EXPECT_THAT( - Describe(IsSupersetOf(expected)), - Eq("a surjection from elements to requirements exists such that:\n" - " - an element is equal to 111\n" - " - an element is equal to 222\n" - " - an element is equal to 333")); -} - -TEST(IsSupersetOfTest, DescribeNegation) { - typedef std::vector IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - EXPECT_THAT( - DescribeNegation(IsSupersetOf(expected)), - Eq("no surjection from elements to requirements exists such that:\n" - " - an element is equal to 111\n" - " - an element is equal to 222\n" - " - an element is equal to 333")); -} - -TEST(IsSupersetOfTest, MatchAndExplain) { - std::vector v; - v.push_back(2); - v.push_back(3); - std::vector expected; - expected.push_back(1); - expected.push_back(2); - StringMatchResultListener listener; - ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) - << listener.str(); - EXPECT_THAT(listener.str(), - Eq("where the following matchers don't match any elements:\n" - "matcher #0: is equal to 1")); - - v.push_back(1); - listener.Clear(); - ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) - << listener.str(); - EXPECT_THAT(listener.str(), Eq("where:\n" - " - element #0 is matched by matcher #1,\n" - " - element #2 is matched by matcher #0")); -} - -TEST(IsSupersetOfTest, WorksForRhsInitializerList) { - const int numbers[] = {1, 3, 6, 2, 4, 5}; - EXPECT_THAT(numbers, IsSupersetOf({1, 2})); - EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); -} - -TEST(IsSupersetOfTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)}))); - helper.Call(MakeUniquePtrs({1, 2})); - EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)})))); - helper.Call(MakeUniquePtrs({2})); -} - -TEST(IsSubsetOfTest, WorksForNativeArray) { - const int subset[] = {1, 4}; - const int superset[] = {1, 2, 4}; - const int disjoint[] = {1, 0, 3}; - EXPECT_THAT(subset, IsSubsetOf(subset)); - EXPECT_THAT(subset, IsSubsetOf(superset)); - EXPECT_THAT(superset, Not(IsSubsetOf(subset))); - EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); - EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); -} - -TEST(IsSubsetOfTest, WorksWithDuplicates) { - const int not_enough[] = {1, 2}; - const int enough[] = {1, 1, 2}; - const int actual[] = {1, 1}; - EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); - EXPECT_THAT(actual, IsSubsetOf(enough)); -} - -TEST(IsSubsetOfTest, WorksForEmpty) { - vector numbers; - vector expected; - EXPECT_THAT(numbers, IsSubsetOf(expected)); - expected.push_back(1); - EXPECT_THAT(numbers, IsSubsetOf(expected)); - expected.clear(); - numbers.push_back(1); - numbers.push_back(2); - EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); - expected.push_back(1); - EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); - expected.push_back(2); - EXPECT_THAT(numbers, IsSubsetOf(expected)); - expected.push_back(3); - EXPECT_THAT(numbers, IsSubsetOf(expected)); -} - -TEST(IsSubsetOfTest, WorksForStreamlike) { - const int a[5] = {1, 2}; - Streamlike s(std::begin(a), std::end(a)); - - vector expected; - expected.push_back(1); - EXPECT_THAT(s, Not(IsSubsetOf(expected))); - expected.push_back(2); - expected.push_back(5); - EXPECT_THAT(s, IsSubsetOf(expected)); -} - -TEST(IsSubsetOfTest, TakesStlContainer) { - const int actual[] = {3, 1, 2}; - - ::std::list expected; - expected.push_back(1); - expected.push_back(3); - EXPECT_THAT(actual, Not(IsSubsetOf(expected))); - - expected.push_back(2); - expected.push_back(4); - EXPECT_THAT(actual, IsSubsetOf(expected)); -} - -TEST(IsSubsetOfTest, Describe) { - typedef std::vector IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - - EXPECT_THAT( - Describe(IsSubsetOf(expected)), - Eq("an injection from elements to requirements exists such that:\n" - " - an element is equal to 111\n" - " - an element is equal to 222\n" - " - an element is equal to 333")); -} - -TEST(IsSubsetOfTest, DescribeNegation) { - typedef std::vector IntVec; - IntVec expected; - expected.push_back(111); - expected.push_back(222); - expected.push_back(333); - EXPECT_THAT( - DescribeNegation(IsSubsetOf(expected)), - Eq("no injection from elements to requirements exists such that:\n" - " - an element is equal to 111\n" - " - an element is equal to 222\n" - " - an element is equal to 333")); -} - -TEST(IsSubsetOfTest, MatchAndExplain) { - std::vector v; - v.push_back(2); - v.push_back(3); - std::vector expected; - expected.push_back(1); - expected.push_back(2); - StringMatchResultListener listener; - ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) - << listener.str(); - EXPECT_THAT(listener.str(), - Eq("where the following elements don't match any matchers:\n" - "element #1: 3")); - - expected.push_back(3); - listener.Clear(); - ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) - << listener.str(); - EXPECT_THAT(listener.str(), Eq("where:\n" - " - element #0 is matched by matcher #1,\n" - " - element #1 is matched by matcher #2")); -} - -TEST(IsSubsetOfTest, WorksForRhsInitializerList) { - const int numbers[] = {1, 2, 3}; - EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); - EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); -} - -TEST(IsSubsetOfTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)}))); - helper.Call(MakeUniquePtrs({1})); - EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)})))); - helper.Call(MakeUniquePtrs({2})); -} - -// Tests using ElementsAre() and ElementsAreArray() with stream-like -// "containers". - -TEST(ElemensAreStreamTest, WorksForStreamlike) { - const int a[5] = {1, 2, 3, 4, 5}; - Streamlike s(std::begin(a), std::end(a)); - EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5)); - EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3))); -} - -TEST(ElemensAreArrayStreamTest, WorksForStreamlike) { - const int a[5] = {1, 2, 3, 4, 5}; - Streamlike s(std::begin(a), std::end(a)); - - vector expected; - expected.push_back(1); - expected.push_back(2); - expected.push_back(3); - expected.push_back(4); - expected.push_back(5); - EXPECT_THAT(s, ElementsAreArray(expected)); - - expected[3] = 0; - EXPECT_THAT(s, Not(ElementsAreArray(expected))); -} - -TEST(ElementsAreTest, WorksWithUncopyable) { - Uncopyable objs[2]; - objs[0].set_value(-3); - objs[1].set_value(1); - EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive))); -} - -TEST(ElementsAreTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2)))); - helper.Call(MakeUniquePtrs({1, 2})); - - EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)}))); - helper.Call(MakeUniquePtrs({3, 4})); -} - -TEST(ElementsAreTest, TakesStlContainer) { - const int actual[] = {3, 1, 2}; - - ::std::list expected; - expected.push_back(3); - expected.push_back(1); - expected.push_back(2); - EXPECT_THAT(actual, ElementsAreArray(expected)); - - expected.push_back(4); - EXPECT_THAT(actual, Not(ElementsAreArray(expected))); -} - -// Tests for UnorderedElementsAreArray() - -TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { - const int a[] = {0, 1, 2, 3, 4}; - std::vector s(std::begin(a), std::end(a)); - do { - StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), - s, &listener)) << listener.str(); - } while (std::next_permutation(s.begin(), s.end())); -} - -TEST(UnorderedElementsAreArrayTest, VectorBool) { - const bool a[] = {0, 1, 0, 1, 1}; - const bool b[] = {1, 0, 1, 1, 0}; - std::vector expected(std::begin(a), std::end(a)); - std::vector actual(std::begin(b), std::end(b)); - StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), - actual, &listener)) << listener.str(); -} - -TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { - // Streamlike 'container' provides only minimal iterator support. - // Its iterators are tagged with input_iterator_tag, and it has no - // size() or empty() methods. - const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(std::begin(a), std::end(a)); - - ::std::vector expected; - expected.push_back(1); - expected.push_back(2); - expected.push_back(3); - expected.push_back(4); - expected.push_back(5); - EXPECT_THAT(s, UnorderedElementsAreArray(expected)); - - expected.push_back(6); - EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected))); -} - -TEST(UnorderedElementsAreArrayTest, TakesStlContainer) { - const int actual[] = {3, 1, 2}; - - ::std::list expected; - expected.push_back(1); - expected.push_back(2); - expected.push_back(3); - EXPECT_THAT(actual, UnorderedElementsAreArray(expected)); - - expected.push_back(4); - EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected))); -} - - -TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { - const int a[5] = {2, 1, 4, 5, 3}; - EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5})); - EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6}))); -} - -TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { - const std::string a[5] = {"a", "b", "c", "d", "e"}; - EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"})); - EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"}))); -} - -TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { - const int a[5] = {2, 1, 4, 5, 3}; - EXPECT_THAT(a, UnorderedElementsAreArray( - {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); - EXPECT_THAT(a, Not(UnorderedElementsAreArray( - {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); -} - -TEST(UnorderedElementsAreArrayTest, - TakesInitializerListOfDifferentTypedMatchers) { - const int a[5] = {2, 1, 4, 5, 3}; - // The compiler cannot infer the type of the initializer list if its - // elements have different types. We must explicitly specify the - // unified element type in this case. - EXPECT_THAT(a, UnorderedElementsAreArray >( - {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); - EXPECT_THAT(a, Not(UnorderedElementsAreArray >( - {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); -} - - -TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, - Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)}))); - helper.Call(MakeUniquePtrs({2, 1})); -} - -class UnorderedElementsAreTest : public testing::Test { - protected: - typedef std::vector IntVec; -}; - -TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) { - Uncopyable objs[2]; - objs[0].set_value(-3); - objs[1].set_value(1); - EXPECT_THAT(objs, - UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3))); -} - -TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { - const int a[] = {1, 2, 3}; - std::vector s(std::begin(a), std::end(a)); - do { - StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), - s, &listener)) << listener.str(); - } while (std::next_permutation(s.begin(), s.end())); -} - -TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { - const int a[] = {1, 2, 3}; - std::vector s(std::begin(a), std::end(a)); - std::vector > mv; - mv.push_back(1); - mv.push_back(2); - mv.push_back(2); - // The element with value '3' matches nothing: fail fast. - StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), - s, &listener)) << listener.str(); -} - -TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { - // Streamlike 'container' provides only minimal iterator support. - // Its iterators are tagged with input_iterator_tag, and it has no - // size() or empty() methods. - const int a[5] = {2, 1, 4, 5, 3}; - Streamlike s(std::begin(a), std::end(a)); - - EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); - EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); -} - -TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2)))); - helper.Call(MakeUniquePtrs({2, 1})); -} - -// One naive implementation of the matcher runs in O(N!) time, which is too -// slow for many real-world inputs. This test shows that our matcher can match -// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158 -// iterations and obviously effectively incomputable. -// [ RUN ] UnorderedElementsAreTest.Performance -// [ OK ] UnorderedElementsAreTest.Performance (4 ms) -TEST_F(UnorderedElementsAreTest, Performance) { - std::vector s; - std::vector > mv; - for (int i = 0; i < 100; ++i) { - s.push_back(i); - mv.push_back(_); - } - mv[50] = Eq(0); - StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), - s, &listener)) << listener.str(); -} - -// Another variant of 'Performance' with similar expectations. -// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict -// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms) -TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { - std::vector s; - std::vector > mv; - for (int i = 0; i < 100; ++i) { - s.push_back(i); - if (i & 1) { - mv.push_back(_); - } else { - mv.push_back(i); - } - } - StringMatchResultListener listener; - EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), - s, &listener)) << listener.str(); -} - -TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { - std::vector v; - v.push_back(4); - StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), - v, &listener)) << listener.str(); - EXPECT_THAT(listener.str(), Eq("which has 1 element")); -} - -TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { - std::vector v; - StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), - v, &listener)) << listener.str(); - EXPECT_THAT(listener.str(), Eq("")); -} - -TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { - std::vector v; - v.push_back(1); - v.push_back(1); - StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), - v, &listener)) << listener.str(); - EXPECT_THAT( - listener.str(), - Eq("where the following matchers don't match any elements:\n" - "matcher #1: is equal to 2")); -} - -TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { - std::vector v; - v.push_back(1); - v.push_back(2); - StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), - v, &listener)) << listener.str(); - EXPECT_THAT( - listener.str(), - Eq("where the following elements don't match any matchers:\n" - "element #1: 2")); -} - -TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { - std::vector v; - v.push_back(2); - v.push_back(3); - StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), - v, &listener)) << listener.str(); - EXPECT_THAT( - listener.str(), - Eq("where" - " the following matchers don't match any elements:\n" - "matcher #0: is equal to 1\n" - "and" - " where" - " the following elements don't match any matchers:\n" - "element #1: 3")); -} - -// Test helper for formatting element, matcher index pairs in expectations. -static std::string EMString(int element, int matcher) { - stringstream ss; - ss << "(element #" << element << ", matcher #" << matcher << ")"; - return ss.str(); -} - -TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { - // A situation where all elements and matchers have a match - // associated with them, but the max matching is not perfect. - std::vector v; - v.push_back("a"); - v.push_back("b"); - v.push_back("c"); - StringMatchResultListener listener; - EXPECT_FALSE(ExplainMatchResult( - UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener)) - << listener.str(); - - std::string prefix = - "where no permutation of the elements can satisfy all matchers, " - "and the closest match is 2 of 3 matchers with the " - "pairings:\n"; - - // We have to be a bit loose here, because there are 4 valid max matches. - EXPECT_THAT( - listener.str(), - AnyOf(prefix + "{\n " + EMString(0, 0) + - ",\n " + EMString(1, 2) + "\n}", - prefix + "{\n " + EMString(0, 1) + - ",\n " + EMString(1, 2) + "\n}", - prefix + "{\n " + EMString(0, 0) + - ",\n " + EMString(2, 2) + "\n}", - prefix + "{\n " + EMString(0, 1) + - ",\n " + EMString(2, 2) + "\n}")); -} - -TEST_F(UnorderedElementsAreTest, Describe) { - EXPECT_THAT(Describe(UnorderedElementsAre()), - Eq("is empty")); - EXPECT_THAT( - Describe(UnorderedElementsAre(345)), - Eq("has 1 element and that element is equal to 345")); - EXPECT_THAT( - Describe(UnorderedElementsAre(111, 222, 333)), - Eq("has 3 elements and there exists some permutation " - "of elements such that:\n" - " - element #0 is equal to 111, and\n" - " - element #1 is equal to 222, and\n" - " - element #2 is equal to 333")); -} - -TEST_F(UnorderedElementsAreTest, DescribeNegation) { - EXPECT_THAT(DescribeNegation(UnorderedElementsAre()), - Eq("isn't empty")); - EXPECT_THAT( - DescribeNegation(UnorderedElementsAre(345)), - Eq("doesn't have 1 element, or has 1 element that isn't equal to 345")); - EXPECT_THAT( - DescribeNegation(UnorderedElementsAre(123, 234, 345)), - Eq("doesn't have 3 elements, or there exists no permutation " - "of elements such that:\n" - " - element #0 is equal to 123, and\n" - " - element #1 is equal to 234, and\n" - " - element #2 is equal to 345")); -} - -namespace { - -// Used as a check on the more complex max flow method used in the -// real testing::internal::FindMaxBipartiteMatching. This method is -// compatible but runs in worst-case factorial time, so we only -// use it in testing for small problem sizes. -template -class BacktrackingMaxBPMState { - public: - // Does not take ownership of 'g'. - explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { } - - ElementMatcherPairs Compute() { - if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) { - return best_so_far_; - } - lhs_used_.assign(graph_->LhsSize(), kUnused); - rhs_used_.assign(graph_->RhsSize(), kUnused); - for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { - matches_.clear(); - RecurseInto(irhs); - if (best_so_far_.size() == graph_->RhsSize()) - break; - } - return best_so_far_; - } - - private: - static const size_t kUnused = static_cast(-1); - - void PushMatch(size_t lhs, size_t rhs) { - matches_.push_back(ElementMatcherPair(lhs, rhs)); - lhs_used_[lhs] = rhs; - rhs_used_[rhs] = lhs; - if (matches_.size() > best_so_far_.size()) { - best_so_far_ = matches_; - } - } - - void PopMatch() { - const ElementMatcherPair& back = matches_.back(); - lhs_used_[back.first] = kUnused; - rhs_used_[back.second] = kUnused; - matches_.pop_back(); - } - - bool RecurseInto(size_t irhs) { - if (rhs_used_[irhs] != kUnused) { - return true; - } - for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { - if (lhs_used_[ilhs] != kUnused) { - continue; - } - if (!graph_->HasEdge(ilhs, irhs)) { - continue; - } - PushMatch(ilhs, irhs); - if (best_so_far_.size() == graph_->RhsSize()) { - return false; - } - for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) { - if (!RecurseInto(mi)) return false; - } - PopMatch(); - } - return true; - } - - const Graph* graph_; // not owned - std::vector lhs_used_; - std::vector rhs_used_; - ElementMatcherPairs matches_; - ElementMatcherPairs best_so_far_; -}; - -template -const size_t BacktrackingMaxBPMState::kUnused; - -} // namespace - -// Implement a simple backtracking algorithm to determine if it is possible -// to find one element per matcher, without reusing elements. -template -ElementMatcherPairs -FindBacktrackingMaxBPM(const Graph& g) { - return BacktrackingMaxBPMState(&g).Compute(); -} - -class BacktrackingBPMTest : public ::testing::Test { }; - -// Tests the MaxBipartiteMatching algorithm with square matrices. -// The single int param is the # of nodes on each of the left and right sides. -class BipartiteTest : public ::testing::TestWithParam {}; - -// Verify all match graphs up to some moderate number of edges. -TEST_P(BipartiteTest, Exhaustive) { - size_t nodes = GetParam(); - MatchMatrix graph(nodes, nodes); - do { - ElementMatcherPairs matches = - internal::FindMaxBipartiteMatching(graph); - EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size()) - << "graph: " << graph.DebugString(); - // Check that all elements of matches are in the graph. - // Check that elements of first and second are unique. - std::vector seen_element(graph.LhsSize()); - std::vector seen_matcher(graph.RhsSize()); - SCOPED_TRACE(PrintToString(matches)); - for (size_t i = 0; i < matches.size(); ++i) { - size_t ilhs = matches[i].first; - size_t irhs = matches[i].second; - EXPECT_TRUE(graph.HasEdge(ilhs, irhs)); - EXPECT_FALSE(seen_element[ilhs]); - EXPECT_FALSE(seen_matcher[irhs]); - seen_element[ilhs] = true; - seen_matcher[irhs] = true; - } - } while (graph.NextGraph()); -} - -INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest, - ::testing::Range(size_t{0}, size_t{5})); - -// Parameterized by a pair interpreted as (LhsSize, RhsSize). -class BipartiteNonSquareTest - : public ::testing::TestWithParam > { -}; - -TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { - // ....... - // 0:-----\ : - // 1:---\ | : - // 2:---\ | : - // 3:-\ | | : - // :.......: - // 0 1 2 - MatchMatrix g(4, 3); - constexpr std::array, 4> kEdges = { - {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}}; - for (size_t i = 0; i < kEdges.size(); ++i) { - g.SetEdge(kEdges[i][0], kEdges[i][1], true); - } - EXPECT_THAT(FindBacktrackingMaxBPM(g), - ElementsAre(Pair(3, 0), - Pair(AnyOf(1, 2), 1), - Pair(0, 2))) << g.DebugString(); -} - -// Verify a few nonsquare matrices. -TEST_P(BipartiteNonSquareTest, Exhaustive) { - size_t nlhs = GetParam().first; - size_t nrhs = GetParam().second; - MatchMatrix graph(nlhs, nrhs); - do { - EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), - internal::FindMaxBipartiteMatching(graph).size()) - << "graph: " << graph.DebugString() - << "\nbacktracking: " - << PrintToString(FindBacktrackingMaxBPM(graph)) - << "\nmax flow: " - << PrintToString(internal::FindMaxBipartiteMatching(graph)); - } while (graph.NextGraph()); -} - -INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest, - testing::Values( - std::make_pair(1, 2), - std::make_pair(2, 1), - std::make_pair(3, 2), - std::make_pair(2, 3), - std::make_pair(4, 1), - std::make_pair(1, 4), - std::make_pair(4, 3), - std::make_pair(3, 4))); - -class BipartiteRandomTest - : public ::testing::TestWithParam > { -}; - -// Verifies a large sample of larger graphs. -TEST_P(BipartiteRandomTest, LargerNets) { - int nodes = GetParam().first; - int iters = GetParam().second; - MatchMatrix graph(static_cast(nodes), static_cast(nodes)); - - auto seed = static_cast(GTEST_FLAG(random_seed)); - if (seed == 0) { - seed = static_cast(time(nullptr)); - } - - for (; iters > 0; --iters, ++seed) { - srand(static_cast(seed)); - graph.Randomize(); - EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), - internal::FindMaxBipartiteMatching(graph).size()) - << " graph: " << graph.DebugString() - << "\nTo reproduce the failure, rerun the test with the flag" - " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; - } -} - -// Test argument is a std::pair representing (nodes, iters). -INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest, - testing::Values( - std::make_pair(5, 10000), - std::make_pair(6, 5000), - std::make_pair(7, 2000), - std::make_pair(8, 500), - std::make_pair(9, 100))); - -// Tests IsReadableTypeName(). - -TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) { - EXPECT_TRUE(IsReadableTypeName("int")); - EXPECT_TRUE(IsReadableTypeName("const unsigned char*")); - EXPECT_TRUE(IsReadableTypeName("MyMap")); - EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)")); -} - -TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) { - EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName")); - EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]")); - EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass")); -} - -TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) { - EXPECT_FALSE( - IsReadableTypeName("basic_string >")); - EXPECT_FALSE(IsReadableTypeName("std::vector >")); -} - -TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { - EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)")); -} - -// Tests FormatMatcherDescription(). - -TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { - EXPECT_EQ("is even", - FormatMatcherDescription(false, "IsEven", Strings())); - EXPECT_EQ("not (is even)", - FormatMatcherDescription(true, "IsEven", Strings())); - - const char* params[] = {"5"}; - EXPECT_EQ("equals 5", - FormatMatcherDescription(false, "Equals", - Strings(params, params + 1))); - - const char* params2[] = {"5", "8"}; - EXPECT_EQ("is in range (5, 8)", - FormatMatcherDescription(false, "IsInRange", - Strings(params2, params2 + 2))); -} - -// Tests PolymorphicMatcher::mutable_impl(). -TEST(PolymorphicMatcherTest, CanAccessMutableImpl) { - PolymorphicMatcher m(DivisibleByImpl(42)); - DivisibleByImpl& impl = m.mutable_impl(); - EXPECT_EQ(42, impl.divider()); - - impl.set_divider(0); - EXPECT_EQ(0, m.mutable_impl().divider()); -} - -// Tests PolymorphicMatcher::impl(). -TEST(PolymorphicMatcherTest, CanAccessImpl) { - const PolymorphicMatcher m(DivisibleByImpl(42)); - const DivisibleByImpl& impl = m.impl(); - EXPECT_EQ(42, impl.divider()); -} - -TEST(MatcherTupleTest, ExplainsMatchFailure) { - stringstream ss1; - ExplainMatchFailureTupleTo( - std::make_tuple(Matcher(Eq('a')), GreaterThan(5)), - std::make_tuple('a', 10), &ss1); - EXPECT_EQ("", ss1.str()); // Successful match. - - stringstream ss2; - ExplainMatchFailureTupleTo( - std::make_tuple(GreaterThan(5), Matcher(Eq('a'))), - std::make_tuple(2, 'b'), &ss2); - EXPECT_EQ(" Expected arg #0: is > 5\n" - " Actual: 2, which is 3 less than 5\n" - " Expected arg #1: is equal to 'a' (97, 0x61)\n" - " Actual: 'b' (98, 0x62)\n", - ss2.str()); // Failed match where both arguments need explanation. - - stringstream ss3; - ExplainMatchFailureTupleTo( - std::make_tuple(GreaterThan(5), Matcher(Eq('a'))), - std::make_tuple(2, 'a'), &ss3); - EXPECT_EQ(" Expected arg #0: is > 5\n" - " Actual: 2, which is 3 less than 5\n", - ss3.str()); // Failed match where only one argument needs - // explanation. -} - -// Tests Each(). - -TEST(EachTest, ExplainsMatchResultCorrectly) { - set a; // empty - - Matcher > m = Each(2); - EXPECT_EQ("", Explain(m, a)); - - Matcher n = Each(1); // NOLINT - - const int b[1] = {1}; - EXPECT_EQ("", Explain(n, b)); - - n = Each(3); - EXPECT_EQ("whose element #0 doesn't match", Explain(n, b)); - - a.insert(1); - a.insert(2); - a.insert(3); - m = Each(GreaterThan(0)); - EXPECT_EQ("", Explain(m, a)); - - m = Each(GreaterThan(10)); - EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10", - Explain(m, a)); -} - -TEST(EachTest, DescribesItselfCorrectly) { - Matcher > m = Each(1); - EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); - - Matcher > m2 = Not(m); - EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); -} - -TEST(EachTest, MatchesVectorWhenAllElementsMatch) { - vector some_vector; - EXPECT_THAT(some_vector, Each(1)); - some_vector.push_back(3); - EXPECT_THAT(some_vector, Not(Each(1))); - EXPECT_THAT(some_vector, Each(3)); - some_vector.push_back(1); - some_vector.push_back(2); - EXPECT_THAT(some_vector, Not(Each(3))); - EXPECT_THAT(some_vector, Each(Lt(3.5))); - - vector another_vector; - another_vector.push_back("fee"); - EXPECT_THAT(another_vector, Each(std::string("fee"))); - another_vector.push_back("fie"); - another_vector.push_back("foe"); - another_vector.push_back("fum"); - EXPECT_THAT(another_vector, Not(Each(std::string("fee")))); -} - -TEST(EachTest, MatchesMapWhenAllElementsMatch) { - map my_map; - const char* bar = "a string"; - my_map[bar] = 2; - EXPECT_THAT(my_map, Each(make_pair(bar, 2))); - - map another_map; - EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); - another_map["fee"] = 1; - EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1))); - another_map["fie"] = 2; - another_map["foe"] = 3; - another_map["fum"] = 4; - EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1)))); - EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1)))); - EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); -} - -TEST(EachTest, AcceptsMatcher) { - const int a[] = {1, 2, 3}; - EXPECT_THAT(a, Each(Gt(0))); - EXPECT_THAT(a, Not(Each(Gt(1)))); -} - -TEST(EachTest, WorksForNativeArrayAsTuple) { - const int a[] = {1, 2}; - const int* const pointer = a; - EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0))); - EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1)))); -} - -TEST(EachTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(Each(Pointee(Gt(0))))); - helper.Call(MakeUniquePtrs({1, 2})); -} - -// For testing Pointwise(). -class IsHalfOfMatcher { - public: - template - bool MatchAndExplain(const std::tuple& a_pair, - MatchResultListener* listener) const { - if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) { - *listener << "where the second is " << std::get<1>(a_pair); - return true; - } else { - *listener << "where the second/2 is " << std::get<1>(a_pair) / 2; - return false; - } - } - - void DescribeTo(ostream* os) const { - *os << "are a pair where the first is half of the second"; - } - - void DescribeNegationTo(ostream* os) const { - *os << "are a pair where the first isn't half of the second"; - } -}; - -PolymorphicMatcher IsHalfOf() { - return MakePolymorphicMatcher(IsHalfOfMatcher()); -} - -TEST(PointwiseTest, DescribesSelf) { - vector rhs; - rhs.push_back(1); - rhs.push_back(2); - rhs.push_back(3); - const Matcher&> m = Pointwise(IsHalfOf(), rhs); - EXPECT_EQ("contains 3 values, where each value and its corresponding value " - "in { 1, 2, 3 } are a pair where the first is half of the second", - Describe(m)); - EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " - "index i where x and the i-th value of { 1, 2, 3 } are a pair " - "where the first isn't half of the second", - DescribeNegation(m)); -} - -TEST(PointwiseTest, MakesCopyOfRhs) { - list rhs; - rhs.push_back(2); - rhs.push_back(4); - - int lhs[] = {1, 2}; - const Matcher m = Pointwise(IsHalfOf(), rhs); - EXPECT_THAT(lhs, m); - - // Changing rhs now shouldn't affect m, which made a copy of rhs. - rhs.push_back(6); - EXPECT_THAT(lhs, m); -} - -TEST(PointwiseTest, WorksForLhsNativeArray) { - const int lhs[] = {1, 2, 3}; - vector rhs; - rhs.push_back(2); - rhs.push_back(4); - rhs.push_back(6); - EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); - EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); -} - -TEST(PointwiseTest, WorksForRhsNativeArray) { - const int rhs[] = {1, 2, 3}; - vector lhs; - lhs.push_back(2); - lhs.push_back(4); - lhs.push_back(6); - EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); - EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); -} - -// Test is effective only with sanitizers. -TEST(PointwiseTest, WorksForVectorOfBool) { - vector rhs(3, false); - rhs[1] = true; - vector lhs = rhs; - EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); - rhs[0] = true; - EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); -} - - -TEST(PointwiseTest, WorksForRhsInitializerList) { - const vector lhs{2, 4, 6}; - EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3})); - EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7}))); -} - - -TEST(PointwiseTest, RejectsWrongSize) { - const double lhs[2] = {1, 2}; - const int rhs[1] = {0}; - EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); - EXPECT_EQ("which contains 2 values", - Explain(Pointwise(Gt(), rhs), lhs)); - - const int rhs2[3] = {0, 1, 2}; - EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); -} - -TEST(PointwiseTest, RejectsWrongContent) { - const double lhs[3] = {1, 2, 3}; - const int rhs[3] = {2, 6, 4}; - EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); - EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " - "where the second/2 is 3", - Explain(Pointwise(IsHalfOf(), rhs), lhs)); -} - -TEST(PointwiseTest, AcceptsCorrectContent) { - const double lhs[3] = {1, 2, 3}; - const int rhs[3] = {2, 4, 6}; - EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); - EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs)); -} - -TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { - const double lhs[3] = {1, 2, 3}; - const int rhs[3] = {2, 4, 6}; - const Matcher> m1 = IsHalfOf(); - EXPECT_THAT(lhs, Pointwise(m1, rhs)); - EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); - - // This type works as a std::tuple can be - // implicitly cast to std::tuple. - const Matcher> m2 = IsHalfOf(); - EXPECT_THAT(lhs, Pointwise(m2, rhs)); - EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); -} - -MATCHER(PointeeEquals, "Points to an equal value") { - return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)), - ::testing::get<0>(arg), result_listener); -} - -TEST(PointwiseTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector{1, 2}))); - helper.Call(MakeUniquePtrs({1, 2})); -} - -TEST(UnorderedPointwiseTest, DescribesSelf) { - vector rhs; - rhs.push_back(1); - rhs.push_back(2); - rhs.push_back(3); - const Matcher&> m = UnorderedPointwise(IsHalfOf(), rhs); - EXPECT_EQ( - "has 3 elements and there exists some permutation of elements such " - "that:\n" - " - element #0 and 1 are a pair where the first is half of the second, " - "and\n" - " - element #1 and 2 are a pair where the first is half of the second, " - "and\n" - " - element #2 and 3 are a pair where the first is half of the second", - Describe(m)); - EXPECT_EQ( - "doesn't have 3 elements, or there exists no permutation of elements " - "such that:\n" - " - element #0 and 1 are a pair where the first is half of the second, " - "and\n" - " - element #1 and 2 are a pair where the first is half of the second, " - "and\n" - " - element #2 and 3 are a pair where the first is half of the second", - DescribeNegation(m)); -} - -TEST(UnorderedPointwiseTest, MakesCopyOfRhs) { - list rhs; - rhs.push_back(2); - rhs.push_back(4); - - int lhs[] = {2, 1}; - const Matcher m = UnorderedPointwise(IsHalfOf(), rhs); - EXPECT_THAT(lhs, m); - - // Changing rhs now shouldn't affect m, which made a copy of rhs. - rhs.push_back(6); - EXPECT_THAT(lhs, m); -} - -TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) { - const int lhs[] = {1, 2, 3}; - vector rhs; - rhs.push_back(4); - rhs.push_back(6); - rhs.push_back(2); - EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs)); - EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); -} - -TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) { - const int rhs[] = {1, 2, 3}; - vector lhs; - lhs.push_back(4); - lhs.push_back(2); - lhs.push_back(6); - EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs)); - EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs))); -} - - -TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { - const vector lhs{2, 4, 6}; - EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3})); - EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7}))); -} - - -TEST(UnorderedPointwiseTest, RejectsWrongSize) { - const double lhs[2] = {1, 2}; - const int rhs[1] = {0}; - EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); - EXPECT_EQ("which has 2 elements", - Explain(UnorderedPointwise(Gt(), rhs), lhs)); - - const int rhs2[3] = {0, 1, 2}; - EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2))); -} - -TEST(UnorderedPointwiseTest, RejectsWrongContent) { - const double lhs[3] = {1, 2, 3}; - const int rhs[3] = {2, 6, 6}; - EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs))); - EXPECT_EQ("where the following elements don't match any matchers:\n" - "element #1: 2", - Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs)); -} - -TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) { - const double lhs[3] = {1, 2, 3}; - const int rhs[3] = {2, 4, 6}; - EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); -} - -TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) { - const double lhs[3] = {1, 2, 3}; - const int rhs[3] = {6, 4, 2}; - EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); -} - -TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { - const double lhs[3] = {1, 2, 3}; - const int rhs[3] = {4, 6, 2}; - const Matcher> m1 = IsHalfOf(); - EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); - - // This type works as a std::tuple can be - // implicitly cast to std::tuple. - const Matcher> m2 = IsHalfOf(); - EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); -} - -TEST(UnorderedPointwiseTest, WorksWithMoveOnly) { - ContainerHelper helper; - EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(), - std::vector{1, 2}))); - helper.Call(MakeUniquePtrs({2, 1})); -} - -// Sample optional type implementation with minimal requirements for use with -// Optional matcher. -template -class SampleOptional { - public: - using value_type = T; - explicit SampleOptional(T value) - : value_(std::move(value)), has_value_(true) {} - SampleOptional() : value_(), has_value_(false) {} - operator bool() const { return has_value_; } - const T& operator*() const { return value_; } - - private: - T value_; - bool has_value_; -}; - -TEST(OptionalTest, DescribesSelf) { - const Matcher> m = Optional(Eq(1)); - EXPECT_EQ("value is equal to 1", Describe(m)); -} - -TEST(OptionalTest, ExplainsSelf) { - const Matcher> m = Optional(Eq(1)); - EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional(1))); - EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional(2))); -} - -TEST(OptionalTest, MatchesNonEmptyOptional) { - const Matcher> m1 = Optional(1); - const Matcher> m2 = Optional(Eq(2)); - const Matcher> m3 = Optional(Lt(3)); - SampleOptional opt(1); - EXPECT_TRUE(m1.Matches(opt)); - EXPECT_FALSE(m2.Matches(opt)); - EXPECT_TRUE(m3.Matches(opt)); -} - -TEST(OptionalTest, DoesNotMatchNullopt) { - const Matcher> m = Optional(1); - SampleOptional empty; - EXPECT_FALSE(m.Matches(empty)); -} - -TEST(OptionalTest, WorksWithMoveOnly) { - Matcher>> m = Optional(Eq(nullptr)); - EXPECT_TRUE(m.Matches(SampleOptional>(nullptr))); -} - -class SampleVariantIntString { - public: - SampleVariantIntString(int i) : i_(i), has_int_(true) {} - SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} - - template - friend bool holds_alternative(const SampleVariantIntString& value) { - return value.has_int_ == std::is_same::value; - } - - template - friend const T& get(const SampleVariantIntString& value) { - return value.get_impl(static_cast(nullptr)); - } - - private: - const int& get_impl(int*) const { return i_; } - const std::string& get_impl(std::string*) const { return s_; } - - int i_; - std::string s_; - bool has_int_; -}; - -TEST(VariantTest, DescribesSelf) { - const Matcher m = VariantWith(Eq(1)); - EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " - "'.*' and the value is equal to 1")); -} - -TEST(VariantTest, ExplainsSelf) { - const Matcher m = VariantWith(Eq(1)); - EXPECT_THAT(Explain(m, SampleVariantIntString(1)), - ContainsRegex("whose value 1")); - EXPECT_THAT(Explain(m, SampleVariantIntString("A")), - HasSubstr("whose value is not of type '")); - EXPECT_THAT(Explain(m, SampleVariantIntString(2)), - "whose value 2 doesn't match"); -} - -TEST(VariantTest, FullMatch) { - Matcher m = VariantWith(Eq(1)); - EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); - - m = VariantWith(Eq("1")); - EXPECT_TRUE(m.Matches(SampleVariantIntString("1"))); -} - -TEST(VariantTest, TypeDoesNotMatch) { - Matcher m = VariantWith(Eq(1)); - EXPECT_FALSE(m.Matches(SampleVariantIntString("1"))); - - m = VariantWith(Eq("1")); - EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); -} - -TEST(VariantTest, InnerDoesNotMatch) { - Matcher m = VariantWith(Eq(1)); - EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); - - m = VariantWith(Eq("1")); - EXPECT_FALSE(m.Matches(SampleVariantIntString("2"))); -} - -class SampleAnyType { - public: - explicit SampleAnyType(int i) : index_(0), i_(i) {} - explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} - - template - friend const T* any_cast(const SampleAnyType* any) { - return any->get_impl(static_cast(nullptr)); - } - - private: - int index_; - int i_; - std::string s_; - - const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; } - const std::string* get_impl(std::string*) const { - return index_ == 1 ? &s_ : nullptr; - } -}; - -TEST(AnyWithTest, FullMatch) { - Matcher m = AnyWith(Eq(1)); - EXPECT_TRUE(m.Matches(SampleAnyType(1))); -} - -TEST(AnyWithTest, TestBadCastType) { - Matcher m = AnyWith(Eq("fail")); - EXPECT_FALSE(m.Matches(SampleAnyType(1))); -} - -TEST(AnyWithTest, TestUseInContainers) { - std::vector a; - a.emplace_back(1); - a.emplace_back(2); - a.emplace_back(3); - EXPECT_THAT( - a, ElementsAreArray({AnyWith(1), AnyWith(2), AnyWith(3)})); - - std::vector b; - b.emplace_back("hello"); - b.emplace_back("merhaba"); - b.emplace_back("salut"); - EXPECT_THAT(b, ElementsAreArray({AnyWith("hello"), - AnyWith("merhaba"), - AnyWith("salut")})); -} -TEST(AnyWithTest, TestCompare) { - EXPECT_THAT(SampleAnyType(1), AnyWith(Gt(0))); -} - -TEST(AnyWithTest, DescribesSelf) { - const Matcher m = AnyWith(Eq(1)); - EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " - "'.*' and the value is equal to 1")); -} - -TEST(AnyWithTest, ExplainsSelf) { - const Matcher m = AnyWith(Eq(1)); - - EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1")); - EXPECT_THAT(Explain(m, SampleAnyType("A")), - HasSubstr("whose value is not of type '")); - EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match"); -} - -TEST(PointeeTest, WorksOnMoveOnlyType) { - std::unique_ptr p(new int(3)); - EXPECT_THAT(p, Pointee(Eq(3))); - EXPECT_THAT(p, Not(Pointee(Eq(2)))); -} - -TEST(NotTest, WorksOnMoveOnlyType) { - std::unique_ptr p(new int(3)); - EXPECT_THAT(p, Pointee(Eq(3))); - EXPECT_THAT(p, Not(Pointee(Eq(2)))); -} - -// Tests Args(m). - -TEST(ArgsTest, AcceptsZeroTemplateArg) { - const std::tuple t(5, true); - EXPECT_THAT(t, Args<>(Eq(std::tuple<>()))); - EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>())))); -} - -TEST(ArgsTest, AcceptsOneTemplateArg) { - const std::tuple t(5, true); - EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5)))); - EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true)))); - EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false))))); -} - -TEST(ArgsTest, AcceptsTwoTemplateArgs) { - const std::tuple t(4, 5, 6L); // NOLINT - - EXPECT_THAT(t, (Args<0, 1>(Lt()))); - EXPECT_THAT(t, (Args<1, 2>(Lt()))); - EXPECT_THAT(t, Not(Args<0, 2>(Gt()))); -} - -TEST(ArgsTest, AcceptsRepeatedTemplateArgs) { - const std::tuple t(4, 5, 6L); // NOLINT - EXPECT_THAT(t, (Args<0, 0>(Eq()))); - EXPECT_THAT(t, Not(Args<1, 1>(Ne()))); -} - -TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { - const std::tuple t(4, 5, 6L); // NOLINT - EXPECT_THAT(t, (Args<2, 0>(Gt()))); - EXPECT_THAT(t, Not(Args<2, 1>(Lt()))); -} - -MATCHER(SumIsZero, "") { - return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0; -} - -TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) { - EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero()))); - EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero()))); -} - -TEST(ArgsTest, CanBeNested) { - const std::tuple t(4, 5, 6L, 6); // NOLINT - EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq())))); - EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt())))); -} - -TEST(ArgsTest, CanMatchTupleByValue) { - typedef std::tuple Tuple3; - const Matcher m = Args<1, 2>(Lt()); - EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2))); - EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2))); -} - -TEST(ArgsTest, CanMatchTupleByReference) { - typedef std::tuple Tuple3; - const Matcher m = Args<0, 1>(Lt()); - EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2))); - EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2))); -} - -// Validates that arg is printed as str. -MATCHER_P(PrintsAs, str, "") { - return testing::PrintToString(arg) == str; -} - -TEST(ArgsTest, AcceptsTenTemplateArgs) { - EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), - (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( - PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); - EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), - Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( - PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)")))); -} - -TEST(ArgsTest, DescirbesSelfCorrectly) { - const Matcher > m = Args<2, 0>(Lt()); - EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where " - "the first < the second", - Describe(m)); -} - -TEST(ArgsTest, DescirbesNestedArgsCorrectly) { - const Matcher&> m = - Args<0, 2, 3>(Args<2, 0>(Lt())); - EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple " - "whose fields (#2, #0) are a pair where the first < the second", - Describe(m)); -} - -TEST(ArgsTest, DescribesNegationCorrectly) { - const Matcher > m = Args<1, 0>(Gt()); - EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair " - "where the first > the second", - DescribeNegation(m)); -} - -TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) { - const Matcher > m = Args<1, 2>(Eq()); - EXPECT_EQ("whose fields (#1, #2) are (42, 42)", - Explain(m, std::make_tuple(false, 42, 42))); - EXPECT_EQ("whose fields (#1, #2) are (42, 43)", - Explain(m, std::make_tuple(false, 42, 43))); -} - -// For testing Args<>'s explanation. -class LessThanMatcher : public MatcherInterface > { - public: - void DescribeTo(::std::ostream* /*os*/) const override {} - - bool MatchAndExplain(std::tuple value, - MatchResultListener* listener) const override { - const int diff = std::get<0>(value) - std::get<1>(value); - if (diff > 0) { - *listener << "where the first value is " << diff - << " more than the second"; - } - return diff < 0; - } -}; - -Matcher > LessThan() { - return MakeMatcher(new LessThanMatcher); -} - -TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { - const Matcher > m = Args<0, 2>(LessThan()); - EXPECT_EQ( - "whose fields (#0, #2) are ('a' (97, 0x61), 42), " - "where the first value is 55 more than the second", - Explain(m, std::make_tuple('a', 42, 42))); - EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)", - Explain(m, std::make_tuple('\0', 42, 43))); -} - -class PredicateFormatterFromMatcherTest : public ::testing::Test { - protected: - enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky }; - - // A matcher that can return different results when used multiple times on the - // same input. No real matcher should do this; but this lets us test that we - // detect such behavior and fail appropriately. - class MockMatcher : public MatcherInterface { - public: - bool MatchAndExplain(Behavior behavior, - MatchResultListener* listener) const override { - *listener << "[MatchAndExplain]"; - switch (behavior) { - case kInitialSuccess: - // The first call to MatchAndExplain should use a "not interested" - // listener; so this is expected to return |true|. There should be no - // subsequent calls. - return !listener->IsInterested(); - - case kAlwaysFail: - return false; - - case kFlaky: - // The first call to MatchAndExplain should use a "not interested" - // listener; so this will return |false|. Subsequent calls should have - // an "interested" listener; so this will return |true|, thus - // simulating a flaky matcher. - return listener->IsInterested(); - } - - GTEST_LOG_(FATAL) << "This should never be reached"; - return false; - } - - void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; } - - void DescribeNegationTo(ostream* os) const override { - *os << "[DescribeNegationTo]"; - } - }; - - AssertionResult RunPredicateFormatter(Behavior behavior) { - auto matcher = MakeMatcher(new MockMatcher); - PredicateFormatterFromMatcher> predicate_formatter( - matcher); - return predicate_formatter("dummy-name", behavior); - } -}; - -TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) { - AssertionResult result = RunPredicateFormatter(kInitialSuccess); - EXPECT_TRUE(result); // Implicit cast to bool. - std::string expect; - EXPECT_EQ(expect, result.message()); -} - -TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) { - AssertionResult result = RunPredicateFormatter(kAlwaysFail); - EXPECT_FALSE(result); // Implicit cast to bool. - std::string expect = - "Value of: dummy-name\nExpected: [DescribeTo]\n" - " Actual: 1, [MatchAndExplain]"; - EXPECT_EQ(expect, result.message()); -} - -TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) { - AssertionResult result = RunPredicateFormatter(kFlaky); - EXPECT_FALSE(result); // Implicit cast to bool. - std::string expect = - "Value of: dummy-name\nExpected: [DescribeTo]\n" - " The matcher failed on the initial attempt; but passed when rerun to " - "generate the explanation.\n" - " Actual: 2, [MatchAndExplain]"; - EXPECT_EQ(expect, result.message()); -} - -} // namespace -} // namespace gmock_matchers_test -} // namespace testing - -#ifdef _MSC_VER -# pragma warning(pop) -#endif diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-more-actions_test.cc b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-more-actions_test.cc deleted file mode 100644 index 97ec5cf08..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/gmock-more-actions_test.cc +++ /dev/null @@ -1,698 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file tests the built-in actions in gmock-more-actions.h. - -#include "gmock/gmock-more-actions.h" - -#include -#include -#include -#include -#include "gmock/gmock.h" -#include "gtest/gtest.h" - -namespace testing { -namespace gmock_more_actions_test { - -using ::std::plus; -using ::std::string; -using testing::_; -using testing::Action; -using testing::ActionInterface; -using testing::DeleteArg; -using testing::Invoke; -using testing::Return; -using testing::ReturnArg; -using testing::ReturnPointee; -using testing::SaveArg; -using testing::SaveArgPointee; -using testing::SetArgReferee; -using testing::Unused; -using testing::WithArg; -using testing::WithoutArgs; - -// For suppressing compiler warnings on conversion possibly losing precision. -inline short Short(short n) { return n; } // NOLINT -inline char Char(char ch) { return ch; } - -// Sample functions and functors for testing Invoke() and etc. -int Nullary() { return 1; } - -class NullaryFunctor { - public: - int operator()() { return 2; } -}; - -bool g_done = false; -void VoidNullary() { g_done = true; } - -class VoidNullaryFunctor { - public: - void operator()() { g_done = true; } -}; - -bool Unary(int x) { return x < 0; } - -const char* Plus1(const char* s) { return s + 1; } - -void VoidUnary(int /* n */) { g_done = true; } - -bool ByConstRef(const std::string& s) { return s == "Hi"; } - -const double g_double = 0; -bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } - -std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT - -struct UnaryFunctor { - int operator()(bool x) { return x ? 1 : -1; } -}; - -const char* Binary(const char* input, short n) { return input + n; } // NOLINT - -void VoidBinary(int, char) { g_done = true; } - -int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT - -void VoidTernary(int, char, bool) { g_done = true; } - -int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } - -int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; } - -void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; } - -std::string Concat4(const char* s1, const char* s2, const char* s3, - const char* s4) { - return std::string(s1) + s2 + s3 + s4; -} - -int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } - -struct SumOf5Functor { - int operator()(int a, int b, int c, int d, int e) { - return a + b + c + d + e; - } -}; - -std::string Concat5(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5) { - return std::string(s1) + s2 + s3 + s4 + s5; -} - -int SumOf6(int a, int b, int c, int d, int e, int f) { - return a + b + c + d + e + f; -} - -struct SumOf6Functor { - int operator()(int a, int b, int c, int d, int e, int f) { - return a + b + c + d + e + f; - } -}; - -std::string Concat6(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6; -} - -std::string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; -} - -std::string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; -} - -std::string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; -} - -std::string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; -} - -class Foo { - public: - Foo() : value_(123) {} - - int Nullary() const { return value_; } - - short Unary(long x) { return static_cast(value_ + x); } // NOLINT - - std::string Binary(const std::string& str, char c) const { return str + c; } - - int Ternary(int x, bool y, char z) { return value_ + x + y*z; } - - int SumOf4(int a, int b, int c, int d) const { - return a + b + c + d + value_; - } - - int SumOfLast2(Unused, Unused, int a, int b) const { return a + b; } - - int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } - - int SumOf6(int a, int b, int c, int d, int e, int f) { - return a + b + c + d + e + f; - } - - std::string Concat7(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; - } - - std::string Concat8(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; - } - - std::string Concat9(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; - } - - std::string Concat10(const char* s1, const char* s2, const char* s3, - const char* s4, const char* s5, const char* s6, - const char* s7, const char* s8, const char* s9, - const char* s10) { - return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; - } - - private: - int value_; -}; - -// Tests using Invoke() with a nullary function. -TEST(InvokeTest, Nullary) { - Action a = Invoke(Nullary); // NOLINT - EXPECT_EQ(1, a.Perform(std::make_tuple())); -} - -// Tests using Invoke() with a unary function. -TEST(InvokeTest, Unary) { - Action a = Invoke(Unary); // NOLINT - EXPECT_FALSE(a.Perform(std::make_tuple(1))); - EXPECT_TRUE(a.Perform(std::make_tuple(-1))); -} - -// Tests using Invoke() with a binary function. -TEST(InvokeTest, Binary) { - Action a = Invoke(Binary); // NOLINT - const char* p = "Hello"; - EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2)))); -} - -// Tests using Invoke() with a ternary function. -TEST(InvokeTest, Ternary) { - Action a = Invoke(Ternary); // NOLINT - EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\2', Short(3)))); -} - -// Tests using Invoke() with a 4-argument function. -TEST(InvokeTest, FunctionThatTakes4Arguments) { - Action a = Invoke(SumOf4); // NOLINT - EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4))); -} - -// Tests using Invoke() with a 5-argument function. -TEST(InvokeTest, FunctionThatTakes5Arguments) { - Action a = Invoke(SumOf5); // NOLINT - EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); -} - -// Tests using Invoke() with a 6-argument function. -TEST(InvokeTest, FunctionThatTakes6Arguments) { - Action a = Invoke(SumOf6); // NOLINT - EXPECT_EQ(123456, - a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); -} - -// A helper that turns the type of a C-string literal from const -// char[N] to const char*. -inline const char* CharPtr(const char* s) { return s; } - -// Tests using Invoke() with a 7-argument function. -TEST(InvokeTest, FunctionThatTakes7Arguments) { - Action - a = Invoke(Concat7); - EXPECT_EQ("1234567", - a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7")))); -} - -// Tests using Invoke() with a 8-argument function. -TEST(InvokeTest, FunctionThatTakes8Arguments) { - Action - a = Invoke(Concat8); - EXPECT_EQ("12345678", - a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8")))); -} - -// Tests using Invoke() with a 9-argument function. -TEST(InvokeTest, FunctionThatTakes9Arguments) { - Action - a = Invoke(Concat9); - EXPECT_EQ("123456789", a.Perform(std::make_tuple( - CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9")))); -} - -// Tests using Invoke() with a 10-argument function. -TEST(InvokeTest, FunctionThatTakes10Arguments) { - Action - a = Invoke(Concat10); - EXPECT_EQ("1234567890", - a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9"), - CharPtr("0")))); -} - -// Tests using Invoke() with functions with parameters declared as Unused. -TEST(InvokeTest, FunctionWithUnusedParameters) { - Action a1 = Invoke(SumOfFirst2); - std::tuple dummy = - std::make_tuple(10, 2, 5.6, std::string("hi")); - EXPECT_EQ(12, a1.Perform(dummy)); - - Action a2 = - Invoke(SumOfFirst2); - EXPECT_EQ( - 23, a2.Perform(std::make_tuple(20, 3, true, static_cast(nullptr)))); -} - -// Tests using Invoke() with methods with parameters declared as Unused. -TEST(InvokeTest, MethodWithUnusedParameters) { - Foo foo; - Action a1 = Invoke(&foo, &Foo::SumOfLast2); - EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr("hi"), true, 10, 2))); - - Action a2 = - Invoke(&foo, &Foo::SumOfLast2); - EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3))); -} - -// Tests using Invoke() with a functor. -TEST(InvokeTest, Functor) { - Action a = Invoke(plus()); // NOLINT - EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2))); -} - -// Tests using Invoke(f) as an action of a compatible type. -TEST(InvokeTest, FunctionWithCompatibleType) { - Action a = Invoke(SumOf4); // NOLINT - EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); -} - -// Tests using Invoke() with an object pointer and a method pointer. - -// Tests using Invoke() with a nullary method. -TEST(InvokeMethodTest, Nullary) { - Foo foo; - Action a = Invoke(&foo, &Foo::Nullary); // NOLINT - EXPECT_EQ(123, a.Perform(std::make_tuple())); -} - -// Tests using Invoke() with a unary method. -TEST(InvokeMethodTest, Unary) { - Foo foo; - Action a = Invoke(&foo, &Foo::Unary); // NOLINT - EXPECT_EQ(4123, a.Perform(std::make_tuple(4000))); -} - -// Tests using Invoke() with a binary method. -TEST(InvokeMethodTest, Binary) { - Foo foo; - Action a = Invoke(&foo, &Foo::Binary); - std::string s("Hell"); - std::tuple dummy = std::make_tuple(s, 'o'); - EXPECT_EQ("Hello", a.Perform(dummy)); -} - -// Tests using Invoke() with a ternary method. -TEST(InvokeMethodTest, Ternary) { - Foo foo; - Action a = Invoke(&foo, &Foo::Ternary); // NOLINT - EXPECT_EQ(1124, a.Perform(std::make_tuple(1000, true, Char(1)))); -} - -// Tests using Invoke() with a 4-argument method. -TEST(InvokeMethodTest, MethodThatTakes4Arguments) { - Foo foo; - Action a = Invoke(&foo, &Foo::SumOf4); // NOLINT - EXPECT_EQ(1357, a.Perform(std::make_tuple(1000, 200, 30, 4))); -} - -// Tests using Invoke() with a 5-argument method. -TEST(InvokeMethodTest, MethodThatTakes5Arguments) { - Foo foo; - Action a = Invoke(&foo, &Foo::SumOf5); // NOLINT - EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5))); -} - -// Tests using Invoke() with a 6-argument method. -TEST(InvokeMethodTest, MethodThatTakes6Arguments) { - Foo foo; - Action a = // NOLINT - Invoke(&foo, &Foo::SumOf6); - EXPECT_EQ(123456, - a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6))); -} - -// Tests using Invoke() with a 7-argument method. -TEST(InvokeMethodTest, MethodThatTakes7Arguments) { - Foo foo; - Action - a = Invoke(&foo, &Foo::Concat7); - EXPECT_EQ("1234567", - a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7")))); -} - -// Tests using Invoke() with a 8-argument method. -TEST(InvokeMethodTest, MethodThatTakes8Arguments) { - Foo foo; - Action - a = Invoke(&foo, &Foo::Concat8); - EXPECT_EQ("12345678", - a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8")))); -} - -// Tests using Invoke() with a 9-argument method. -TEST(InvokeMethodTest, MethodThatTakes9Arguments) { - Foo foo; - Action - a = Invoke(&foo, &Foo::Concat9); - EXPECT_EQ("123456789", a.Perform(std::make_tuple( - CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9")))); -} - -// Tests using Invoke() with a 10-argument method. -TEST(InvokeMethodTest, MethodThatTakes10Arguments) { - Foo foo; - Action - a = Invoke(&foo, &Foo::Concat10); - EXPECT_EQ("1234567890", - a.Perform(std::make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"), - CharPtr("4"), CharPtr("5"), CharPtr("6"), - CharPtr("7"), CharPtr("8"), CharPtr("9"), - CharPtr("0")))); -} - -// Tests using Invoke(f) as an action of a compatible type. -TEST(InvokeMethodTest, MethodWithCompatibleType) { - Foo foo; - Action a = // NOLINT - Invoke(&foo, &Foo::SumOf4); - EXPECT_EQ(4444, a.Perform(std::make_tuple(4000, Short(300), Char(20), true))); -} - -// Tests using WithoutArgs with an action that takes no argument. -TEST(WithoutArgsTest, NoArg) { - Action a = WithoutArgs(Invoke(Nullary)); // NOLINT - EXPECT_EQ(1, a.Perform(std::make_tuple(2))); -} - -// Tests using WithArg with an action that takes 1 argument. -TEST(WithArgTest, OneArg) { - Action b = WithArg<1>(Invoke(Unary)); // NOLINT - EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1))); - EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1))); -} - -TEST(ReturnArgActionTest, WorksForOneArgIntArg0) { - const Action a = ReturnArg<0>(); - EXPECT_EQ(5, a.Perform(std::make_tuple(5))); -} - -TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) { - const Action a = ReturnArg<0>(); - EXPECT_TRUE(a.Perform(std::make_tuple(true, false, false))); -} - -TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) { - const Action a = ReturnArg<2>(); - EXPECT_EQ("seven", a.Perform(std::make_tuple(5, 6, std::string("seven"), 8))); -} - -TEST(SaveArgActionTest, WorksForSameType) { - int result = 0; - const Action a1 = SaveArg<0>(&result); - a1.Perform(std::make_tuple(5)); - EXPECT_EQ(5, result); -} - -TEST(SaveArgActionTest, WorksForCompatibleType) { - int result = 0; - const Action a1 = SaveArg<1>(&result); - a1.Perform(std::make_tuple(true, 'a')); - EXPECT_EQ('a', result); -} - -TEST(SaveArgPointeeActionTest, WorksForSameType) { - int result = 0; - const int value = 5; - const Action a1 = SaveArgPointee<0>(&result); - a1.Perform(std::make_tuple(&value)); - EXPECT_EQ(5, result); -} - -TEST(SaveArgPointeeActionTest, WorksForCompatibleType) { - int result = 0; - char value = 'a'; - const Action a1 = SaveArgPointee<1>(&result); - a1.Perform(std::make_tuple(true, &value)); - EXPECT_EQ('a', result); -} - -TEST(SetArgRefereeActionTest, WorksForSameType) { - int value = 0; - const Action a1 = SetArgReferee<0>(1); - a1.Perform(std::tuple(value)); - EXPECT_EQ(1, value); -} - -TEST(SetArgRefereeActionTest, WorksForCompatibleType) { - int value = 0; - const Action a1 = SetArgReferee<1>('a'); - a1.Perform(std::tuple(0, value)); - EXPECT_EQ('a', value); -} - -TEST(SetArgRefereeActionTest, WorksWithExtraArguments) { - int value = 0; - const Action a1 = SetArgReferee<2>('a'); - a1.Perform(std::tuple(true, 0, value, "hi")); - EXPECT_EQ('a', value); -} - -// A class that can be used to verify that its destructor is called: it will set -// the bool provided to the constructor to true when destroyed. -class DeletionTester { - public: - explicit DeletionTester(bool* is_deleted) - : is_deleted_(is_deleted) { - // Make sure the bit is set to false. - *is_deleted_ = false; - } - - ~DeletionTester() { - *is_deleted_ = true; - } - - private: - bool* is_deleted_; -}; - -TEST(DeleteArgActionTest, OneArg) { - bool is_deleted = false; - DeletionTester* t = new DeletionTester(&is_deleted); - const Action a1 = DeleteArg<0>(); // NOLINT - EXPECT_FALSE(is_deleted); - a1.Perform(std::make_tuple(t)); - EXPECT_TRUE(is_deleted); -} - -TEST(DeleteArgActionTest, TenArgs) { - bool is_deleted = false; - DeletionTester* t = new DeletionTester(&is_deleted); - const Action a1 = DeleteArg<9>(); - EXPECT_FALSE(is_deleted); - a1.Perform(std::make_tuple(true, 5, 6, CharPtr("hi"), false, 7, 8, 9, 10, t)); - EXPECT_TRUE(is_deleted); -} - -#if GTEST_HAS_EXCEPTIONS - -TEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) { - const Action a = Throw('a'); - EXPECT_THROW(a.Perform(std::make_tuple(0)), char); -} - -class MyException {}; - -TEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) { - const Action a = Throw(MyException()); - EXPECT_THROW(a.Perform(std::make_tuple('0')), MyException); -} - -TEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) { - const Action a = Throw(MyException()); - EXPECT_THROW(a.Perform(std::make_tuple()), MyException); -} - -#endif // GTEST_HAS_EXCEPTIONS - -// Tests that SetArrayArgument(first, last) sets the elements of the array -// pointed to by the N-th (0-based) argument to values in range [first, last). -TEST(SetArrayArgumentTest, SetsTheNthArray) { - typedef void MyFunction(bool, int*, char*); - int numbers[] = { 1, 2, 3 }; - Action a = SetArrayArgument<1>(numbers, numbers + 3); - - int n[4] = {}; - int* pn = n; - char ch[4] = {}; - char* pch = ch; - a.Perform(std::make_tuple(true, pn, pch)); - EXPECT_EQ(1, n[0]); - EXPECT_EQ(2, n[1]); - EXPECT_EQ(3, n[2]); - EXPECT_EQ(0, n[3]); - EXPECT_EQ('\0', ch[0]); - EXPECT_EQ('\0', ch[1]); - EXPECT_EQ('\0', ch[2]); - EXPECT_EQ('\0', ch[3]); - - // Tests first and last are iterators. - std::string letters = "abc"; - a = SetArrayArgument<2>(letters.begin(), letters.end()); - std::fill_n(n, 4, 0); - std::fill_n(ch, 4, '\0'); - a.Perform(std::make_tuple(true, pn, pch)); - EXPECT_EQ(0, n[0]); - EXPECT_EQ(0, n[1]); - EXPECT_EQ(0, n[2]); - EXPECT_EQ(0, n[3]); - EXPECT_EQ('a', ch[0]); - EXPECT_EQ('b', ch[1]); - EXPECT_EQ('c', ch[2]); - EXPECT_EQ('\0', ch[3]); -} - -// Tests SetArrayArgument(first, last) where first == last. -TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) { - typedef void MyFunction(bool, int*); - int numbers[] = { 1, 2, 3 }; - Action a = SetArrayArgument<1>(numbers, numbers); - - int n[4] = {}; - int* pn = n; - a.Perform(std::make_tuple(true, pn)); - EXPECT_EQ(0, n[0]); - EXPECT_EQ(0, n[1]); - EXPECT_EQ(0, n[2]); - EXPECT_EQ(0, n[3]); -} - -// Tests SetArrayArgument(first, last) where *first is convertible -// (but not equal) to the argument type. -TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) { - typedef void MyFunction(bool, int*); - char chars[] = { 97, 98, 99 }; - Action a = SetArrayArgument<1>(chars, chars + 3); - - int codes[4] = { 111, 222, 333, 444 }; - int* pcodes = codes; - a.Perform(std::make_tuple(true, pcodes)); - EXPECT_EQ(97, codes[0]); - EXPECT_EQ(98, codes[1]); - EXPECT_EQ(99, codes[2]); - EXPECT_EQ(444, codes[3]); -} - -// Test SetArrayArgument(first, last) with iterator as argument. -TEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) { - typedef void MyFunction(bool, std::back_insert_iterator); - std::string letters = "abc"; - Action a = SetArrayArgument<1>(letters.begin(), letters.end()); - - std::string s; - a.Perform(std::make_tuple(true, back_inserter(s))); - EXPECT_EQ(letters, s); -} - -TEST(ReturnPointeeTest, Works) { - int n = 42; - const Action a = ReturnPointee(&n); - EXPECT_EQ(42, a.Perform(std::make_tuple())); - - n = 43; - EXPECT_EQ(43, a.Perform(std::make_tuple())); -} - -} // namespace gmock_generated_actions_test -} // namespace testing diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/pump_test.py b/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/pump_test.py deleted file mode 100755 index eb5a13134..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/test/pump_test.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Tests for the Pump meta-programming tool.""" - -from google3.testing.pybase import googletest -import google3.third_party.googletest.googlemock.scripts.pump - -pump = google3.third_party.googletest.googlemock.scripts.pump -Convert = pump.ConvertFromPumpSource -StripMetaComments = pump.StripMetaComments - - -class PumpTest(googletest.TestCase): - - def testConvertsEmptyToEmpty(self): - self.assertEquals('', Convert('').strip()) - - def testConvertsPlainCodeToSame(self): - self.assertEquals('#include \n', - Convert('#include \n')) - - def testConvertsLongIWYUPragmaToSame(self): - long_line = '// IWYU pragma: private, include "' + (80*'a') + '.h"\n' - self.assertEquals(long_line, Convert(long_line)) - - def testConvertsIWYUPragmaWithLeadingSpaceToSame(self): - long_line = ' // IWYU pragma: private, include "' + (80*'a') + '.h"\n' - self.assertEquals(long_line, Convert(long_line)) - - def testConvertsIWYUPragmaWithSlashStarLeaderToSame(self): - long_line = '/* IWYU pragma: private, include "' + (80*'a') + '.h"\n' - self.assertEquals(long_line, Convert(long_line)) - - def testConvertsIWYUPragmaWithSlashStarAndSpacesToSame(self): - long_line = ' /* IWYU pragma: private, include "' + (80*'a') + '.h"\n' - self.assertEquals(long_line, Convert(long_line)) - - def testIgnoresMetaComment(self): - self.assertEquals('', - Convert('$$ This is a Pump meta comment.\n').strip()) - - def testSimpleVarDeclarationWorks(self): - self.assertEquals('3\n', - Convert('$var m = 3\n' - '$m\n')) - - def testVarDeclarationCanReferenceEarlierVar(self): - self.assertEquals('43 != 3;\n', - Convert('$var a = 42\n' - '$var b = a + 1\n' - '$var c = (b - a)*3\n' - '$b != $c;\n')) - - def testSimpleLoopWorks(self): - self.assertEquals('1, 2, 3, 4, 5\n', - Convert('$var n = 5\n' - '$range i 1..n\n' - '$for i, [[$i]]\n')) - - def testSimpleLoopWithCommentWorks(self): - self.assertEquals('1, 2, 3, 4, 5\n', - Convert('$var n = 5 $$ This is comment 1.\n' - '$range i 1..n $$ This is comment 2.\n' - '$for i, [[$i]]\n')) - - def testNonTrivialRangeExpressionsWork(self): - self.assertEquals('1, 2, 3, 4\n', - Convert('$var n = 5\n' - '$range i (n/n)..(n - 1)\n' - '$for i, [[$i]]\n')) - - def testLoopWithoutSeparatorWorks(self): - self.assertEquals('a + 1 + 2 + 3;\n', - Convert('$range i 1..3\n' - 'a$for i [[ + $i]];\n')) - - def testCanGenerateDollarSign(self): - self.assertEquals('$\n', Convert('$($)\n')) - - def testCanIterpolateExpressions(self): - self.assertEquals('a[2] = 3;\n', - Convert('$var i = 1\n' - 'a[$(i + 1)] = $(i*4 - 1);\n')) - - def testConditionalWithoutElseBranchWorks(self): - self.assertEquals('true\n', - Convert('$var n = 5\n' - '$if n > 0 [[true]]\n')) - - def testConditionalWithElseBranchWorks(self): - self.assertEquals('true -- really false\n', - Convert('$var n = 5\n' - '$if n > 0 [[true]]\n' - '$else [[false]] -- \n' - '$if n > 10 [[really true]]\n' - '$else [[really false]]\n')) - - def testConditionalWithCascadingElseBranchWorks(self): - self.assertEquals('a\n', - Convert('$var n = 5\n' - '$if n > 0 [[a]]\n' - '$elif n > 10 [[b]]\n' - '$else [[c]]\n')) - self.assertEquals('b\n', - Convert('$var n = 5\n' - '$if n > 10 [[a]]\n' - '$elif n > 0 [[b]]\n' - '$else [[c]]\n')) - self.assertEquals('c\n', - Convert('$var n = 5\n' - '$if n > 10 [[a]]\n' - '$elif n > 8 [[b]]\n' - '$else [[c]]\n')) - - def testNestedLexicalBlocksWork(self): - self.assertEquals('a = 5;\n', - Convert('$var n = 5\n' - 'a = [[$if n > 0 [[$n]]]];\n')) - - -class StripMetaCommentsTest(googletest.TestCase): - - def testReturnsSameStringIfItContainsNoComment(self): - self.assertEquals('', StripMetaComments('')) - self.assertEquals(' blah ', StripMetaComments(' blah ')) - self.assertEquals('A single $ is fine.', - StripMetaComments('A single $ is fine.')) - self.assertEquals('multiple\nlines', - StripMetaComments('multiple\nlines')) - - def testStripsSimpleComment(self): - self.assertEquals('yes\n', StripMetaComments('yes $$ or no?\n')) - - def testStripsSimpleCommentWithMissingNewline(self): - self.assertEquals('yes', StripMetaComments('yes $$ or no?')) - - def testStripsPureCommentLinesEntirely(self): - self.assertEquals('yes\n', - StripMetaComments('$$ a pure comment line.\n' - 'yes $$ or no?\n' - ' $$ another comment line.\n')) - - def testStripsCommentsFromMultiLineText(self): - self.assertEquals('multi-\n' - 'line\n' - 'text is fine.', - StripMetaComments('multi- $$ comment 1\n' - 'line\n' - 'text is fine. $$ comment 2')) - - -if __name__ == '__main__': - googletest.main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/LICENSE b/thirdparty_builtin/googletest-master-2020-01-07/googletest/LICENSE deleted file mode 100644 index 1941a11f8..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2008, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/README.md b/thirdparty_builtin/googletest-master-2020-01-07/googletest/README.md deleted file mode 100644 index 904048f48..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/README.md +++ /dev/null @@ -1,244 +0,0 @@ -### Generic Build Instructions - -#### Setup - -To build Google Test and your tests that use it, you need to tell your build -system where to find its headers and source files. The exact way to do it -depends on which build system you use, and is usually straightforward. - -### Build with CMake - -Google Test comes with a CMake build script -([CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt)) -that can be used on a wide range of platforms ("C" stands for cross-platform.). -If you don't have CMake installed already, you can download it for free from -. - -CMake works by generating native makefiles or build projects that can be used in -the compiler environment of your choice. You can either build Google Test as a -standalone project or it can be incorporated into an existing CMake build for -another project. - -#### Standalone CMake Project - -When building Google Test as a standalone project, the typical workflow starts -with: - - mkdir mybuild # Create a directory to hold the build output. - cd mybuild - cmake ${GTEST_DIR} # Generate native build scripts. - -If you want to build Google Test's samples, you should replace the last command -with - - cmake -Dgtest_build_samples=ON ${GTEST_DIR} - -If you are on a \*nix system, you should now see a Makefile in the current -directory. Just type 'make' to build gtest. - -If you use Windows and have Visual Studio installed, a `gtest.sln` file and -several `.vcproj` files will be created. You can then build them using Visual -Studio. - -On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated. - -#### Incorporating Into An Existing CMake Project - -If you want to use gtest in a project which already uses CMake, then a more -robust and flexible approach is to build gtest as part of that project directly. -This is done by making the GoogleTest source code available to the main build -and adding it using CMake's `add_subdirectory()` command. This has the -significant advantage that the same compiler and linker settings are used -between gtest and the rest of your project, so issues associated with using -incompatible libraries (eg debug/release), etc. are avoided. This is -particularly useful on Windows. Making GoogleTest's source code available to the -main build can be done a few different ways: - -* Download the GoogleTest source code manually and place it at a known - location. This is the least flexible approach and can make it more difficult - to use with continuous integration systems, etc. -* Embed the GoogleTest source code as a direct copy in the main project's - source tree. This is often the simplest approach, but is also the hardest to - keep up to date. Some organizations may not permit this method. -* Add GoogleTest as a git submodule or equivalent. This may not always be - possible or appropriate. Git submodules, for example, have their own set of - advantages and drawbacks. -* Use CMake to download GoogleTest as part of the build's configure step. This - is just a little more complex, but doesn't have the limitations of the other - methods. - -The last of the above methods is implemented with a small piece of CMake code in -a separate file (e.g. `CMakeLists.txt.in`) which is copied to the build area and -then invoked as a sub-build _during the CMake stage_. That directory is then -pulled into the main build with `add_subdirectory()`. For example: - -New file `CMakeLists.txt.in`: - -```cmake -cmake_minimum_required(VERSION 2.8.2) - -project(googletest-download NONE) - -include(ExternalProject) -ExternalProject_Add(googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG master - SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-src" - BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/googletest-build" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - TEST_COMMAND "" -) -``` - -Existing build's `CMakeLists.txt`: - -```cmake -# Download and unpack googletest at configure time -configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) -execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . - RESULT_VARIABLE result - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download ) -if(result) - message(FATAL_ERROR "CMake step for googletest failed: ${result}") -endif() -execute_process(COMMAND ${CMAKE_COMMAND} --build . - RESULT_VARIABLE result - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download ) -if(result) - message(FATAL_ERROR "Build step for googletest failed: ${result}") -endif() - -# Prevent overriding the parent project's compiler/linker -# settings on Windows -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - -# Add googletest directly to our build. This defines -# the gtest and gtest_main targets. -add_subdirectory(${CMAKE_CURRENT_BINARY_DIR}/googletest-src - ${CMAKE_CURRENT_BINARY_DIR}/googletest-build - EXCLUDE_FROM_ALL) - -# The gtest/gtest_main targets carry header search path -# dependencies automatically when using CMake 2.8.11 or -# later. Otherwise we have to add them here ourselves. -if (CMAKE_VERSION VERSION_LESS 2.8.11) - include_directories("${gtest_SOURCE_DIR}/include") -endif() - -# Now simply link against gtest or gtest_main as needed. Eg -add_executable(example example.cpp) -target_link_libraries(example gtest_main) -add_test(NAME example_test COMMAND example) -``` - -Note that this approach requires CMake 2.8.2 or later due to its use of the -`ExternalProject_Add()` command. The above technique is discussed in more detail -in [this separate article](http://crascit.com/2015/07/25/cmake-gtest/) which -also contains a link to a fully generalized implementation of the technique. - -##### Visual Studio Dynamic vs Static Runtimes - -By default, new Visual Studio projects link the C runtimes dynamically but -Google Test links them statically. This will generate an error that looks -something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch -detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value -'MDd_DynamicDebug' in main.obj - -Google Test already has a CMake option for this: `gtest_force_shared_crt` - -Enabling this option will make gtest link the runtimes dynamically too, and -match the project in which it is included. - -#### C++ Standard Version - -An environment that supports C++11 is required in order to successfully build -Google Test. One way to ensure this is to specify the standard in the top-level -project, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this -is not feasible, for example in a C project using Google Test for validation, -then it can be specified by adding it to the options for cmake via the -`DCMAKE_CXX_FLAGS` option. - -### Tweaking Google Test - -Google Test can be used in diverse environments. The default configuration may -not work (or may not work well) out of the box in some environments. However, -you can easily tweak Google Test by defining control macros on the compiler -command line. Generally, these macros are named like `GTEST_XYZ` and you define -them to either 1 or 0 to enable or disable a certain feature. - -We list the most frequently used macros below. For a complete list, see file -[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-port.h). - -### Multi-threaded Tests - -Google Test is thread-safe where the pthread library is available. After -`#include "gtest/gtest.h"`, you can check the -`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is -`#defined` to 1, no if it's undefined.). - -If Google Test doesn't correctly detect whether pthread is available in your -environment, you can force it with - - -DGTEST_HAS_PTHREAD=1 - -or - - -DGTEST_HAS_PTHREAD=0 - -When Google Test uses pthread, you may need to add flags to your compiler and/or -linker to select the pthread library, or you'll get link errors. If you use the -CMake script or the deprecated Autotools script, this is taken care of for you. -If you use your own build script, you'll need to read your compiler and linker's -manual to figure out what flags to add. - -### As a Shared Library (DLL) - -Google Test is compact, so most users can build and link it as a static library -for the simplicity. You can choose to use Google Test as a shared library (known -as a DLL on Windows) if you prefer. - -To compile *gtest* as a shared library, add - - -DGTEST_CREATE_SHARED_LIBRARY=1 - -to the compiler flags. You'll also need to tell the linker to produce a shared -library instead - consult your linker's manual for how to do it. - -To compile your *tests* that use the gtest shared library, add - - -DGTEST_LINKED_AS_SHARED_LIBRARY=1 - -to the compiler flags. - -Note: while the above steps aren't technically necessary today when using some -compilers (e.g. GCC), they may become necessary in the future, if we decide to -improve the speed of loading the library (see - for details). Therefore you are recommended -to always add the above flags when using Google Test as a shared library. -Otherwise a future release of Google Test may break your build script. - -### Avoiding Macro Name Clashes - -In C++, macros don't obey namespaces. Therefore two libraries that both define a -macro of the same name will clash if you `#include` both definitions. In case a -Google Test macro clashes with another library, you can force Google Test to -rename its macro to avoid the conflict. - -Specifically, if both Google Test and some other code define macro FOO, you can -add - - -DGTEST_DONT_DEFINE_FOO=1 - -to the compiler flags to tell Google Test to change the macro's name from `FOO` -to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For -example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write - - GTEST_TEST(SomeTest, DoesThis) { ... } - -instead of - - TEST(SomeTest, DoesThis) { ... } - -in order to define a test. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/README.md b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/README.md deleted file mode 100644 index fa359fed9..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Please Note: - -Files in this directory are no longer supported by the maintainers. They -represent mosty historical artifacts and supported by the community only. There -is no guarantee whatsoever that these scripts still work. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/common.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/common.py deleted file mode 100644 index 3c0347a75..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/common.py +++ /dev/null @@ -1,83 +0,0 @@ -# Copyright 2013 Google Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Shared utilities for writing scripts for Google Test/Mock.""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - - -import os -import re - - -# Matches the line from 'svn info .' output that describes what SVN -# path the current local directory corresponds to. For example, in -# a googletest SVN workspace's trunk/test directory, the output will be: -# -# URL: https://googletest.googlecode.com/svn/trunk/test -_SVN_INFO_URL_RE = re.compile(r'^URL: https://(\w+)\.googlecode\.com/svn(.*)') - - -def GetCommandOutput(command): - """Runs the shell command and returns its stdout as a list of lines.""" - - f = os.popen(command, 'r') - lines = [line.strip() for line in f.readlines()] - f.close() - return lines - - -def GetSvnInfo(): - """Returns the project name and the current SVN workspace's root path.""" - - for line in GetCommandOutput('svn info .'): - m = _SVN_INFO_URL_RE.match(line) - if m: - project = m.group(1) # googletest or googlemock - rel_path = m.group(2) - root = os.path.realpath(rel_path.count('/') * '../') - return project, root - - return None, None - - -def GetSvnTrunk(): - """Returns the current SVN workspace's trunk root path.""" - - _, root = GetSvnInfo() - return root + '/trunk' if root else None - - -def IsInGTestSvn(): - project, _ = GetSvnInfo() - return project == 'googletest' - - -def IsInGMockSvn(): - project, _ = GetSvnInfo() - return project == 'googlemock' diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/fuse_gtest_files.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/fuse_gtest_files.py deleted file mode 100755 index d0dd464fe..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/fuse_gtest_files.py +++ /dev/null @@ -1,253 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""fuse_gtest_files.py v0.2.0 -Fuses Google Test source code into a .h file and a .cc file. - -SYNOPSIS - fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR - - Scans GTEST_ROOT_DIR for Google Test source code, and generates - two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc. - Then you can build your tests by adding OUTPUT_DIR to the include - search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These - two files contain everything you need to use Google Test. Hence - you can "install" Google Test by copying them to wherever you want. - - GTEST_ROOT_DIR can be omitted and defaults to the parent - directory of the directory holding this script. - -EXAMPLES - ./fuse_gtest_files.py fused_gtest - ./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest - -This tool is experimental. In particular, it assumes that there is no -conditional inclusion of Google Test headers. Please report any -problems to googletestframework@googlegroups.com. You can read -https://github.com/google/googletest/blob/master/googletest/docs/advanced.md for -more information. -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import re -try: - from sets import Set as set # For Python 2.3 compatibility -except ImportError: - pass -import sys - -# We assume that this file is in the scripts/ directory in the Google -# Test root directory. -DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') - -# Regex for matching '#include "gtest/..."'. -INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"') - -# Regex for matching '#include "src/..."'. -INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"') - -# Where to find the source seed files. -GTEST_H_SEED = 'include/gtest/gtest.h' -GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h' -GTEST_ALL_CC_SEED = 'src/gtest-all.cc' - -# Where to put the generated files. -GTEST_H_OUTPUT = 'gtest/gtest.h' -GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc' - - -def VerifyFileExists(directory, relative_path): - """Verifies that the given file exists; aborts on failure. - - relative_path is the file path relative to the given directory. - """ - - if not os.path.isfile(os.path.join(directory, relative_path)): - print('ERROR: Cannot find %s in directory %s.' % (relative_path, - directory)) - print('Please either specify a valid project root directory ' - 'or omit it on the command line.') - sys.exit(1) - - -def ValidateGTestRootDir(gtest_root): - """Makes sure gtest_root points to a valid gtest root directory. - - The function aborts the program on failure. - """ - - VerifyFileExists(gtest_root, GTEST_H_SEED) - VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED) - - -def VerifyOutputFile(output_dir, relative_path): - """Verifies that the given output file path is valid. - - relative_path is relative to the output_dir directory. - """ - - # Makes sure the output file either doesn't exist or can be overwritten. - output_file = os.path.join(output_dir, relative_path) - if os.path.exists(output_file): - # TODO(wan@google.com): The following user-interaction doesn't - # work with automated processes. We should provide a way for the - # Makefile to force overwriting the files. - print('%s already exists in directory %s - overwrite it? (y/N) ' % - (relative_path, output_dir)) - answer = sys.stdin.readline().strip() - if answer not in ['y', 'Y']: - print('ABORTED.') - sys.exit(1) - - # Makes sure the directory holding the output file exists; creates - # it and all its ancestors if necessary. - parent_directory = os.path.dirname(output_file) - if not os.path.isdir(parent_directory): - os.makedirs(parent_directory) - - -def ValidateOutputDir(output_dir): - """Makes sure output_dir points to a valid output directory. - - The function aborts the program on failure. - """ - - VerifyOutputFile(output_dir, GTEST_H_OUTPUT) - VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT) - - -def FuseGTestH(gtest_root, output_dir): - """Scans folder gtest_root to generate gtest/gtest.h in output_dir.""" - - output_file = open(os.path.join(output_dir, GTEST_H_OUTPUT), 'w') - processed_files = set() # Holds all gtest headers we've processed. - - def ProcessFile(gtest_header_path): - """Processes the given gtest header file.""" - - # We don't process the same header twice. - if gtest_header_path in processed_files: - return - - processed_files.add(gtest_header_path) - - # Reads each line in the given gtest header. - for line in open(os.path.join(gtest_root, gtest_header_path), 'r'): - m = INCLUDE_GTEST_FILE_REGEX.match(line) - if m: - # It's '#include "gtest/..."' - let's process it recursively. - ProcessFile('include/' + m.group(1)) - else: - # Otherwise we copy the line unchanged to the output file. - output_file.write(line) - - ProcessFile(GTEST_H_SEED) - output_file.close() - - -def FuseGTestAllCcToFile(gtest_root, output_file): - """Scans folder gtest_root to generate gtest/gtest-all.cc in output_file.""" - - processed_files = set() - - def ProcessFile(gtest_source_file): - """Processes the given gtest source file.""" - - # We don't process the same #included file twice. - if gtest_source_file in processed_files: - return - - processed_files.add(gtest_source_file) - - # Reads each line in the given gtest source file. - for line in open(os.path.join(gtest_root, gtest_source_file), 'r'): - m = INCLUDE_GTEST_FILE_REGEX.match(line) - if m: - if 'include/' + m.group(1) == GTEST_SPI_H_SEED: - # It's '#include "gtest/gtest-spi.h"'. This file is not - # #included by "gtest/gtest.h", so we need to process it. - ProcessFile(GTEST_SPI_H_SEED) - else: - # It's '#include "gtest/foo.h"' where foo is not gtest-spi. - # We treat it as '#include "gtest/gtest.h"', as all other - # gtest headers are being fused into gtest.h and cannot be - # #included directly. - - # There is no need to #include "gtest/gtest.h" more than once. - if not GTEST_H_SEED in processed_files: - processed_files.add(GTEST_H_SEED) - output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,)) - else: - m = INCLUDE_SRC_FILE_REGEX.match(line) - if m: - # It's '#include "src/foo"' - let's process it recursively. - ProcessFile(m.group(1)) - else: - output_file.write(line) - - ProcessFile(GTEST_ALL_CC_SEED) - - -def FuseGTestAllCc(gtest_root, output_dir): - """Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir.""" - - output_file = open(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w') - FuseGTestAllCcToFile(gtest_root, output_file) - output_file.close() - - -def FuseGTest(gtest_root, output_dir): - """Fuses gtest.h and gtest-all.cc.""" - - ValidateGTestRootDir(gtest_root) - ValidateOutputDir(output_dir) - - FuseGTestH(gtest_root, output_dir) - FuseGTestAllCc(gtest_root, output_dir) - - -def main(): - argc = len(sys.argv) - if argc == 2: - # fuse_gtest_files.py OUTPUT_DIR - FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1]) - elif argc == 3: - # fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR - FuseGTest(sys.argv[1], sys.argv[2]) - else: - print(__doc__) - sys.exit(1) - - -if __name__ == '__main__': - main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/gen_gtest_pred_impl.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/gen_gtest_pred_impl.py deleted file mode 100755 index e09a6e017..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/gen_gtest_pred_impl.py +++ /dev/null @@ -1,733 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2006, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""gen_gtest_pred_impl.py v0.1 - -Generates the implementation of Google Test predicate assertions and -accompanying tests. - -Usage: - - gen_gtest_pred_impl.py MAX_ARITY - -where MAX_ARITY is a positive integer. - -The command generates the implementation of up-to MAX_ARITY-ary -predicate assertions, and writes it to file gtest_pred_impl.h in the -directory where the script is. It also generates the accompanying -unit test in file gtest_pred_impl_unittest.cc. -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import sys -import time - -# Where this script is. -SCRIPT_DIR = os.path.dirname(sys.argv[0]) - -# Where to store the generated header. -HEADER = os.path.join(SCRIPT_DIR, '../include/gtest/gtest_pred_impl.h') - -# Where to store the generated unit test. -UNIT_TEST = os.path.join(SCRIPT_DIR, '../test/gtest_pred_impl_unittest.cc') - - -def HeaderPreamble(n): - """Returns the preamble for the header file. - - Args: - n: the maximum arity of the predicate macros to be generated. - """ - - # A map that defines the values used in the preamble template. - DEFS = { - 'today' : time.strftime('%m/%d/%Y'), - 'year' : time.strftime('%Y'), - 'command' : '%s %s' % (os.path.basename(sys.argv[0]), n), - 'n' : n - } - - return ( - """// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is AUTOMATICALLY GENERATED on %(today)s by command -// '%(command)s'. DO NOT EDIT BY HAND! -// -// Implements a family of generic predicate assertion macros. -// GOOGLETEST_CM0001 DO NOT DELETE - - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ - -#include "gtest/gtest.h" - -namespace testing { - -// This header implements a family of generic predicate assertion -// macros: -// -// ASSERT_PRED_FORMAT1(pred_format, v1) -// ASSERT_PRED_FORMAT2(pred_format, v1, v2) -// ... -// -// where pred_format is a function or functor that takes n (in the -// case of ASSERT_PRED_FORMATn) values and their source expression -// text, and returns a testing::AssertionResult. See the definition -// of ASSERT_EQ in gtest.h for an example. -// -// If you don't care about formatting, you can use the more -// restrictive version: -// -// ASSERT_PRED1(pred, v1) -// ASSERT_PRED2(pred, v1, v2) -// ... -// -// where pred is an n-ary function or functor that returns bool, -// and the values v1, v2, ..., must support the << operator for -// streaming to std::ostream. -// -// We also define the EXPECT_* variations. -// -// For now we only support predicates whose arity is at most %(n)s. -// Please email googletestframework@googlegroups.com if you need -// support for higher arities. - -// GTEST_ASSERT_ is the basic statement to which all of the assertions -// in this file reduce. Don't use this in your code. - -#define GTEST_ASSERT_(expression, on_failure) \\ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\ - if (const ::testing::AssertionResult gtest_ar = (expression)) \\ - ; \\ - else \\ - on_failure(gtest_ar.failure_message()) -""" % DEFS) - - -def Arity(n): - """Returns the English name of the given arity.""" - - if n < 0: - return None - elif n <= 3: - return ['nullary', 'unary', 'binary', 'ternary'][n] - else: - return '%s-ary' % n - - -def Title(word): - """Returns the given word in title case. The difference between - this and string's title() method is that Title('4-ary') is '4-ary' - while '4-ary'.title() is '4-Ary'.""" - - return word[0].upper() + word[1:] - - -def OneTo(n): - """Returns the list [1, 2, 3, ..., n].""" - - return range(1, n + 1) - - -def Iter(n, format, sep=''): - """Given a positive integer n, a format string that contains 0 or - more '%s' format specs, and optionally a separator string, returns - the join of n strings, each formatted with the format string on an - iterator ranged from 1 to n. - - Example: - - Iter(3, 'v%s', sep=', ') returns 'v1, v2, v3'. - """ - - # How many '%s' specs are in format? - spec_count = len(format.split('%s')) - 1 - return sep.join([format % (spec_count * (i,)) for i in OneTo(n)]) - - -def ImplementationForArity(n): - """Returns the implementation of n-ary predicate assertions.""" - - # A map the defines the values used in the implementation template. - DEFS = { - 'n' : str(n), - 'vs' : Iter(n, 'v%s', sep=', '), - 'vts' : Iter(n, '#v%s', sep=', '), - 'arity' : Arity(n), - 'Arity' : Title(Arity(n)) - } - - impl = """ - -// Helper function for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use -// this in your code. -template -AssertionResult AssertPred%(n)sHelper(const char* pred_text""" % DEFS - - impl += Iter(n, """, - const char* e%s""") - - impl += """, - Pred pred""" - - impl += Iter(n, """, - const T%s& v%s""") - - impl += """) { - if (pred(%(vs)s)) return AssertionSuccess(); - -""" % DEFS - - impl += ' return AssertionFailure() << pred_text << "("' - - impl += Iter(n, """ - << e%s""", sep=' << ", "') - - impl += ' << ") evaluates to false, where"' - - impl += Iter( - n, """ - << "\\n" << e%s << " evaluates to " << ::testing::PrintToString(v%s)""" - ) - - impl += """; -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT%(n)s. -// Don't use this in your code. -#define GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, on_failure)\\ - GTEST_ASSERT_(pred_format(%(vts)s, %(vs)s), \\ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED%(n)s. Don't use -// this in your code. -#define GTEST_PRED%(n)s_(pred, %(vs)s, on_failure)\\ - GTEST_ASSERT_(::testing::AssertPred%(n)sHelper(#pred""" % DEFS - - impl += Iter(n, """, \\ - #v%s""") - - impl += """, \\ - pred""" - - impl += Iter(n, """, \\ - v%s""") - - impl += """), on_failure) - -// %(Arity)s predicate assertion macros. -#define EXPECT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\ - GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED%(n)s(pred, %(vs)s) \\ - GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT%(n)s(pred_format, %(vs)s) \\ - GTEST_PRED_FORMAT%(n)s_(pred_format, %(vs)s, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED%(n)s(pred, %(vs)s) \\ - GTEST_PRED%(n)s_(pred, %(vs)s, GTEST_FATAL_FAILURE_) - -""" % DEFS - - return impl - - -def HeaderPostamble(): - """Returns the postamble for the header file.""" - - return """ - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ -""" - - -def GenerateFile(path, content): - """Given a file path and a content string - overwrites it with the given content. - """ - print 'Updating file %s . . .' % path - f = file(path, 'w+') - print >>f, content, - f.close() - - print 'File %s has been updated.' % path - - -def GenerateHeader(n): - """Given the maximum arity n, updates the header file that implements - the predicate assertions. - """ - GenerateFile(HEADER, - HeaderPreamble(n) - + ''.join([ImplementationForArity(i) for i in OneTo(n)]) - + HeaderPostamble()) - - -def UnitTestPreamble(): - """Returns the preamble for the unit test file.""" - - # A map that defines the values used in the preamble template. - DEFS = { - 'today' : time.strftime('%m/%d/%Y'), - 'year' : time.strftime('%Y'), - 'command' : '%s %s' % (os.path.basename(sys.argv[0]), sys.argv[1]), - } - - return ( - """// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is AUTOMATICALLY GENERATED on %(today)s by command -// '%(command)s'. DO NOT EDIT BY HAND! - -// Regression test for gtest_pred_impl.h -// -// This file is generated by a script and quite long. If you intend to -// learn how Google Test works by reading its unit tests, read -// gtest_unittest.cc instead. -// -// This is intended as a regression test for the Google Test predicate -// assertions. We compile it as part of the gtest_unittest target -// only to keep the implementation tidy and compact, as it is quite -// involved to set up the stage for testing Google Test using Google -// Test itself. -// -// Currently, gtest_unittest takes ~11 seconds to run in the testing -// daemon. In the future, if it grows too large and needs much more -// time to finish, we should consider separating this file into a -// stand-alone regression test. - -#include - -#include "gtest/gtest.h" -#include "gtest/gtest-spi.h" - -// A user-defined data type. -struct Bool { - explicit Bool(int val) : value(val != 0) {} - - bool operator>(int n) const { return value > Bool(n).value; } - - Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); } - - bool operator==(const Bool& rhs) const { return value == rhs.value; } - - bool value; -}; - -// Enables Bool to be used in assertions. -std::ostream& operator<<(std::ostream& os, const Bool& x) { - return os << (x.value ? "true" : "false"); -} - -""" % DEFS) - - -def TestsForArity(n): - """Returns the tests for n-ary predicate assertions.""" - - # A map that defines the values used in the template for the tests. - DEFS = { - 'n' : n, - 'es' : Iter(n, 'e%s', sep=', '), - 'vs' : Iter(n, 'v%s', sep=', '), - 'vts' : Iter(n, '#v%s', sep=', '), - 'tvs' : Iter(n, 'T%s v%s', sep=', '), - 'int_vs' : Iter(n, 'int v%s', sep=', '), - 'Bool_vs' : Iter(n, 'Bool v%s', sep=', '), - 'types' : Iter(n, 'typename T%s', sep=', '), - 'v_sum' : Iter(n, 'v%s', sep=' + '), - 'arity' : Arity(n), - 'Arity' : Title(Arity(n)), - } - - tests = ( - """// Sample functions/functors for testing %(arity)s predicate assertions. - -// A %(arity)s predicate function. -template <%(types)s> -bool PredFunction%(n)s(%(tvs)s) { - return %(v_sum)s > 0; -} - -// The following two functions are needed because a compiler doesn't have -// a context yet to know which template function must be instantiated. -bool PredFunction%(n)sInt(%(int_vs)s) { - return %(v_sum)s > 0; -} -bool PredFunction%(n)sBool(%(Bool_vs)s) { - return %(v_sum)s > 0; -} -""" % DEFS) - - tests += """ -// A %(arity)s predicate functor. -struct PredFunctor%(n)s { - template <%(types)s> - bool operator()(""" % DEFS - - tests += Iter(n, 'const T%s& v%s', sep=""", - """) - - tests += """) { - return %(v_sum)s > 0; - } -}; -""" % DEFS - - tests += """ -// A %(arity)s predicate-formatter function. -template <%(types)s> -testing::AssertionResult PredFormatFunction%(n)s(""" % DEFS - - tests += Iter(n, 'const char* e%s', sep=""", - """) - - tests += Iter(n, """, - const T%s& v%s""") - - tests += """) { - if (PredFunction%(n)s(%(vs)s)) - return testing::AssertionSuccess(); - - return testing::AssertionFailure() - << """ % DEFS - - tests += Iter(n, 'e%s', sep=' << " + " << ') - - tests += """ - << " is expected to be positive, but evaluates to " - << %(v_sum)s << "."; -} -""" % DEFS - - tests += """ -// A %(arity)s predicate-formatter functor. -struct PredFormatFunctor%(n)s { - template <%(types)s> - testing::AssertionResult operator()(""" % DEFS - - tests += Iter(n, 'const char* e%s', sep=""", - """) - - tests += Iter(n, """, - const T%s& v%s""") - - tests += """) const { - return PredFormatFunction%(n)s(%(es)s, %(vs)s); - } -}; -""" % DEFS - - tests += """ -// Tests for {EXPECT|ASSERT}_PRED_FORMAT%(n)s. - -class Predicate%(n)sTest : public testing::Test { - protected: - void SetUp() override { - expected_to_finish_ = true; - finished_ = false;""" % DEFS - - tests += """ - """ + Iter(n, 'n%s_ = ') + """0; - } -""" - - tests += """ - void TearDown() override { - // Verifies that each of the predicate's arguments was evaluated - // exactly once.""" - - tests += ''.join([""" - EXPECT_EQ(1, n%s_) << - "The predicate assertion didn't evaluate argument %s " - "exactly once.";""" % (i, i + 1) for i in OneTo(n)]) - - tests += """ - - // Verifies that the control flow in the test function is expected. - if (expected_to_finish_ && !finished_) { - FAIL() << "The predicate assertion unexpactedly aborted the test."; - } else if (!expected_to_finish_ && finished_) { - FAIL() << "The failed predicate assertion didn't abort the test " - "as expected."; - } - } - - // true if and only if the test function is expected to run to finish. - static bool expected_to_finish_; - - // true if and only if the test function did run to finish. - static bool finished_; -""" % DEFS - - tests += Iter(n, """ - static int n%s_;""") - - tests += """ -}; - -bool Predicate%(n)sTest::expected_to_finish_; -bool Predicate%(n)sTest::finished_; -""" % DEFS - - tests += Iter(n, """int Predicate%%(n)sTest::n%s_; -""") % DEFS - - tests += """ -typedef Predicate%(n)sTest EXPECT_PRED_FORMAT%(n)sTest; -typedef Predicate%(n)sTest ASSERT_PRED_FORMAT%(n)sTest; -typedef Predicate%(n)sTest EXPECT_PRED%(n)sTest; -typedef Predicate%(n)sTest ASSERT_PRED%(n)sTest; -""" % DEFS - - def GenTest(use_format, use_assert, expect_failure, - use_functor, use_user_type): - """Returns the test for a predicate assertion macro. - - Args: - use_format: true if and only if the assertion is a *_PRED_FORMAT*. - use_assert: true if and only if the assertion is a ASSERT_*. - expect_failure: true if and only if the assertion is expected to fail. - use_functor: true if and only if the first argument of the assertion is - a functor (as opposed to a function) - use_user_type: true if and only if the predicate functor/function takes - argument(s) of a user-defined type. - - Example: - - GenTest(1, 0, 0, 1, 0) returns a test that tests the behavior - of a successful EXPECT_PRED_FORMATn() that takes a functor - whose arguments have built-in types.""" - - if use_assert: - assrt = 'ASSERT' # 'assert' is reserved, so we cannot use - # that identifier here. - else: - assrt = 'EXPECT' - - assertion = assrt + '_PRED' - - if use_format: - pred_format = 'PredFormat' - assertion += '_FORMAT' - else: - pred_format = 'Pred' - - assertion += '%(n)s' % DEFS - - if use_functor: - pred_format_type = 'functor' - pred_format += 'Functor%(n)s()' - else: - pred_format_type = 'function' - pred_format += 'Function%(n)s' - if not use_format: - if use_user_type: - pred_format += 'Bool' - else: - pred_format += 'Int' - - test_name = pred_format_type.title() - - if use_user_type: - arg_type = 'user-defined type (Bool)' - test_name += 'OnUserType' - if expect_failure: - arg = 'Bool(n%s_++)' - else: - arg = 'Bool(++n%s_)' - else: - arg_type = 'built-in type (int)' - test_name += 'OnBuiltInType' - if expect_failure: - arg = 'n%s_++' - else: - arg = '++n%s_' - - if expect_failure: - successful_or_failed = 'failed' - expected_or_not = 'expected.' - test_name += 'Failure' - else: - successful_or_failed = 'successful' - expected_or_not = 'UNEXPECTED!' - test_name += 'Success' - - # A map that defines the values used in the test template. - defs = DEFS.copy() - defs.update({ - 'assert' : assrt, - 'assertion' : assertion, - 'test_name' : test_name, - 'pf_type' : pred_format_type, - 'pf' : pred_format, - 'arg_type' : arg_type, - 'arg' : arg, - 'successful' : successful_or_failed, - 'expected' : expected_or_not, - }) - - test = """ -// Tests a %(successful)s %(assertion)s where the -// predicate-formatter is a %(pf_type)s on a %(arg_type)s. -TEST_F(%(assertion)sTest, %(test_name)s) {""" % defs - - indent = (len(assertion) + 3)*' ' - extra_indent = '' - - if expect_failure: - extra_indent = ' ' - if use_assert: - test += """ - expected_to_finish_ = false; - EXPECT_FATAL_FAILURE({ // NOLINT""" - else: - test += """ - EXPECT_NONFATAL_FAILURE({ // NOLINT""" - - test += '\n' + extra_indent + """ %(assertion)s(%(pf)s""" % defs - - test = test % defs - test += Iter(n, ',\n' + indent + extra_indent + '%(arg)s' % defs) - test += ');\n' + extra_indent + ' finished_ = true;\n' - - if expect_failure: - test += ' }, "");\n' - - test += '}\n' - return test - - # Generates tests for all 2**6 = 64 combinations. - tests += ''.join([GenTest(use_format, use_assert, expect_failure, - use_functor, use_user_type) - for use_format in [0, 1] - for use_assert in [0, 1] - for expect_failure in [0, 1] - for use_functor in [0, 1] - for use_user_type in [0, 1] - ]) - - return tests - - -def UnitTestPostamble(): - """Returns the postamble for the tests.""" - - return '' - - -def GenerateUnitTest(n): - """Returns the tests for up-to n-ary predicate assertions.""" - - GenerateFile(UNIT_TEST, - UnitTestPreamble() - + ''.join([TestsForArity(i) for i in OneTo(n)]) - + UnitTestPostamble()) - - -def _Main(): - """The entry point of the script. Generates the header file and its - unit test.""" - - if len(sys.argv) != 2: - print __doc__ - print 'Author: ' + __author__ - sys.exit(1) - - n = int(sys.argv[1]) - GenerateHeader(n) - GenerateUnitTest(n) - - -if __name__ == '__main__': - _Main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/gtest-config.in b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/gtest-config.in deleted file mode 100755 index 780f8432e..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/gtest-config.in +++ /dev/null @@ -1,274 +0,0 @@ -#!/bin/sh - -# These variables are automatically filled in by the configure script. -name="@PACKAGE_TARNAME@" -version="@PACKAGE_VERSION@" - -show_usage() -{ - echo "Usage: gtest-config [OPTIONS...]" -} - -show_help() -{ - show_usage - cat <<\EOF - -The `gtest-config' script provides access to the necessary compile and linking -flags to connect with Google C++ Testing Framework, both in a build prior to -installation, and on the system proper after installation. The installation -overrides may be issued in combination with any other queries, but will only -affect installation queries if called on a built but not installed gtest. The -installation queries may not be issued with any other types of queries, and -only one installation query may be made at a time. The version queries and -compiler flag queries may be combined as desired but not mixed. Different -version queries are always combined with logical "and" semantics, and only the -last of any particular query is used while all previous ones ignored. All -versions must be specified as a sequence of numbers separated by periods. -Compiler flag queries output the union of the sets of flags when combined. - - Examples: - gtest-config --min-version=1.0 || echo "Insufficient Google Test version." - - g++ $(gtest-config --cppflags --cxxflags) -o foo.o -c foo.cpp - g++ $(gtest-config --ldflags --libs) -o foo foo.o - - # When using a built but not installed Google Test: - g++ $(../../my_gtest_build/scripts/gtest-config ...) ... - - # When using an installed Google Test, but with installation overrides: - export GTEST_PREFIX="/opt" - g++ $(gtest-config --libdir="/opt/lib64" ...) ... - - Help: - --usage brief usage information - --help display this help message - - Installation Overrides: - --prefix= overrides the installation prefix - --exec-prefix= overrides the executable installation prefix - --libdir= overrides the library installation prefix - --includedir= overrides the header file installation prefix - - Installation Queries: - --prefix installation prefix - --exec-prefix executable installation prefix - --libdir library installation directory - --includedir header file installation directory - --version the version of the Google Test installation - - Version Queries: - --min-version=VERSION return 0 if the version is at least VERSION - --exact-version=VERSION return 0 if the version is exactly VERSION - --max-version=VERSION return 0 if the version is at most VERSION - - Compilation Flag Queries: - --cppflags compile flags specific to the C-like preprocessors - --cxxflags compile flags appropriate for C++ programs - --ldflags linker flags - --libs libraries for linking - -EOF -} - -# This function bounds our version with a min and a max. It uses some clever -# POSIX-compliant variable expansion to portably do all the work in the shell -# and avoid any dependency on a particular "sed" or "awk" implementation. -# Notable is that it will only ever compare the first 3 components of versions. -# Further components will be cleanly stripped off. All versions must be -# unadorned, so "v1.0" will *not* work. The minimum version must be in $1, and -# the max in $2. TODO(chandlerc@google.com): If this ever breaks, we should -# investigate expanding this via autom4te from AS_VERSION_COMPARE rather than -# continuing to maintain our own shell version. -check_versions() -{ - major_version=${version%%.*} - minor_version="0" - point_version="0" - if test "${version#*.}" != "${version}"; then - minor_version=${version#*.} - minor_version=${minor_version%%.*} - fi - if test "${version#*.*.}" != "${version}"; then - point_version=${version#*.*.} - point_version=${point_version%%.*} - fi - - min_version="$1" - min_major_version=${min_version%%.*} - min_minor_version="0" - min_point_version="0" - if test "${min_version#*.}" != "${min_version}"; then - min_minor_version=${min_version#*.} - min_minor_version=${min_minor_version%%.*} - fi - if test "${min_version#*.*.}" != "${min_version}"; then - min_point_version=${min_version#*.*.} - min_point_version=${min_point_version%%.*} - fi - - max_version="$2" - max_major_version=${max_version%%.*} - max_minor_version="0" - max_point_version="0" - if test "${max_version#*.}" != "${max_version}"; then - max_minor_version=${max_version#*.} - max_minor_version=${max_minor_version%%.*} - fi - if test "${max_version#*.*.}" != "${max_version}"; then - max_point_version=${max_version#*.*.} - max_point_version=${max_point_version%%.*} - fi - - test $(($major_version)) -lt $(($min_major_version)) && exit 1 - if test $(($major_version)) -eq $(($min_major_version)); then - test $(($minor_version)) -lt $(($min_minor_version)) && exit 1 - if test $(($minor_version)) -eq $(($min_minor_version)); then - test $(($point_version)) -lt $(($min_point_version)) && exit 1 - fi - fi - - test $(($major_version)) -gt $(($max_major_version)) && exit 1 - if test $(($major_version)) -eq $(($max_major_version)); then - test $(($minor_version)) -gt $(($max_minor_version)) && exit 1 - if test $(($minor_version)) -eq $(($max_minor_version)); then - test $(($point_version)) -gt $(($max_point_version)) && exit 1 - fi - fi - - exit 0 -} - -# Show the usage line when no arguments are specified. -if test $# -eq 0; then - show_usage - exit 1 -fi - -while test $# -gt 0; do - case $1 in - --usage) show_usage; exit 0;; - --help) show_help; exit 0;; - - # Installation overrides - --prefix=*) GTEST_PREFIX=${1#--prefix=};; - --exec-prefix=*) GTEST_EXEC_PREFIX=${1#--exec-prefix=};; - --libdir=*) GTEST_LIBDIR=${1#--libdir=};; - --includedir=*) GTEST_INCLUDEDIR=${1#--includedir=};; - - # Installation queries - --prefix|--exec-prefix|--libdir|--includedir|--version) - if test -n "${do_query}"; then - show_usage - exit 1 - fi - do_query=${1#--} - ;; - - # Version checking - --min-version=*) - do_check_versions=yes - min_version=${1#--min-version=} - ;; - --max-version=*) - do_check_versions=yes - max_version=${1#--max-version=} - ;; - --exact-version=*) - do_check_versions=yes - exact_version=${1#--exact-version=} - ;; - - # Compiler flag output - --cppflags) echo_cppflags=yes;; - --cxxflags) echo_cxxflags=yes;; - --ldflags) echo_ldflags=yes;; - --libs) echo_libs=yes;; - - # Everything else is an error - *) show_usage; exit 1;; - esac - shift -done - -# These have defaults filled in by the configure script but can also be -# overridden by environment variables or command line parameters. -prefix="${GTEST_PREFIX:-@prefix@}" -exec_prefix="${GTEST_EXEC_PREFIX:-@exec_prefix@}" -libdir="${GTEST_LIBDIR:-@libdir@}" -includedir="${GTEST_INCLUDEDIR:-@includedir@}" - -# We try and detect if our binary is not located at its installed location. If -# it's not, we provide variables pointing to the source and build tree rather -# than to the install tree. This allows building against a just-built gtest -# rather than an installed gtest. -bindir="@bindir@" -this_relative_bindir=`dirname $0` -this_bindir=`cd ${this_relative_bindir}; pwd -P` -if test "${this_bindir}" = "${this_bindir%${bindir}}"; then - # The path to the script doesn't end in the bindir sequence from Autoconf, - # assume that we are in a build tree. - build_dir=`dirname ${this_bindir}` - src_dir=`cd ${this_bindir}; cd @top_srcdir@; pwd -P` - - # TODO(chandlerc@google.com): This is a dangerous dependency on libtool, we - # should work to remove it, and/or remove libtool altogether, replacing it - # with direct references to the library and a link path. - gtest_libs="${build_dir}/lib/libgtest.la @PTHREAD_CFLAGS@ @PTHREAD_LIBS@" - gtest_ldflags="" - - # We provide hooks to include from either the source or build dir, where the - # build dir is always preferred. This will potentially allow us to write - # build rules for generated headers and have them automatically be preferred - # over provided versions. - gtest_cppflags="-I${build_dir}/include -I${src_dir}/include" - gtest_cxxflags="@PTHREAD_CFLAGS@" -else - # We're using an installed gtest, although it may be staged under some - # prefix. Assume (as our own libraries do) that we can resolve the prefix, - # and are present in the dynamic link paths. - gtest_ldflags="-L${libdir}" - gtest_libs="-l${name} @PTHREAD_CFLAGS@ @PTHREAD_LIBS@" - gtest_cppflags="-I${includedir}" - gtest_cxxflags="@PTHREAD_CFLAGS@" -fi - -# Do an installation query if requested. -if test -n "$do_query"; then - case $do_query in - prefix) echo $prefix; exit 0;; - exec-prefix) echo $exec_prefix; exit 0;; - libdir) echo $libdir; exit 0;; - includedir) echo $includedir; exit 0;; - version) echo $version; exit 0;; - *) show_usage; exit 1;; - esac -fi - -# Do a version check if requested. -if test "$do_check_versions" = "yes"; then - # Make sure we didn't receive a bad combination of parameters. - test "$echo_cppflags" = "yes" && show_usage && exit 1 - test "$echo_cxxflags" = "yes" && show_usage && exit 1 - test "$echo_ldflags" = "yes" && show_usage && exit 1 - test "$echo_libs" = "yes" && show_usage && exit 1 - - if test "$exact_version" != ""; then - check_versions $exact_version $exact_version - # unreachable - else - check_versions ${min_version:-0.0.0} ${max_version:-9999.9999.9999} - # unreachable - fi -fi - -# Do the output in the correct order so that these can be used in-line of -# a compiler invocation. -output="" -test "$echo_cppflags" = "yes" && output="$output $gtest_cppflags" -test "$echo_cxxflags" = "yes" && output="$output $gtest_cxxflags" -test "$echo_ldflags" = "yes" && output="$output $gtest_ldflags" -test "$echo_libs" = "yes" && output="$output $gtest_libs" -echo $output - -exit 0 diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/release_docs.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/release_docs.py deleted file mode 100755 index 1291347f6..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/release_docs.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2013 Google Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Script for branching Google Test/Mock wiki pages for a new version. - -SYNOPSIS - release_docs.py NEW_RELEASE_VERSION - - Google Test and Google Mock's external user documentation is in - interlinked wiki files. When we release a new version of - Google Test or Google Mock, we need to branch the wiki files - such that users of a specific version of Google Test/Mock can - look up documenation relevant for that version. This script - automates that process by: - - - branching the current wiki pages (which document the - behavior of the SVN trunk head) to pages for the specified - version (e.g. branching FAQ.wiki to V2_6_FAQ.wiki when - NEW_RELEASE_VERSION is 2.6); - - updating the links in the branched files to point to the branched - version (e.g. a link in V2_6_FAQ.wiki that pointed to - Primer.wiki#Anchor will now point to V2_6_Primer.wiki#Anchor). - - NOTE: NEW_RELEASE_VERSION must be a NEW version number for - which the wiki pages don't yet exist; otherwise you'll get SVN - errors like "svn: Path 'V1_7_PumpManual.wiki' is not a - directory" when running the script. - -EXAMPLE - $ cd PATH/TO/GTEST_SVN_WORKSPACE/trunk - $ scripts/release_docs.py 2.6 # create wiki pages for v2.6 - $ svn status # verify the file list - $ svn diff # verify the file contents - $ svn commit -m "release wiki pages for v2.6" -""" - -__author__ = 'wan@google.com (Zhanyong Wan)' - -import os -import re -import sys - -import common - - -# Wiki pages that shouldn't be branched for every gtest/gmock release. -GTEST_UNVERSIONED_WIKIS = ['DevGuide.wiki'] -GMOCK_UNVERSIONED_WIKIS = [ - 'DesignDoc.wiki', - 'DevGuide.wiki', - 'KnownIssues.wiki' - ] - - -def DropWikiSuffix(wiki_filename): - """Removes the .wiki suffix (if any) from the given filename.""" - - return (wiki_filename[:-len('.wiki')] if wiki_filename.endswith('.wiki') - else wiki_filename) - - -class WikiBrancher(object): - """Branches ...""" - - def __init__(self, dot_version): - self.project, svn_root_path = common.GetSvnInfo() - if self.project not in ('googletest', 'googlemock'): - sys.exit('This script must be run in a gtest or gmock SVN workspace.') - self.wiki_dir = svn_root_path + '/wiki' - # Turn '2.6' to 'V2_6_'. - self.version_prefix = 'V' + dot_version.replace('.', '_') + '_' - self.files_to_branch = self.GetFilesToBranch() - page_names = [DropWikiSuffix(f) for f in self.files_to_branch] - # A link to Foo.wiki is in one of the following forms: - # [Foo words] - # [Foo#Anchor words] - # [http://code.google.com/.../wiki/Foo words] - # [http://code.google.com/.../wiki/Foo#Anchor words] - # We want to replace 'Foo' with 'V2_6_Foo' in the above cases. - self.search_for_re = re.compile( - # This regex matches either - # [Foo - # or - # /wiki/Foo - # followed by a space or a #, where Foo is the name of an - # unversioned wiki page. - r'(\[|/wiki/)(%s)([ #])' % '|'.join(page_names)) - self.replace_with = r'\1%s\2\3' % (self.version_prefix,) - - def GetFilesToBranch(self): - """Returns a list of .wiki file names that need to be branched.""" - - unversioned_wikis = (GTEST_UNVERSIONED_WIKIS if self.project == 'googletest' - else GMOCK_UNVERSIONED_WIKIS) - return [f for f in os.listdir(self.wiki_dir) - if (f.endswith('.wiki') and - not re.match(r'^V\d', f) and # Excluded versioned .wiki files. - f not in unversioned_wikis)] - - def BranchFiles(self): - """Branches the .wiki files needed to be branched.""" - - print 'Branching %d .wiki files:' % (len(self.files_to_branch),) - os.chdir(self.wiki_dir) - for f in self.files_to_branch: - command = 'svn cp %s %s%s' % (f, self.version_prefix, f) - print command - os.system(command) - - def UpdateLinksInBranchedFiles(self): - - for f in self.files_to_branch: - source_file = os.path.join(self.wiki_dir, f) - versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f) - print 'Updating links in %s.' % (versioned_file,) - text = file(source_file, 'r').read() - new_text = self.search_for_re.sub(self.replace_with, text) - file(versioned_file, 'w').write(new_text) - - -def main(): - if len(sys.argv) != 2: - sys.exit(__doc__) - - brancher = WikiBrancher(sys.argv[1]) - brancher.BranchFiles() - brancher.UpdateLinksInBranchedFiles() - - -if __name__ == '__main__': - main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/run_with_path.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/run_with_path.py deleted file mode 100755 index d46ab4d34..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/run_with_path.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2010 Google Inc. All Rights Reserved. - -"""Runs program specified in the command line with the substituted PATH. - - This script is needed for to support building under Pulse which is unable - to override the existing PATH variable. -""" - -import os -import subprocess -import sys - -SUBST_PATH_ENV_VAR_NAME = "SUBST_PATH" - -def main(): - if SUBST_PATH_ENV_VAR_NAME in os.environ: - os.environ["PATH"] = os.environ[SUBST_PATH_ENV_VAR_NAME] - - exit_code = subprocess.Popen(sys.argv[1:]).wait() - - # exit_code is negative (-signal) if the process has been terminated by - # a signal. Returning negative exit code is not portable and so we return - # 100 instead. - if exit_code < 0: - exit_code = 100 - - sys.exit(exit_code) - -if __name__ == "__main__": - main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/test/Makefile b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/test/Makefile deleted file mode 100644 index cdff58463..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/test/Makefile +++ /dev/null @@ -1,59 +0,0 @@ -# A Makefile for fusing Google Test and building a sample test against it. -# -# SYNOPSIS: -# -# make [all] - makes everything. -# make TARGET - makes the given target. -# make check - makes everything and runs the built sample test. -# make clean - removes all files generated by make. - -# Points to the root of fused Google Test, relative to where this file is. -FUSED_GTEST_DIR = output - -# Paths to the fused gtest files. -FUSED_GTEST_H = $(FUSED_GTEST_DIR)/gtest/gtest.h -FUSED_GTEST_ALL_CC = $(FUSED_GTEST_DIR)/gtest/gtest-all.cc - -# Where to find the sample test. -SAMPLE_DIR = ../../samples - -# Where to find gtest_main.cc. -GTEST_MAIN_CC = ../../src/gtest_main.cc - -# Flags passed to the preprocessor. -# We have no idea here whether pthreads is available in the system, so -# disable its use. -CPPFLAGS += -I$(FUSED_GTEST_DIR) -DGTEST_HAS_PTHREAD=0 - -# Flags passed to the C++ compiler. -CXXFLAGS += -g - -all : sample1_unittest - -check : all - ./sample1_unittest - -clean : - rm -rf $(FUSED_GTEST_DIR) sample1_unittest *.o - -$(FUSED_GTEST_H) : - ../fuse_gtest_files.py $(FUSED_GTEST_DIR) - -$(FUSED_GTEST_ALL_CC) : - ../fuse_gtest_files.py $(FUSED_GTEST_DIR) - -gtest-all.o : $(FUSED_GTEST_H) $(FUSED_GTEST_ALL_CC) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(FUSED_GTEST_DIR)/gtest/gtest-all.cc - -gtest_main.o : $(FUSED_GTEST_H) $(GTEST_MAIN_CC) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GTEST_MAIN_CC) - -sample1.o : $(SAMPLE_DIR)/sample1.cc $(SAMPLE_DIR)/sample1.h - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(SAMPLE_DIR)/sample1.cc - -sample1_unittest.o : $(SAMPLE_DIR)/sample1_unittest.cc \ - $(SAMPLE_DIR)/sample1.h $(FUSED_GTEST_H) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(SAMPLE_DIR)/sample1_unittest.cc - -sample1_unittest : sample1.o sample1_unittest.o gtest-all.o gtest_main.o - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ -o $@ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/upload.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/upload.py deleted file mode 100755 index eba571142..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/upload.py +++ /dev/null @@ -1,1402 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2007, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Tool for uploading diffs from a version control system to the codereview app. - -Usage summary: upload.py [options] [-- diff_options] - -Diff options are passed to the diff command of the underlying system. - -Supported version control systems: - Git - Mercurial - Subversion - -It is important for Git/Mercurial users to specify a tree/node/branch to diff -against by using the '--rev' option. -""" -# This code is derived from appcfg.py in the App Engine SDK (open source), -# and from ASPN recipe #146306. - -import cookielib -import getpass -import logging -import md5 -import mimetypes -import optparse -import os -import re -import socket -import subprocess -import sys -import urllib -import urllib2 -import urlparse - -try: - import readline -except ImportError: - pass - -# The logging verbosity: -# 0: Errors only. -# 1: Status messages. -# 2: Info logs. -# 3: Debug logs. -verbosity = 1 - -# Max size of patch or base file. -MAX_UPLOAD_SIZE = 900 * 1024 - - -def GetEmail(prompt): - """Prompts the user for their email address and returns it. - - The last used email address is saved to a file and offered up as a suggestion - to the user. If the user presses enter without typing in anything the last - used email address is used. If the user enters a new address, it is saved - for next time we prompt. - - """ - last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") - last_email = "" - if os.path.exists(last_email_file_name): - try: - last_email_file = open(last_email_file_name, "r") - last_email = last_email_file.readline().strip("\n") - last_email_file.close() - prompt += " [%s]" % last_email - except IOError, e: - pass - email = raw_input(prompt + ": ").strip() - if email: - try: - last_email_file = open(last_email_file_name, "w") - last_email_file.write(email) - last_email_file.close() - except IOError, e: - pass - else: - email = last_email - return email - - -def StatusUpdate(msg): - """Print a status message to stdout. - - If 'verbosity' is greater than 0, print the message. - - Args: - msg: The string to print. - """ - if verbosity > 0: - print msg - - -def ErrorExit(msg): - """Print an error message to stderr and exit.""" - print >>sys.stderr, msg - sys.exit(1) - - -class ClientLoginError(urllib2.HTTPError): - """Raised to indicate there was an error authenticating with ClientLogin.""" - - def __init__(self, url, code, msg, headers, args): - urllib2.HTTPError.__init__(self, url, code, msg, headers, None) - self.args = args - self.reason = args["Error"] - - -class AbstractRpcServer(object): - """Provides a common interface for a simple RPC server.""" - - def __init__(self, host, auth_function, host_override=None, extra_headers={}, - save_cookies=False): - """Creates a new HttpRpcServer. - - Args: - host: The host to send requests to. - auth_function: A function that takes no arguments and returns an - (email, password) tuple when called. Will be called if authentication - is required. - host_override: The host header to send to the server (defaults to host). - extra_headers: A dict of extra headers to append to every request. - save_cookies: If True, save the authentication cookies to local disk. - If False, use an in-memory cookiejar instead. Subclasses must - implement this functionality. Defaults to False. - """ - self.host = host - self.host_override = host_override - self.auth_function = auth_function - self.authenticated = False - self.extra_headers = extra_headers - self.save_cookies = save_cookies - self.opener = self._GetOpener() - if self.host_override: - logging.info("Server: %s; Host: %s", self.host, self.host_override) - else: - logging.info("Server: %s", self.host) - - def _GetOpener(self): - """Returns an OpenerDirector for making HTTP requests. - - Returns: - A urllib2.OpenerDirector object. - """ - raise NotImplementedError() - - def _CreateRequest(self, url, data=None): - """Creates a new urllib request.""" - logging.debug("Creating request for: '%s' with payload:\n%s", url, data) - req = urllib2.Request(url, data=data) - if self.host_override: - req.add_header("Host", self.host_override) - for key, value in self.extra_headers.iteritems(): - req.add_header(key, value) - return req - - def _GetAuthToken(self, email, password): - """Uses ClientLogin to authenticate the user, returning an auth token. - - Args: - email: The user's email address - password: The user's password - - Raises: - ClientLoginError: If there was an error authenticating with ClientLogin. - HTTPError: If there was some other form of HTTP error. - - Returns: - The authentication token returned by ClientLogin. - """ - account_type = "GOOGLE" - if self.host.endswith(".google.com"): - # Needed for use inside Google. - account_type = "HOSTED" - req = self._CreateRequest( - url="https://www.google.com/accounts/ClientLogin", - data=urllib.urlencode({ - "Email": email, - "Passwd": password, - "service": "ah", - "source": "rietveld-codereview-upload", - "accountType": account_type, - }), - ) - try: - response = self.opener.open(req) - response_body = response.read() - response_dict = dict(x.split("=") - for x in response_body.split("\n") if x) - return response_dict["Auth"] - except urllib2.HTTPError, e: - if e.code == 403: - body = e.read() - response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) - raise ClientLoginError(req.get_full_url(), e.code, e.msg, - e.headers, response_dict) - else: - raise - - def _GetAuthCookie(self, auth_token): - """Fetches authentication cookies for an authentication token. - - Args: - auth_token: The authentication token returned by ClientLogin. - - Raises: - HTTPError: If there was an error fetching the authentication cookies. - """ - # This is a dummy value to allow us to identify when we're successful. - continue_location = "http://localhost/" - args = {"continue": continue_location, "auth": auth_token} - req = self._CreateRequest("http://%s/_ah/login?%s" % - (self.host, urllib.urlencode(args))) - try: - response = self.opener.open(req) - except urllib2.HTTPError, e: - response = e - if (response.code != 302 or - response.info()["location"] != continue_location): - raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, - response.headers, response.fp) - self.authenticated = True - - def _Authenticate(self): - """Authenticates the user. - - The authentication process works as follows: - 1) We get a username and password from the user - 2) We use ClientLogin to obtain an AUTH token for the user - (see https://developers.google.com/identity/protocols/AuthForInstalledApps). - 3) We pass the auth token to /_ah/login on the server to obtain an - authentication cookie. If login was successful, it tries to redirect - us to the URL we provided. - - If we attempt to access the upload API without first obtaining an - authentication cookie, it returns a 401 response and directs us to - authenticate ourselves with ClientLogin. - """ - for i in range(3): - credentials = self.auth_function() - try: - auth_token = self._GetAuthToken(credentials[0], credentials[1]) - except ClientLoginError, e: - if e.reason == "BadAuthentication": - print >>sys.stderr, "Invalid username or password." - continue - if e.reason == "CaptchaRequired": - print >>sys.stderr, ( - "Please go to\n" - "https://www.google.com/accounts/DisplayUnlockCaptcha\n" - "and verify you are a human. Then try again.") - break - if e.reason == "NotVerified": - print >>sys.stderr, "Account not verified." - break - if e.reason == "TermsNotAgreed": - print >>sys.stderr, "User has not agreed to TOS." - break - if e.reason == "AccountDeleted": - print >>sys.stderr, "The user account has been deleted." - break - if e.reason == "AccountDisabled": - print >>sys.stderr, "The user account has been disabled." - break - if e.reason == "ServiceDisabled": - print >>sys.stderr, ("The user's access to the service has been " - "disabled.") - break - if e.reason == "ServiceUnavailable": - print >>sys.stderr, "The service is not available; try again later." - break - raise - self._GetAuthCookie(auth_token) - return - - def Send(self, request_path, payload=None, - content_type="application/octet-stream", - timeout=None, - **kwargs): - """Sends an RPC and returns the response. - - Args: - request_path: The path to send the request to, eg /api/appversion/create. - payload: The body of the request, or None to send an empty request. - content_type: The Content-Type header to use. - timeout: timeout in seconds; default None i.e. no timeout. - (Note: for large requests on OS X, the timeout doesn't work right.) - kwargs: Any keyword arguments are converted into query string parameters. - - Returns: - The response body, as a string. - """ - # TODO: Don't require authentication. Let the server say - # whether it is necessary. - if not self.authenticated: - self._Authenticate() - - old_timeout = socket.getdefaulttimeout() - socket.setdefaulttimeout(timeout) - try: - tries = 0 - while True: - tries += 1 - args = dict(kwargs) - url = "http://%s%s" % (self.host, request_path) - if args: - url += "?" + urllib.urlencode(args) - req = self._CreateRequest(url=url, data=payload) - req.add_header("Content-Type", content_type) - try: - f = self.opener.open(req) - response = f.read() - f.close() - return response - except urllib2.HTTPError, e: - if tries > 3: - raise - elif e.code == 401: - self._Authenticate() -## elif e.code >= 500 and e.code < 600: -## # Server Error - try again. -## continue - else: - raise - finally: - socket.setdefaulttimeout(old_timeout) - - -class HttpRpcServer(AbstractRpcServer): - """Provides a simplified RPC-style interface for HTTP requests.""" - - def _Authenticate(self): - """Save the cookie jar after authentication.""" - super(HttpRpcServer, self)._Authenticate() - if self.save_cookies: - StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) - self.cookie_jar.save() - - def _GetOpener(self): - """Returns an OpenerDirector that supports cookies and ignores redirects. - - Returns: - A urllib2.OpenerDirector object. - """ - opener = urllib2.OpenerDirector() - opener.add_handler(urllib2.ProxyHandler()) - opener.add_handler(urllib2.UnknownHandler()) - opener.add_handler(urllib2.HTTPHandler()) - opener.add_handler(urllib2.HTTPDefaultErrorHandler()) - opener.add_handler(urllib2.HTTPSHandler()) - opener.add_handler(urllib2.HTTPErrorProcessor()) - if self.save_cookies: - self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies") - self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) - if os.path.exists(self.cookie_file): - try: - self.cookie_jar.load() - self.authenticated = True - StatusUpdate("Loaded authentication cookies from %s" % - self.cookie_file) - except (cookielib.LoadError, IOError): - # Failed to load cookies - just ignore them. - pass - else: - # Create an empty cookie file with mode 600 - fd = os.open(self.cookie_file, os.O_CREAT, 0600) - os.close(fd) - # Always chmod the cookie file - os.chmod(self.cookie_file, 0600) - else: - # Don't save cookies across runs of update.py. - self.cookie_jar = cookielib.CookieJar() - opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) - return opener - - -parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]") -parser.add_option("-y", "--assume_yes", action="store_true", - dest="assume_yes", default=False, - help="Assume that the answer to yes/no questions is 'yes'.") -# Logging -group = parser.add_option_group("Logging options") -group.add_option("-q", "--quiet", action="store_const", const=0, - dest="verbose", help="Print errors only.") -group.add_option("-v", "--verbose", action="store_const", const=2, - dest="verbose", default=1, - help="Print info level logs (default).") -group.add_option("--noisy", action="store_const", const=3, - dest="verbose", help="Print all logs.") -# Review server -group = parser.add_option_group("Review server options") -group.add_option("-s", "--server", action="store", dest="server", - default="codereview.appspot.com", - metavar="SERVER", - help=("The server to upload to. The format is host[:port]. " - "Defaults to 'codereview.appspot.com'.")) -group.add_option("-e", "--email", action="store", dest="email", - metavar="EMAIL", default=None, - help="The username to use. Will prompt if omitted.") -group.add_option("-H", "--host", action="store", dest="host", - metavar="HOST", default=None, - help="Overrides the Host header sent with all RPCs.") -group.add_option("--no_cookies", action="store_false", - dest="save_cookies", default=True, - help="Do not save authentication cookies to local disk.") -# Issue -group = parser.add_option_group("Issue options") -group.add_option("-d", "--description", action="store", dest="description", - metavar="DESCRIPTION", default=None, - help="Optional description when creating an issue.") -group.add_option("-f", "--description_file", action="store", - dest="description_file", metavar="DESCRIPTION_FILE", - default=None, - help="Optional path of a file that contains " - "the description when creating an issue.") -group.add_option("-r", "--reviewers", action="store", dest="reviewers", - metavar="REVIEWERS", default=None, - help="Add reviewers (comma separated email addresses).") -group.add_option("--cc", action="store", dest="cc", - metavar="CC", default=None, - help="Add CC (comma separated email addresses).") -# Upload options -group = parser.add_option_group("Patch options") -group.add_option("-m", "--message", action="store", dest="message", - metavar="MESSAGE", default=None, - help="A message to identify the patch. " - "Will prompt if omitted.") -group.add_option("-i", "--issue", type="int", action="store", - metavar="ISSUE", default=None, - help="Issue number to which to add. Defaults to new issue.") -group.add_option("--download_base", action="store_true", - dest="download_base", default=False, - help="Base files will be downloaded by the server " - "(side-by-side diffs may not work on files with CRs).") -group.add_option("--rev", action="store", dest="revision", - metavar="REV", default=None, - help="Branch/tree/revision to diff against (used by DVCS).") -group.add_option("--send_mail", action="store_true", - dest="send_mail", default=False, - help="Send notification email to reviewers.") - - -def GetRpcServer(options): - """Returns an instance of an AbstractRpcServer. - - Returns: - A new AbstractRpcServer, on which RPC calls can be made. - """ - - rpc_server_class = HttpRpcServer - - def GetUserCredentials(): - """Prompts the user for a username and password.""" - email = options.email - if email is None: - email = GetEmail("Email (login for uploading to %s)" % options.server) - password = getpass.getpass("Password for %s: " % email) - return (email, password) - - # If this is the dev_appserver, use fake authentication. - host = (options.host or options.server).lower() - if host == "localhost" or host.startswith("localhost:"): - email = options.email - if email is None: - email = "test@example.com" - logging.info("Using debug user %s. Override with --email" % email) - server = rpc_server_class( - options.server, - lambda: (email, "password"), - host_override=options.host, - extra_headers={"Cookie": - 'dev_appserver_login="%s:False"' % email}, - save_cookies=options.save_cookies) - # Don't try to talk to ClientLogin. - server.authenticated = True - return server - - return rpc_server_class(options.server, GetUserCredentials, - host_override=options.host, - save_cookies=options.save_cookies) - - -def EncodeMultipartFormData(fields, files): - """Encode form fields for multipart/form-data. - - Args: - fields: A sequence of (name, value) elements for regular form fields. - files: A sequence of (name, filename, value) elements for data to be - uploaded as files. - Returns: - (content_type, body) ready for httplib.HTTP instance. - - Source: - https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306 - """ - BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' - CRLF = '\r\n' - lines = [] - for (key, value) in fields: - lines.append('--' + BOUNDARY) - lines.append('Content-Disposition: form-data; name="%s"' % key) - lines.append('') - lines.append(value) - for (key, filename, value) in files: - lines.append('--' + BOUNDARY) - lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % - (key, filename)) - lines.append('Content-Type: %s' % GetContentType(filename)) - lines.append('') - lines.append(value) - lines.append('--' + BOUNDARY + '--') - lines.append('') - body = CRLF.join(lines) - content_type = 'multipart/form-data; boundary=%s' % BOUNDARY - return content_type, body - - -def GetContentType(filename): - """Helper to guess the content-type from the filename.""" - return mimetypes.guess_type(filename)[0] or 'application/octet-stream' - - -# Use a shell for subcommands on Windows to get a PATH search. -use_shell = sys.platform.startswith("win") - -def RunShellWithReturnCode(command, print_output=False, - universal_newlines=True): - """Executes a command and returns the output from stdout and the return code. - - Args: - command: Command to execute. - print_output: If True, the output is printed to stdout. - If False, both stdout and stderr are ignored. - universal_newlines: Use universal_newlines flag (default: True). - - Returns: - Tuple (output, return code) - """ - logging.info("Running %s", command) - p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - shell=use_shell, universal_newlines=universal_newlines) - if print_output: - output_array = [] - while True: - line = p.stdout.readline() - if not line: - break - print line.strip("\n") - output_array.append(line) - output = "".join(output_array) - else: - output = p.stdout.read() - p.wait() - errout = p.stderr.read() - if print_output and errout: - print >>sys.stderr, errout - p.stdout.close() - p.stderr.close() - return output, p.returncode - - -def RunShell(command, silent_ok=False, universal_newlines=True, - print_output=False): - data, retcode = RunShellWithReturnCode(command, print_output, - universal_newlines) - if retcode: - ErrorExit("Got error status from %s:\n%s" % (command, data)) - if not silent_ok and not data: - ErrorExit("No output from %s" % command) - return data - - -class VersionControlSystem(object): - """Abstract base class providing an interface to the VCS.""" - - def __init__(self, options): - """Constructor. - - Args: - options: Command line options. - """ - self.options = options - - def GenerateDiff(self, args): - """Return the current diff as a string. - - Args: - args: Extra arguments to pass to the diff command. - """ - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - def GetUnknownFiles(self): - """Return a list of files unknown to the VCS.""" - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - def CheckForUnknownFiles(self): - """Show an "are you sure?" prompt if there are unknown files.""" - unknown_files = self.GetUnknownFiles() - if unknown_files: - print "The following files are not added to version control:" - for line in unknown_files: - print line - prompt = "Are you sure to continue?(y/N) " - answer = raw_input(prompt).strip() - if answer != "y": - ErrorExit("User aborted") - - def GetBaseFile(self, filename): - """Get the content of the upstream version of a file. - - Returns: - A tuple (base_content, new_content, is_binary, status) - base_content: The contents of the base file. - new_content: For text files, this is empty. For binary files, this is - the contents of the new file, since the diff output won't contain - information to reconstruct the current file. - is_binary: True iff the file is binary. - status: The status of the file. - """ - - raise NotImplementedError( - "abstract method -- subclass %s must override" % self.__class__) - - - def GetBaseFiles(self, diff): - """Helper that calls GetBase file for each file in the patch. - - Returns: - A dictionary that maps from filename to GetBaseFile's tuple. Filenames - are retrieved based on lines that start with "Index:" or - "Property changes on:". - """ - files = {} - for line in diff.splitlines(True): - if line.startswith('Index:') or line.startswith('Property changes on:'): - unused, filename = line.split(':', 1) - # On Windows if a file has property changes its filename uses '\' - # instead of '/'. - filename = filename.strip().replace('\\', '/') - files[filename] = self.GetBaseFile(filename) - return files - - - def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, - files): - """Uploads the base files (and if necessary, the current ones as well).""" - - def UploadFile(filename, file_id, content, is_binary, status, is_base): - """Uploads a file to the server.""" - file_too_large = False - if is_base: - type = "base" - else: - type = "current" - if len(content) > MAX_UPLOAD_SIZE: - print ("Not uploading the %s file for %s because it's too large." % - (type, filename)) - file_too_large = True - content = "" - checksum = md5.new(content).hexdigest() - if options.verbose > 0 and not file_too_large: - print "Uploading %s file for %s" % (type, filename) - url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) - form_fields = [("filename", filename), - ("status", status), - ("checksum", checksum), - ("is_binary", str(is_binary)), - ("is_current", str(not is_base)), - ] - if file_too_large: - form_fields.append(("file_too_large", "1")) - if options.email: - form_fields.append(("user", options.email)) - ctype, body = EncodeMultipartFormData(form_fields, - [("data", filename, content)]) - response_body = rpc_server.Send(url, body, - content_type=ctype) - if not response_body.startswith("OK"): - StatusUpdate(" --> %s" % response_body) - sys.exit(1) - - patches = dict() - [patches.setdefault(v, k) for k, v in patch_list] - for filename in patches.keys(): - base_content, new_content, is_binary, status = files[filename] - file_id_str = patches.get(filename) - if file_id_str.find("nobase") != -1: - base_content = None - file_id_str = file_id_str[file_id_str.rfind("_") + 1:] - file_id = int(file_id_str) - if base_content != None: - UploadFile(filename, file_id, base_content, is_binary, status, True) - if new_content != None: - UploadFile(filename, file_id, new_content, is_binary, status, False) - - def IsImage(self, filename): - """Returns true if the filename has an image extension.""" - mimetype = mimetypes.guess_type(filename)[0] - if not mimetype: - return False - return mimetype.startswith("image/") - - -class SubversionVCS(VersionControlSystem): - """Implementation of the VersionControlSystem interface for Subversion.""" - - def __init__(self, options): - super(SubversionVCS, self).__init__(options) - if self.options.revision: - match = re.match(r"(\d+)(:(\d+))?", self.options.revision) - if not match: - ErrorExit("Invalid Subversion revision %s." % self.options.revision) - self.rev_start = match.group(1) - self.rev_end = match.group(3) - else: - self.rev_start = self.rev_end = None - # Cache output from "svn list -r REVNO dirname". - # Keys: dirname, Values: 2-tuple (output for start rev and end rev). - self.svnls_cache = {} - # SVN base URL is required to fetch files deleted in an older revision. - # Result is cached to not guess it over and over again in GetBaseFile(). - required = self.options.download_base or self.options.revision is not None - self.svn_base = self._GuessBase(required) - - def GuessBase(self, required): - """Wrapper for _GuessBase.""" - return self.svn_base - - def _GuessBase(self, required): - """Returns the SVN base URL. - - Args: - required: If true, exits if the url can't be guessed, otherwise None is - returned. - """ - info = RunShell(["svn", "info"]) - for line in info.splitlines(): - words = line.split() - if len(words) == 2 and words[0] == "URL:": - url = words[1] - scheme, netloc, path, params, query, fragment = urlparse.urlparse(url) - username, netloc = urllib.splituser(netloc) - if username: - logging.info("Removed username from base URL") - if netloc.endswith("svn.python.org"): - if netloc == "svn.python.org": - if path.startswith("/projects/"): - path = path[9:] - elif netloc != "pythondev@svn.python.org": - ErrorExit("Unrecognized Python URL: %s" % url) - base = "http://svn.python.org/view/*checkout*%s/" % path - logging.info("Guessed Python base = %s", base) - elif netloc.endswith("svn.collab.net"): - if path.startswith("/repos/"): - path = path[6:] - base = "http://svn.collab.net/viewvc/*checkout*%s/" % path - logging.info("Guessed CollabNet base = %s", base) - elif netloc.endswith(".googlecode.com"): - path = path + "/" - base = urlparse.urlunparse(("http", netloc, path, params, - query, fragment)) - logging.info("Guessed Google Code base = %s", base) - else: - path = path + "/" - base = urlparse.urlunparse((scheme, netloc, path, params, - query, fragment)) - logging.info("Guessed base = %s", base) - return base - if required: - ErrorExit("Can't find URL in output from svn info") - return None - - def GenerateDiff(self, args): - cmd = ["svn", "diff"] - if self.options.revision: - cmd += ["-r", self.options.revision] - cmd.extend(args) - data = RunShell(cmd) - count = 0 - for line in data.splitlines(): - if line.startswith("Index:") or line.startswith("Property changes on:"): - count += 1 - logging.info(line) - if not count: - ErrorExit("No valid patches found in output from svn diff") - return data - - def _CollapseKeywords(self, content, keyword_str): - """Collapses SVN keywords.""" - # svn cat translates keywords but svn diff doesn't. As a result of this - # behavior patching.PatchChunks() fails with a chunk mismatch error. - # This part was originally written by the Review Board development team - # who had the same problem (https://reviews.reviewboard.org/r/276/). - # Mapping of keywords to known aliases - svn_keywords = { - # Standard keywords - 'Date': ['Date', 'LastChangedDate'], - 'Revision': ['Revision', 'LastChangedRevision', 'Rev'], - 'Author': ['Author', 'LastChangedBy'], - 'HeadURL': ['HeadURL', 'URL'], - 'Id': ['Id'], - - # Aliases - 'LastChangedDate': ['LastChangedDate', 'Date'], - 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'], - 'LastChangedBy': ['LastChangedBy', 'Author'], - 'URL': ['URL', 'HeadURL'], - } - - def repl(m): - if m.group(2): - return "$%s::%s$" % (m.group(1), " " * len(m.group(3))) - return "$%s$" % m.group(1) - keywords = [keyword - for name in keyword_str.split(" ") - for keyword in svn_keywords.get(name, [])] - return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content) - - def GetUnknownFiles(self): - status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True) - unknown_files = [] - for line in status.split("\n"): - if line and line[0] == "?": - unknown_files.append(line) - return unknown_files - - def ReadFile(self, filename): - """Returns the contents of a file.""" - file = open(filename, 'rb') - result = "" - try: - result = file.read() - finally: - file.close() - return result - - def GetStatus(self, filename): - """Returns the status of a file.""" - if not self.options.revision: - status = RunShell(["svn", "status", "--ignore-externals", filename]) - if not status: - ErrorExit("svn status returned no output for %s" % filename) - status_lines = status.splitlines() - # If file is in a cl, the output will begin with - # "\n--- Changelist 'cl_name':\n". See - # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt - if (len(status_lines) == 3 and - not status_lines[0] and - status_lines[1].startswith("--- Changelist")): - status = status_lines[2] - else: - status = status_lines[0] - # If we have a revision to diff against we need to run "svn list" - # for the old and the new revision and compare the results to get - # the correct status for a file. - else: - dirname, relfilename = os.path.split(filename) - if dirname not in self.svnls_cache: - cmd = ["svn", "list", "-r", self.rev_start, dirname or "."] - out, returncode = RunShellWithReturnCode(cmd) - if returncode: - ErrorExit("Failed to get status for %s." % filename) - old_files = out.splitlines() - args = ["svn", "list"] - if self.rev_end: - args += ["-r", self.rev_end] - cmd = args + [dirname or "."] - out, returncode = RunShellWithReturnCode(cmd) - if returncode: - ErrorExit("Failed to run command %s" % cmd) - self.svnls_cache[dirname] = (old_files, out.splitlines()) - old_files, new_files = self.svnls_cache[dirname] - if relfilename in old_files and relfilename not in new_files: - status = "D " - elif relfilename in old_files and relfilename in new_files: - status = "M " - else: - status = "A " - return status - - def GetBaseFile(self, filename): - status = self.GetStatus(filename) - base_content = None - new_content = None - - # If a file is copied its status will be "A +", which signifies - # "addition-with-history". See "svn st" for more information. We need to - # upload the original file or else diff parsing will fail if the file was - # edited. - if status[0] == "A" and status[3] != "+": - # We'll need to upload the new content if we're adding a binary file - # since diff's output won't contain it. - mimetype = RunShell(["svn", "propget", "svn:mime-type", filename], - silent_ok=True) - base_content = "" - is_binary = mimetype and not mimetype.startswith("text/") - if is_binary and self.IsImage(filename): - new_content = self.ReadFile(filename) - elif (status[0] in ("M", "D", "R") or - (status[0] == "A" and status[3] == "+") or # Copied file. - (status[0] == " " and status[1] == "M")): # Property change. - args = [] - if self.options.revision: - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) - else: - # Don't change filename, it's needed later. - url = filename - args += ["-r", "BASE"] - cmd = ["svn"] + args + ["propget", "svn:mime-type", url] - mimetype, returncode = RunShellWithReturnCode(cmd) - if returncode: - # File does not exist in the requested revision. - # Reset mimetype, it contains an error message. - mimetype = "" - get_base = False - is_binary = mimetype and not mimetype.startswith("text/") - if status[0] == " ": - # Empty base content just to force an upload. - base_content = "" - elif is_binary: - if self.IsImage(filename): - get_base = True - if status[0] == "M": - if not self.rev_end: - new_content = self.ReadFile(filename) - else: - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end) - new_content = RunShell(["svn", "cat", url], - universal_newlines=True, silent_ok=True) - else: - base_content = "" - else: - get_base = True - - if get_base: - if is_binary: - universal_newlines = False - else: - universal_newlines = True - if self.rev_start: - # "svn cat -r REV delete_file.txt" doesn't work. cat requires - # the full URL with "@REV" appended instead of using "-r" option. - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) - base_content = RunShell(["svn", "cat", url], - universal_newlines=universal_newlines, - silent_ok=True) - else: - base_content = RunShell(["svn", "cat", filename], - universal_newlines=universal_newlines, - silent_ok=True) - if not is_binary: - args = [] - if self.rev_start: - url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) - else: - url = filename - args += ["-r", "BASE"] - cmd = ["svn"] + args + ["propget", "svn:keywords", url] - keywords, returncode = RunShellWithReturnCode(cmd) - if keywords and not returncode: - base_content = self._CollapseKeywords(base_content, keywords) - else: - StatusUpdate("svn status returned unexpected output: %s" % status) - sys.exit(1) - return base_content, new_content, is_binary, status[0:5] - - -class GitVCS(VersionControlSystem): - """Implementation of the VersionControlSystem interface for Git.""" - - def __init__(self, options): - super(GitVCS, self).__init__(options) - # Map of filename -> hash of base file. - self.base_hashes = {} - - def GenerateDiff(self, extra_args): - # This is more complicated than svn's GenerateDiff because we must convert - # the diff output to include an svn-style "Index:" line as well as record - # the hashes of the base files, so we can upload them along with our diff. - if self.options.revision: - extra_args = [self.options.revision] + extra_args - gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args) - svndiff = [] - filecount = 0 - filename = None - for line in gitdiff.splitlines(): - match = re.match(r"diff --git a/(.*) b/.*$", line) - if match: - filecount += 1 - filename = match.group(1) - svndiff.append("Index: %s\n" % filename) - else: - # The "index" line in a git diff looks like this (long hashes elided): - # index 82c0d44..b2cee3f 100755 - # We want to save the left hash, as that identifies the base file. - match = re.match(r"index (\w+)\.\.", line) - if match: - self.base_hashes[filename] = match.group(1) - svndiff.append(line + "\n") - if not filecount: - ErrorExit("No valid patches found in output from git diff") - return "".join(svndiff) - - def GetUnknownFiles(self): - status = RunShell(["git", "ls-files", "--exclude-standard", "--others"], - silent_ok=True) - return status.splitlines() - - def GetBaseFile(self, filename): - hash = self.base_hashes[filename] - base_content = None - new_content = None - is_binary = False - if hash == "0" * 40: # All-zero hash indicates no base file. - status = "A" - base_content = "" - else: - status = "M" - base_content, returncode = RunShellWithReturnCode(["git", "show", hash]) - if returncode: - ErrorExit("Got error status from 'git show %s'" % hash) - return (base_content, new_content, is_binary, status) - - -class MercurialVCS(VersionControlSystem): - """Implementation of the VersionControlSystem interface for Mercurial.""" - - def __init__(self, options, repo_dir): - super(MercurialVCS, self).__init__(options) - # Absolute path to repository (we can be in a subdir) - self.repo_dir = os.path.normpath(repo_dir) - # Compute the subdir - cwd = os.path.normpath(os.getcwd()) - assert cwd.startswith(self.repo_dir) - self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") - if self.options.revision: - self.base_rev = self.options.revision - else: - self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip() - - def _GetRelPath(self, filename): - """Get relative path of a file according to the current directory, - given its logical path in the repo.""" - assert filename.startswith(self.subdir), filename - return filename[len(self.subdir):].lstrip(r"\/") - - def GenerateDiff(self, extra_args): - # If no file specified, restrict to the current subdir - extra_args = extra_args or ["."] - cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args - data = RunShell(cmd, silent_ok=True) - svndiff = [] - filecount = 0 - for line in data.splitlines(): - m = re.match("diff --git a/(\S+) b/(\S+)", line) - if m: - # Modify line to make it look like as it comes from svn diff. - # With this modification no changes on the server side are required - # to make upload.py work with Mercurial repos. - # NOTE: for proper handling of moved/copied files, we have to use - # the second filename. - filename = m.group(2) - svndiff.append("Index: %s" % filename) - svndiff.append("=" * 67) - filecount += 1 - logging.info(line) - else: - svndiff.append(line) - if not filecount: - ErrorExit("No valid patches found in output from hg diff") - return "\n".join(svndiff) + "\n" - - def GetUnknownFiles(self): - """Return a list of files unknown to the VCS.""" - args = [] - status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], - silent_ok=True) - unknown_files = [] - for line in status.splitlines(): - st, fn = line.split(" ", 1) - if st == "?": - unknown_files.append(fn) - return unknown_files - - def GetBaseFile(self, filename): - # "hg status" and "hg cat" both take a path relative to the current subdir - # rather than to the repo root, but "hg diff" has given us the full path - # to the repo root. - base_content = "" - new_content = None - is_binary = False - oldrelpath = relpath = self._GetRelPath(filename) - # "hg status -C" returns two lines for moved/copied files, one otherwise - out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) - out = out.splitlines() - # HACK: strip error message about missing file/directory if it isn't in - # the working copy - if out[0].startswith('%s: ' % relpath): - out = out[1:] - if len(out) > 1: - # Moved/copied => considered as modified, use old filename to - # retrieve base contents - oldrelpath = out[1].strip() - status = "M" - else: - status, _ = out[0].split(' ', 1) - if status != "A": - base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], - silent_ok=True) - is_binary = "\0" in base_content # Mercurial's heuristic - if status != "R": - new_content = open(relpath, "rb").read() - is_binary = is_binary or "\0" in new_content - if is_binary and base_content: - # Fetch again without converting newlines - base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], - silent_ok=True, universal_newlines=False) - if not is_binary or not self.IsImage(relpath): - new_content = None - return base_content, new_content, is_binary, status - - -# NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. -def SplitPatch(data): - """Splits a patch into separate pieces for each file. - - Args: - data: A string containing the output of svn diff. - - Returns: - A list of 2-tuple (filename, text) where text is the svn diff output - pertaining to filename. - """ - patches = [] - filename = None - diff = [] - for line in data.splitlines(True): - new_filename = None - if line.startswith('Index:'): - unused, new_filename = line.split(':', 1) - new_filename = new_filename.strip() - elif line.startswith('Property changes on:'): - unused, temp_filename = line.split(':', 1) - # When a file is modified, paths use '/' between directories, however - # when a property is modified '\' is used on Windows. Make them the same - # otherwise the file shows up twice. - temp_filename = temp_filename.strip().replace('\\', '/') - if temp_filename != filename: - # File has property changes but no modifications, create a new diff. - new_filename = temp_filename - if new_filename: - if filename and diff: - patches.append((filename, ''.join(diff))) - filename = new_filename - diff = [line] - continue - if diff is not None: - diff.append(line) - if filename and diff: - patches.append((filename, ''.join(diff))) - return patches - - -def UploadSeparatePatches(issue, rpc_server, patchset, data, options): - """Uploads a separate patch for each file in the diff output. - - Returns a list of [patch_key, filename] for each file. - """ - patches = SplitPatch(data) - rv = [] - for patch in patches: - if len(patch[1]) > MAX_UPLOAD_SIZE: - print ("Not uploading the patch for " + patch[0] + - " because the file is too large.") - continue - form_fields = [("filename", patch[0])] - if not options.download_base: - form_fields.append(("content_upload", "1")) - files = [("data", "data.diff", patch[1])] - ctype, body = EncodeMultipartFormData(form_fields, files) - url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) - print "Uploading patch for " + patch[0] - response_body = rpc_server.Send(url, body, content_type=ctype) - lines = response_body.splitlines() - if not lines or lines[0] != "OK": - StatusUpdate(" --> %s" % response_body) - sys.exit(1) - rv.append([lines[1], patch[0]]) - return rv - - -def GuessVCS(options): - """Helper to guess the version control system. - - This examines the current directory, guesses which VersionControlSystem - we're using, and returns an instance of the appropriate class. Exit with an - error if we can't figure it out. - - Returns: - A VersionControlSystem instance. Exits if the VCS can't be guessed. - """ - # Mercurial has a command to get the base directory of a repository - # Try running it, but don't die if we don't have hg installed. - # NOTE: we try Mercurial first as it can sit on top of an SVN working copy. - try: - out, returncode = RunShellWithReturnCode(["hg", "root"]) - if returncode == 0: - return MercurialVCS(options, out.strip()) - except OSError, (errno, message): - if errno != 2: # ENOENT -- they don't have hg installed. - raise - - # Subversion has a .svn in all working directories. - if os.path.isdir('.svn'): - logging.info("Guessed VCS = Subversion") - return SubversionVCS(options) - - # Git has a command to test if you're in a git tree. - # Try running it, but don't die if we don't have git installed. - try: - out, returncode = RunShellWithReturnCode(["git", "rev-parse", - "--is-inside-work-tree"]) - if returncode == 0: - return GitVCS(options) - except OSError, (errno, message): - if errno != 2: # ENOENT -- they don't have git installed. - raise - - ErrorExit(("Could not guess version control system. " - "Are you in a working copy directory?")) - - -def RealMain(argv, data=None): - """The real main function. - - Args: - argv: Command line arguments. - data: Diff contents. If None (default) the diff is generated by - the VersionControlSystem implementation returned by GuessVCS(). - - Returns: - A 2-tuple (issue id, patchset id). - The patchset id is None if the base files are not uploaded by this - script (applies only to SVN checkouts). - """ - logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:" - "%(lineno)s %(message)s ")) - os.environ['LC_ALL'] = 'C' - options, args = parser.parse_args(argv[1:]) - global verbosity - verbosity = options.verbose - if verbosity >= 3: - logging.getLogger().setLevel(logging.DEBUG) - elif verbosity >= 2: - logging.getLogger().setLevel(logging.INFO) - vcs = GuessVCS(options) - if isinstance(vcs, SubversionVCS): - # base field is only allowed for Subversion. - # Note: Fetching base files may become deprecated in future releases. - base = vcs.GuessBase(options.download_base) - else: - base = None - if not base and options.download_base: - options.download_base = True - logging.info("Enabled upload of base file") - if not options.assume_yes: - vcs.CheckForUnknownFiles() - if data is None: - data = vcs.GenerateDiff(args) - files = vcs.GetBaseFiles(data) - if verbosity >= 1: - print "Upload server:", options.server, "(change with -s/--server)" - if options.issue: - prompt = "Message describing this patch set: " - else: - prompt = "New issue subject: " - message = options.message or raw_input(prompt).strip() - if not message: - ErrorExit("A non-empty message is required") - rpc_server = GetRpcServer(options) - form_fields = [("subject", message)] - if base: - form_fields.append(("base", base)) - if options.issue: - form_fields.append(("issue", str(options.issue))) - if options.email: - form_fields.append(("user", options.email)) - if options.reviewers: - for reviewer in options.reviewers.split(','): - if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1: - ErrorExit("Invalid email address: %s" % reviewer) - form_fields.append(("reviewers", options.reviewers)) - if options.cc: - for cc in options.cc.split(','): - if "@" in cc and not cc.split("@")[1].count(".") == 1: - ErrorExit("Invalid email address: %s" % cc) - form_fields.append(("cc", options.cc)) - description = options.description - if options.description_file: - if options.description: - ErrorExit("Can't specify description and description_file") - file = open(options.description_file, 'r') - description = file.read() - file.close() - if description: - form_fields.append(("description", description)) - # Send a hash of all the base file so the server can determine if a copy - # already exists in an earlier patchset. - base_hashes = "" - for file, info in files.iteritems(): - if not info[0] is None: - checksum = md5.new(info[0]).hexdigest() - if base_hashes: - base_hashes += "|" - base_hashes += checksum + ":" + file - form_fields.append(("base_hashes", base_hashes)) - # If we're uploading base files, don't send the email before the uploads, so - # that it contains the file status. - if options.send_mail and options.download_base: - form_fields.append(("send_mail", "1")) - if not options.download_base: - form_fields.append(("content_upload", "1")) - if len(data) > MAX_UPLOAD_SIZE: - print "Patch is large, so uploading file patches separately." - uploaded_diff_file = [] - form_fields.append(("separate_patches", "1")) - else: - uploaded_diff_file = [("data", "data.diff", data)] - ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) - response_body = rpc_server.Send("/upload", body, content_type=ctype) - patchset = None - if not options.download_base or not uploaded_diff_file: - lines = response_body.splitlines() - if len(lines) >= 2: - msg = lines[0] - patchset = lines[1].strip() - patches = [x.split(" ", 1) for x in lines[2:]] - else: - msg = response_body - else: - msg = response_body - StatusUpdate(msg) - if not response_body.startswith("Issue created.") and \ - not response_body.startswith("Issue updated."): - sys.exit(0) - issue = msg[msg.rfind("/")+1:] - - if not uploaded_diff_file: - result = UploadSeparatePatches(issue, rpc_server, patchset, data, options) - if not options.download_base: - patches = result - - if not options.download_base: - vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files) - if options.send_mail: - rpc_server.Send("/" + issue + "/mail", payload="") - return issue, patchset - - -def main(): - try: - RealMain(sys.argv) - except KeyboardInterrupt: - print - StatusUpdate("Interrupted.") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/googletest-json-output-unittest.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/googletest-json-output-unittest.py deleted file mode 100644 index 15861f75c..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/googletest-json-output-unittest.py +++ /dev/null @@ -1,778 +0,0 @@ -#!/usr/bin/env python -# Copyright 2018, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Unit test for the gtest_json_output module.""" - -import datetime -import errno -import json -import os -import re -import sys - -import gtest_json_test_utils -import gtest_test_utils - -GTEST_FILTER_FLAG = '--gtest_filter' -GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' -GTEST_OUTPUT_FLAG = '--gtest_output' -GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.json' -GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' - -# The flag indicating stacktraces are not supported -NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' - -SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv - -if SUPPORTS_STACK_TRACES: - STACK_TRACE_TEMPLATE = '\nStack trace:\n*' -else: - STACK_TRACE_TEMPLATE = '' - -EXPECTED_NON_EMPTY = { - u'tests': - 24, - u'failures': - 4, - u'disabled': - 2, - u'errors': - 0, - u'timestamp': - u'*', - u'time': - u'*', - u'ad_hoc_property': - u'42', - u'name': - u'AllTests', - u'testsuites': [{ - u'name': - u'SuccessfulTest', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'Succeeds', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'SuccessfulTest' - }] - }, { - u'name': - u'FailedTest', - u'tests': - 1, - u'failures': - 1, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': - u'Fails', - u'status': - u'RUN', - u'result': - u'COMPLETED', - u'time': - u'*', - u'timestamp': - u'*', - u'classname': - u'FailedTest', - u'failures': [{ - u'failure': u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - }] - }] - }, { - u'name': - u'DisabledTest', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 1, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'DISABLED_test_not_run', - u'status': u'NOTRUN', - u'result': u'SUPPRESSED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'DisabledTest' - }] - }, { - u'name': - u'SkippedTest', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'Skipped', - u'status': u'RUN', - u'result': u'SKIPPED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'SkippedTest' - }] - }, { - u'name': - u'MixedResultTest', - u'tests': - 3, - u'failures': - 1, - u'disabled': - 1, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'Succeeds', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'MixedResultTest' - }, { - u'name': - u'Fails', - u'status': - u'RUN', - u'result': - u'COMPLETED', - u'time': - u'*', - u'timestamp': - u'*', - u'classname': - u'MixedResultTest', - u'failures': [{ - u'failure': u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 1\n 2' + STACK_TRACE_TEMPLATE, - u'type': u'' - }, { - u'failure': u'gtest_xml_output_unittest_.cc:*\n' - u'Expected equality of these values:\n' - u' 2\n 3' + STACK_TRACE_TEMPLATE, - u'type': u'' - }] - }, { - u'name': u'DISABLED_test', - u'status': u'NOTRUN', - u'result': u'SUPPRESSED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'MixedResultTest' - }] - }, { - u'name': - u'XmlQuotingTest', - u'tests': - 1, - u'failures': - 1, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': - u'OutputsCData', - u'status': - u'RUN', - u'result': - u'COMPLETED', - u'time': - u'*', - u'timestamp': - u'*', - u'classname': - u'XmlQuotingTest', - u'failures': [{ - u'failure': u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nXML output: ' - u'' + - STACK_TRACE_TEMPLATE, - u'type': u'' - }] - }] - }, { - u'name': - u'InvalidCharactersTest', - u'tests': - 1, - u'failures': - 1, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': - u'InvalidCharactersInMessage', - u'status': - u'RUN', - u'result': - u'COMPLETED', - u'time': - u'*', - u'timestamp': - u'*', - u'classname': - u'InvalidCharactersTest', - u'failures': [{ - u'failure': u'gtest_xml_output_unittest_.cc:*\n' - u'Failed\nInvalid characters in brackets' - u' [\x01\x02]' + STACK_TRACE_TEMPLATE, - u'type': u'' - }] - }] - }, { - u'name': - u'PropertyRecordingTest', - u'tests': - 4, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'SetUpTestSuite': - u'yes', - u'TearDownTestSuite': - u'aye', - u'testsuite': [{ - u'name': u'OneProperty', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1' - }, { - u'name': u'IntValuedProperty', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'PropertyRecordingTest', - u'key_int': u'1' - }, { - u'name': u'ThreeProperties', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'1', - u'key_2': u'2', - u'key_3': u'3' - }, { - u'name': u'TwoValuesForOneKeyUsesLastValue', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'PropertyRecordingTest', - u'key_1': u'2' - }] - }, { - u'name': - u'NoFixtureTest', - u'tests': - 3, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'RecordProperty', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'NoFixtureTest', - u'key': u'1' - }, { - u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_int': u'1' - }, { - u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'NoFixtureTest', - u'key_for_utility_string': u'1' - }] - }, { - u'name': - u'TypedTest/0', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'TypedTest/0' - }] - }, { - u'name': - u'TypedTest/1', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'TypedTest/1' - }] - }, { - u'name': - u'Single/TypeParameterizedTestSuite/0', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'HasTypeParamAttribute', - u'type_param': u'int', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'Single/TypeParameterizedTestSuite/0' - }] - }, { - u'name': - u'Single/TypeParameterizedTestSuite/1', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'HasTypeParamAttribute', - u'type_param': u'long', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'Single/TypeParameterizedTestSuite/1' - }] - }, { - u'name': - u'Single/ValueParamTest', - u'tests': - 4, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'HasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'Single/ValueParamTest' - }, { - u'name': u'HasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'Single/ValueParamTest' - }, { - u'name': u'AnotherTestThatHasValueParamAttribute/0', - u'value_param': u'33', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'Single/ValueParamTest' - }, { - u'name': u'AnotherTestThatHasValueParamAttribute/1', - u'value_param': u'42', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'Single/ValueParamTest' - }] - }] -} - -EXPECTED_FILTERED = { - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'name': - u'AllTests', - u'ad_hoc_property': - u'42', - u'testsuites': [{ - u'name': - u'SuccessfulTest', - u'tests': - 1, - u'failures': - 0, - u'disabled': - 0, - u'errors': - 0, - u'time': - u'*', - u'timestamp': - u'*', - u'testsuite': [{ - u'name': u'Succeeds', - u'status': u'RUN', - u'result': u'COMPLETED', - u'time': u'*', - u'timestamp': u'*', - u'classname': u'SuccessfulTest', - }] - }], -} - -EXPECTED_EMPTY = { - u'tests': 0, - u'failures': 0, - u'disabled': 0, - u'errors': 0, - u'time': u'*', - u'timestamp': u'*', - u'name': u'AllTests', - u'testsuites': [], -} - -GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) - -SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( - [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output - - -class GTestJsonOutputUnitTest(gtest_test_utils.TestCase): - """Unit test for Google Test's JSON output functionality. - """ - - # This test currently breaks on platforms that do not support typed and - # type-parameterized tests, so we don't run it under them. - if SUPPORTS_TYPED_TESTS: - - def testNonEmptyJsonOutput(self): - """Verifies JSON output for a Google Test binary with non-empty output. - - Runs a test program that generates a non-empty JSON output, and - tests that the JSON output is expected. - """ - self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1) - - def testEmptyJsonOutput(self): - """Verifies JSON output for a Google Test binary without actual tests. - - Runs a test program that generates an empty JSON output, and - tests that the JSON output is expected. - """ - - self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_EMPTY, 0) - - def testTimestampValue(self): - """Checks whether the timestamp attribute in the JSON output is valid. - - Runs a test program that generates an empty JSON output, and checks if - the timestamp attribute in the testsuites tag is valid. - """ - actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0) - date_time_str = actual['timestamp'] - # datetime.strptime() is only available in Python 2.5+ so we have to - # parse the expected datetime manually. - match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) - self.assertTrue( - re.match, - 'JSON datettime string %s has incorrect format' % date_time_str) - date_time_from_json = datetime.datetime( - year=int(match.group(1)), month=int(match.group(2)), - day=int(match.group(3)), hour=int(match.group(4)), - minute=int(match.group(5)), second=int(match.group(6))) - - time_delta = abs(datetime.datetime.now() - date_time_from_json) - # timestamp value should be near the current local time - self.assertTrue(time_delta < datetime.timedelta(seconds=600), - 'time_delta is %s' % time_delta) - - def testDefaultOutputFile(self): - """Verifies the default output file name. - - Confirms that Google Test produces an JSON output file with the expected - default name if no name is explicitly specified. - """ - output_file = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_DEFAULT_OUTPUT_FILE) - gtest_prog_path = gtest_test_utils.GetTestExecutablePath( - 'gtest_no_test_unittest') - try: - os.remove(output_file) - except OSError: - e = sys.exc_info()[1] - if e.errno != errno.ENOENT: - raise - - p = gtest_test_utils.Subprocess( - [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG], - working_dir=gtest_test_utils.GetTempDir()) - self.assert_(p.exited) - self.assertEquals(0, p.exit_code) - self.assert_(os.path.isfile(output_file)) - - def testSuppressedJsonOutput(self): - """Verifies that no JSON output is generated. - - Tests that no JSON file is generated if the default JSON listener is - shut down before RUN_ALL_TESTS is invoked. - """ - - json_path = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_PROGRAM_NAME + 'out.json') - if os.path.isfile(json_path): - os.remove(json_path) - - command = [GTEST_PROGRAM_PATH, - '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path), - '--shut_down_xml'] - p = gtest_test_utils.Subprocess(command) - if p.terminated_by_signal: - # p.signal is available only if p.terminated_by_signal is True. - self.assertFalse( - p.terminated_by_signal, - '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(1, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, 1)) - - self.assert_(not os.path.isfile(json_path)) - - def testFilteredTestJsonOutput(self): - """Verifies JSON output when a filter is applied. - - Runs a test program that executes only some tests and verifies that - non-selected tests do not show up in the JSON output. - """ - - self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0, - extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) - - def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code): - """Returns the JSON output generated by running the program gtest_prog_name. - - Furthermore, the program's exit code must be expected_exit_code. - - Args: - gtest_prog_name: Google Test binary name. - extra_args: extra arguments to binary invocation. - expected_exit_code: program's exit code. - """ - json_path = os.path.join(gtest_test_utils.GetTempDir(), - gtest_prog_name + 'out.json') - gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) - - command = ( - [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] + - extra_args - ) - p = gtest_test_utils.Subprocess(command) - if p.terminated_by_signal: - self.assert_(False, - '%s was killed by signal %d' % (gtest_prog_name, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(expected_exit_code, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, expected_exit_code)) - with open(json_path) as f: - actual = json.load(f) - return actual - - def _TestJsonOutput(self, gtest_prog_name, expected, - expected_exit_code, extra_args=None): - """Checks the JSON output generated by the Google Test binary. - - Asserts that the JSON document generated by running the program - gtest_prog_name matches expected_json, a string containing another - JSON document. Furthermore, the program's exit code must be - expected_exit_code. - - Args: - gtest_prog_name: Google Test binary name. - expected: expected output. - expected_exit_code: program's exit code. - extra_args: extra arguments to binary invocation. - """ - - actual = self._GetJsonOutput(gtest_prog_name, extra_args or [], - expected_exit_code) - self.assertEqual(expected, gtest_json_test_utils.normalize(actual)) - - -if __name__ == '__main__': - if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: - # unittest.main() can't handle unknown flags - sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) - - os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' - gtest_test_utils.Main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/gtest_list_output_unittest.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/gtest_list_output_unittest.py deleted file mode 100644 index 3bba7ea2c..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/gtest_list_output_unittest.py +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2006, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Unit test for Google Test's --gtest_list_tests flag. - -A user can ask Google Test to list all tests by specifying the ---gtest_list_tests flag. If output is requested, via --gtest_output=xml -or --gtest_output=json, the tests are listed, with extra information in the -output file. -This script tests such functionality by invoking gtest_list_output_unittest_ - (a program written with Google Test) the command line flags. -""" - -import os -import re -import gtest_test_utils - -GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' -GTEST_OUTPUT_FLAG = '--gtest_output' - -EXPECTED_XML = """<\?xml version="1.0" encoding="UTF-8"\?> - - - - - - -""" - -EXPECTED_JSON = """{ - "tests": 2, - "name": "AllTests", - "testsuites": \[ - { - "name": "FooTest", - "tests": 2, - "testsuite": \[ - { - "name": "Test1", - "file": ".*gtest_list_output_unittest_.cc", - "line": 43 - }, - { - "name": "Test2", - "file": ".*gtest_list_output_unittest_.cc", - "line": 45 - } - \] - } - \] -} -""" - - -class GTestListTestsOutputUnitTest(gtest_test_utils.TestCase): - """Unit test for Google Test's list tests with output to file functionality. - """ - - def testXml(self): - """Verifies XML output for listing tests in a Google Test binary. - - Runs a test program that generates an empty XML output, and - tests that the XML output is expected. - """ - self._TestOutput('xml', EXPECTED_XML) - - def testJSON(self): - """Verifies XML output for listing tests in a Google Test binary. - - Runs a test program that generates an empty XML output, and - tests that the XML output is expected. - """ - self._TestOutput('json', EXPECTED_JSON) - - def _GetOutput(self, out_format): - file_path = os.path.join(gtest_test_utils.GetTempDir(), - 'test_out.' + out_format) - gtest_prog_path = gtest_test_utils.GetTestExecutablePath( - 'gtest_list_output_unittest_') - - command = ([ - gtest_prog_path, - '%s=%s:%s' % (GTEST_OUTPUT_FLAG, out_format, file_path), - '--gtest_list_tests' - ]) - environ_copy = os.environ.copy() - p = gtest_test_utils.Subprocess( - command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir()) - - self.assert_(p.exited) - self.assertEquals(0, p.exit_code) - with open(file_path) as f: - result = f.read() - return result - - def _TestOutput(self, test_format, expected_output): - actual = self._GetOutput(test_format) - actual_lines = actual.splitlines() - expected_lines = expected_output.splitlines() - line_count = 0 - for actual_line in actual_lines: - expected_line = expected_lines[line_count] - expected_line_re = re.compile(expected_line.strip()) - self.assert_( - expected_line_re.match(actual_line.strip()), - ('actual output of "%s",\n' - 'which does not match expected regex of "%s"\n' - 'on line %d' % (actual, expected_output, line_count))) - line_count = line_count + 1 - - -if __name__ == '__main__': - os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' - gtest_test_utils.Main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/gtest_xml_output_unittest.py b/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/gtest_xml_output_unittest.py deleted file mode 100755 index 63b1af0b6..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/test/gtest_xml_output_unittest.py +++ /dev/null @@ -1,389 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2006, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Unit test for the gtest_xml_output module""" - -import datetime -import errno -import os -import re -import sys -from xml.dom import minidom, Node - -import gtest_test_utils -import gtest_xml_test_utils - -GTEST_FILTER_FLAG = '--gtest_filter' -GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' -GTEST_OUTPUT_FLAG = '--gtest_output' -GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml' -GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' - -# The flag indicating stacktraces are not supported -NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' - -# The environment variables for test sharding. -TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' -SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' -SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE' - -SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv - -if SUPPORTS_STACK_TRACES: - STACK_TRACE_TEMPLATE = '\nStack trace:\n*' -else: - STACK_TRACE_TEMPLATE = '' - # unittest.main() can't handle unknown flags - sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) - -EXPECTED_NON_EMPTY_XML = """ - - - - - - - - - - - - - - - - - - - - ]]>%(stack)s]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -""" % { - 'stack': STACK_TRACE_TEMPLATE -} - -EXPECTED_FILTERED_TEST_XML = """ - - - - -""" - -EXPECTED_SHARDED_TEST_XML = """ - - - - - - - - - - - - - - -""" - -EXPECTED_EMPTY_XML = """ - -""" - -GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) - -SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( - [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output - - -class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): - """ - Unit test for Google Test's XML output functionality. - """ - - # This test currently breaks on platforms that do not support typed and - # type-parameterized tests, so we don't run it under them. - if SUPPORTS_TYPED_TESTS: - def testNonEmptyXmlOutput(self): - """ - Runs a test program that generates a non-empty XML output, and - tests that the XML output is expected. - """ - self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1) - - def testEmptyXmlOutput(self): - """Verifies XML output for a Google Test binary without actual tests. - - Runs a test program that generates an empty XML output, and - tests that the XML output is expected. - """ - - self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0) - - def testTimestampValue(self): - """Checks whether the timestamp attribute in the XML output is valid. - - Runs a test program that generates an empty XML output, and checks if - the timestamp attribute in the testsuites tag is valid. - """ - actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0) - date_time_str = actual.documentElement.getAttributeNode('timestamp').value - # datetime.strptime() is only available in Python 2.5+ so we have to - # parse the expected datetime manually. - match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) - self.assertTrue( - re.match, - 'XML datettime string %s has incorrect format' % date_time_str) - date_time_from_xml = datetime.datetime( - year=int(match.group(1)), month=int(match.group(2)), - day=int(match.group(3)), hour=int(match.group(4)), - minute=int(match.group(5)), second=int(match.group(6))) - - time_delta = abs(datetime.datetime.now() - date_time_from_xml) - # timestamp value should be near the current local time - self.assertTrue(time_delta < datetime.timedelta(seconds=600), - 'time_delta is %s' % time_delta) - actual.unlink() - - def testDefaultOutputFile(self): - """ - Confirms that Google Test produces an XML output file with the expected - default name if no name is explicitly specified. - """ - output_file = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_DEFAULT_OUTPUT_FILE) - gtest_prog_path = gtest_test_utils.GetTestExecutablePath( - 'gtest_no_test_unittest') - try: - os.remove(output_file) - except OSError: - e = sys.exc_info()[1] - if e.errno != errno.ENOENT: - raise - - p = gtest_test_utils.Subprocess( - [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG], - working_dir=gtest_test_utils.GetTempDir()) - self.assert_(p.exited) - self.assertEquals(0, p.exit_code) - self.assert_(os.path.isfile(output_file)) - - def testSuppressedXmlOutput(self): - """ - Tests that no XML file is generated if the default XML listener is - shut down before RUN_ALL_TESTS is invoked. - """ - - xml_path = os.path.join(gtest_test_utils.GetTempDir(), - GTEST_PROGRAM_NAME + 'out.xml') - if os.path.isfile(xml_path): - os.remove(xml_path) - - command = [GTEST_PROGRAM_PATH, - '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path), - '--shut_down_xml'] - p = gtest_test_utils.Subprocess(command) - if p.terminated_by_signal: - # p.signal is available only if p.terminated_by_signal is True. - self.assertFalse( - p.terminated_by_signal, - '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(1, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, 1)) - - self.assert_(not os.path.isfile(xml_path)) - - def testFilteredTestXmlOutput(self): - """Verifies XML output when a filter is applied. - - Runs a test program that executes only some tests and verifies that - non-selected tests do not show up in the XML output. - """ - - self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0, - extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) - - def testShardedTestXmlOutput(self): - """Verifies XML output when run using multiple shards. - - Runs a test program that executes only one shard and verifies that tests - from other shards do not show up in the XML output. - """ - - self._TestXmlOutput( - GTEST_PROGRAM_NAME, - EXPECTED_SHARDED_TEST_XML, - 0, - extra_env={SHARD_INDEX_ENV_VAR: '0', - TOTAL_SHARDS_ENV_VAR: '10'}) - - def _GetXmlOutput(self, gtest_prog_name, extra_args, extra_env, - expected_exit_code): - """ - Returns the xml output generated by running the program gtest_prog_name. - Furthermore, the program's exit code must be expected_exit_code. - """ - xml_path = os.path.join(gtest_test_utils.GetTempDir(), - gtest_prog_name + 'out.xml') - gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) - - command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] + - extra_args) - environ_copy = os.environ.copy() - if extra_env: - environ_copy.update(extra_env) - p = gtest_test_utils.Subprocess(command, env=environ_copy) - - if p.terminated_by_signal: - self.assert_(False, - '%s was killed by signal %d' % (gtest_prog_name, p.signal)) - else: - self.assert_(p.exited) - self.assertEquals(expected_exit_code, p.exit_code, - "'%s' exited with code %s, which doesn't match " - 'the expected exit code %s.' - % (command, p.exit_code, expected_exit_code)) - actual = minidom.parse(xml_path) - return actual - - def _TestXmlOutput(self, gtest_prog_name, expected_xml, - expected_exit_code, extra_args=None, extra_env=None): - """ - Asserts that the XML document generated by running the program - gtest_prog_name matches expected_xml, a string containing another - XML document. Furthermore, the program's exit code must be - expected_exit_code. - """ - - actual = self._GetXmlOutput(gtest_prog_name, extra_args or [], - extra_env or {}, expected_exit_code) - expected = minidom.parseString(expected_xml) - self.NormalizeXml(actual.documentElement) - self.AssertEquivalentNodes(expected.documentElement, - actual.documentElement) - expected.unlink() - actual.unlink() - - -if __name__ == '__main__': - os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' - gtest_test_utils.Main() diff --git a/thirdparty_builtin/googletest-master-2020-01-07/library.json b/thirdparty_builtin/googletest-master-2020-01-07/library.json deleted file mode 100644 index 91169b7f7..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/library.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "googletest", - "keywords": "unittest, unit, test, gtest, gmock", - "description": "googletest is a testing framework developed by the Testing Technology team with Google's specific requirements and constraints in mind. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports any kind of tests, not just unit tests.", - "license": "BSD-3-Clause", - "homepage": "https://github.com/google/googletest/blob/master/README.md", - "repository": { - "type": "git", - "url": "https://github.com/google/googletest.git" - }, - "version": "1.10.0", - "frameworks": "arduino", - "platforms": [ - "espressif32", - "espressif8266" - ], - "export": { - "include": [ - "googlemock/include/*", - "googlemock/src/*", - "googletest/include/*", - "googletest/src/*" - ], - "exclude": [ - "ci", - "googlemock/cmake", - "googlemock/scripts", - "googlemock/src/gmock-all.cc", - "googlemock/src/gmock_main.cc", - "googlemock/test", - "googlemock/CMakeLists.txt", - "googletest/cmake", - "googletest/scripts", - "googletest/src/gtest-all.cc", - "googletest/src/gtest_main.cc", - "googletest/test", - "googletest/CMakeLists.txt" - ] - }, - "build": { - "flags": [ - "-Igooglemock/include", - "-Igooglemock", - "-Igoogletest/include", - "-Igoogletest" - ], - "srcFilter": [ - "+<*>", - "-<.git/>", - "-", - "-", - "-", - "+", - "+", - "+", - "-", - "-", - "-", - "-", - "-", - "-", - "+", - "+" - ] - } -} diff --git a/thirdparty_builtin/googletest-master-2020-01-07/platformio.ini b/thirdparty_builtin/googletest-master-2020-01-07/platformio.ini deleted file mode 100644 index 7be1f7d58..000000000 --- a/thirdparty_builtin/googletest-master-2020-01-07/platformio.ini +++ /dev/null @@ -1,47 +0,0 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples -; http://docs.platformio.org/page/projectconf.html - - -[platformio] -#src_dir = ./googlemock -#src_dir = ./googletest -src_dir = . - -[env:googletest_esp32] -platform = espressif32 -board = esp32dev -framework = arduino -build_flags = -I./googletest/include -I./googletest -src_filter = +<*> -<.git/> - - - - + + -upload_speed = 921600 - -[env:googlemock_esp32] -platform = espressif32 -board = esp32dev -framework = arduino -build_flags = -I./googlemock/include -I./googletest/include -I./googletest -I./googlemock -src_filter = +<*> -<.git/> - - - + + + -upload_speed = 921600 - -[env:googletest_esp8266] -platform = espressif8266 -board = huzzah -framework = arduino -build_flags = -I./googletest/include -I./googletest -src_filter = +<*> -<.git/> - - - - - - + + -upload_speed = 921600 - -[env:googlemock_esp8266] -platform = espressif8266 -board = huzzah -framework = arduino -build_flags = -I./googlemock/include -I./googletest/include -I./googletest -I./googlemock -src_filter = +<*> -<.git/> - - - + + + -upload_speed = 921600 \ No newline at end of file diff --git a/thirdparty_builtin/googletest/.clang-format b/thirdparty_builtin/googletest/.clang-format new file mode 100644 index 000000000..5b9bfe6d2 --- /dev/null +++ b/thirdparty_builtin/googletest/.clang-format @@ -0,0 +1,4 @@ +# Run manually to reformat a file: +# clang-format -i --style=file +Language: Cpp +BasedOnStyle: Google diff --git a/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/00-bug_report.yml b/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/00-bug_report.yml new file mode 100644 index 000000000..586779ad2 --- /dev/null +++ b/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/00-bug_report.yml @@ -0,0 +1,53 @@ +name: Bug Report +description: Let us know that something does not work as expected. +title: "[Bug]: Please title this bug report" +body: + - type: textarea + id: what-happened + attributes: + label: Describe the issue + description: What happened, and what did you expect to happen? + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce the problem + description: It is important that we are able to reproduce the problem that you are experiencing. Please provide all code and relevant steps to reproduce the problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the problem are also helpful. + validations: + required: true + - type: textarea + id: version + attributes: + label: What version of GoogleTest are you using? + description: Please include the output of `git rev-parse HEAD` or the GoogleTest release version number that you are using. + validations: + required: true + - type: textarea + id: os + attributes: + label: What operating system and version are you using? + description: If you are using a Linux distribution please include the name and version of the distribution as well. + validations: + required: true + - type: textarea + id: compiler + attributes: + label: What compiler and version are you using? + description: Please include the output of `gcc -v` or `clang -v`, or the equivalent for your compiler. + validations: + required: true + - type: textarea + id: buildsystem + attributes: + label: What build system are you using? + description: Please include the output of `bazel --version` or `cmake --version`, or the equivalent for your build system. + validations: + required: true + - type: textarea + id: additional + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/10-feature_request.yml b/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/10-feature_request.yml new file mode 100644 index 000000000..f3bbc091e --- /dev/null +++ b/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/10-feature_request.yml @@ -0,0 +1,33 @@ +name: Feature request +description: Propose a new feature. +title: "[FR]: Please title this feature request" +labels: "enhancement" +body: + - type: textarea + id: version + attributes: + label: Does the feature exist in the most recent commit? + description: We recommend using the latest commit from GitHub in your projects. + validations: + required: true + - type: textarea + id: why + attributes: + label: Why do we need this feature? + description: Ideally, explain why a combination of existing features cannot be used instead. + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Describe the proposal. + description: Include a detailed description of the feature, with usage examples. + validations: + required: true + - type: textarea + id: platform + attributes: + label: Is the feature specific to an operating system, compiler, or build system version? + description: If it is, please specify which versions. + validations: + required: true diff --git a/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/config.yml b/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..65170d10a --- /dev/null +++ b/thirdparty_builtin/googletest/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Get Help + url: https://github.com/google/googletest/discussions + about: Please ask and answer questions here. diff --git a/thirdparty_builtin/googletest/.github/workflows/gtest-ci.yml b/thirdparty_builtin/googletest/.github/workflows/gtest-ci.yml new file mode 100644 index 000000000..03a8cc5e2 --- /dev/null +++ b/thirdparty_builtin/googletest/.github/workflows/gtest-ci.yml @@ -0,0 +1,43 @@ +name: ci + +on: + push: + pull_request: + +env: + BAZEL_CXXOPTS: -std=c++14 + +jobs: + Linux: + runs-on: ubuntu-latest + steps: + + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Tests + run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ... + + macOS: + runs-on: macos-latest + steps: + + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Tests + run: bazel test --cxxopt=-std=c++14 --features=external_include_paths --test_output=errors ... + + + Windows: + runs-on: windows-latest + steps: + + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Tests + run: bazel test --cxxopt=/std:c++14 --features=external_include_paths --test_output=errors ... diff --git a/thirdparty_builtin/googletest/.gitignore b/thirdparty_builtin/googletest/.gitignore new file mode 100644 index 000000000..f08cb72a3 --- /dev/null +++ b/thirdparty_builtin/googletest/.gitignore @@ -0,0 +1,84 @@ +# Ignore CI build directory +build/ +xcuserdata +cmake-build-debug/ +.idea/ +bazel-bin +bazel-genfiles +bazel-googletest +bazel-out +bazel-testlogs +# python +*.pyc + +# Visual Studio files +.vs +*.sdf +*.opensdf +*.VC.opendb +*.suo +*.user +_ReSharper.Caches/ +Win32-Debug/ +Win32-Release/ +x64-Debug/ +x64-Release/ + +# Ignore autoconf / automake files +Makefile.in +aclocal.m4 +configure +build-aux/ +autom4te.cache/ +googletest/m4/libtool.m4 +googletest/m4/ltoptions.m4 +googletest/m4/ltsugar.m4 +googletest/m4/ltversion.m4 +googletest/m4/lt~obsolete.m4 +googlemock/m4 + +# Ignore generated directories. +googlemock/fused-src/ +googletest/fused-src/ + +# macOS files +.DS_Store +googletest/.DS_Store +googletest/xcode/.DS_Store + +# Ignore cmake generated directories and files. +CMakeFiles +CTestTestfile.cmake +Makefile +cmake_install.cmake +googlemock/CMakeFiles +googlemock/CTestTestfile.cmake +googlemock/Makefile +googlemock/cmake_install.cmake +googlemock/gtest +/bin +/googlemock/gmock.dir +/googlemock/gmock_main.dir +/googlemock/RUN_TESTS.vcxproj.filters +/googlemock/RUN_TESTS.vcxproj +/googlemock/INSTALL.vcxproj.filters +/googlemock/INSTALL.vcxproj +/googlemock/gmock_main.vcxproj.filters +/googlemock/gmock_main.vcxproj +/googlemock/gmock.vcxproj.filters +/googlemock/gmock.vcxproj +/googlemock/gmock.sln +/googlemock/ALL_BUILD.vcxproj.filters +/googlemock/ALL_BUILD.vcxproj +/lib +/Win32 +/ZERO_CHECK.vcxproj.filters +/ZERO_CHECK.vcxproj +/RUN_TESTS.vcxproj.filters +/RUN_TESTS.vcxproj +/INSTALL.vcxproj.filters +/INSTALL.vcxproj +/googletest-distribution.sln +/CMakeCache.txt +/ALL_BUILD.vcxproj.filters +/ALL_BUILD.vcxproj diff --git a/thirdparty_builtin/googletest-master-2020-01-07/BUILD.bazel b/thirdparty_builtin/googletest/BUILD.bazel similarity index 84% rename from thirdparty_builtin/googletest-master-2020-01-07/BUILD.bazel rename to thirdparty_builtin/googletest/BUILD.bazel index 9b48aee53..ac62251e1 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/BUILD.bazel +++ b/thirdparty_builtin/googletest/BUILD.bazel @@ -30,15 +30,38 @@ # # Bazel Build for Google C++ Testing Framework(Google Test) -load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") - package(default_visibility = ["//visibility:public"]) licenses(["notice"]) +exports_files(["LICENSE"]) + +config_setting( + name = "qnx", + constraint_values = ["@platforms//os:qnx"], +) + config_setting( name = "windows", - constraint_values = ["@bazel_tools//platforms:windows"], + constraint_values = ["@platforms//os:windows"], +) + +config_setting( + name = "freebsd", + constraint_values = ["@platforms//os:freebsd"], +) + +config_setting( + name = "openbsd", + constraint_values = ["@platforms//os:openbsd"], +) + +config_setting( + name = "msvc_compiler", + flag_values = { + "@bazel_tools//tools/cpp:compiler": "msvc-cl", + }, + visibility = [":__subpackages__"], ) config_setting( @@ -76,6 +99,7 @@ cc_library( "googlemock/include/gmock/*.h", ]), copts = select({ + ":qnx": [], ":windows": [], "//conditions:default": ["-pthread"], }), @@ -94,7 +118,16 @@ cc_library( "googletest/include", ], linkopts = select({ + ":qnx": ["-lregex"], ":windows": [], + ":freebsd": [ + "-lm", + "-pthread", + ], + ":openbsd": [ + "-lm", + "-pthread", + ], "//conditions:default": ["-pthread"], }), deps = select({ @@ -102,9 +135,15 @@ cc_library( "@com_google_absl//absl/debugging:failure_signal_handler", "@com_google_absl//absl/debugging:stacktrace", "@com_google_absl//absl/debugging:symbolize", + "@com_google_absl//absl/flags:flag", + "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/flags:reflection", + "@com_google_absl//absl/flags:usage", "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:any", "@com_google_absl//absl/types:optional", "@com_google_absl//absl/types:variant", + "@com_googlesource_code_re2//:re2", ], "//conditions:default": [], }), diff --git a/thirdparty_builtin/googletest-master-2020-01-07/CMakeLists.txt b/thirdparty_builtin/googletest/CMakeLists.txt similarity index 60% rename from thirdparty_builtin/googletest-master-2020-01-07/CMakeLists.txt rename to thirdparty_builtin/googletest/CMakeLists.txt index 30b8f9e4c..b5ae2b0d0 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/CMakeLists.txt +++ b/thirdparty_builtin/googletest/CMakeLists.txt @@ -5,8 +5,20 @@ 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) + project(googletest-distribution) -set(GOOGLETEST_VERSION 1.10.0) +set(GOOGLETEST_VERSION 1.13.0) + +if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX) + set(CMAKE_CXX_EXTENSIONS OFF) +endif() enable_testing() @@ -16,6 +28,7 @@ include(GNUInstallDirs) #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(BUILD_GMOCK) add_subdirectory( googlemock ) diff --git a/thirdparty_builtin/googletest-master-2020-01-07/CONTRIBUTING.md b/thirdparty_builtin/googletest/CONTRIBUTING.md similarity index 78% rename from thirdparty_builtin/googletest-master-2020-01-07/CONTRIBUTING.md rename to thirdparty_builtin/googletest/CONTRIBUTING.md index bd1843eb4..8bed14b26 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/CONTRIBUTING.md +++ b/thirdparty_builtin/googletest/CONTRIBUTING.md @@ -21,14 +21,14 @@ accept your pull requests. ## Are you a Googler? -If you are a Googler, please make an attempt to submit an internal change rather -than a GitHub Pull Request. If you are not able to submit an internal change a +If you are a Googler, please make an attempt to submit an internal contribution +rather than a GitHub Pull Request. If you are not able to submit internally, a PR is acceptable as an alternative. ## Contributing A Patch 1. Submit an issue describing your proposed change to the - [issue tracker](https://github.com/google/googletest). + [issue tracker](https://github.com/google/googletest/issues). 2. Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one. @@ -36,7 +36,8 @@ PR is acceptable as an alternative. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches. 4. If your proposed change is accepted, and you haven't already done so, sign a - Contributor License Agreement (see details above). + Contributor License Agreement + ([see details above](#contributor-license-agreements)). 5. Fork the desired repo, develop and test your code changes. 6. Ensure that your code adheres to the existing style in the sample to which you are contributing. @@ -79,17 +80,17 @@ fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project. All patches will be expected to conform to the style outlined [here](https://google.github.io/styleguide/cppguide.html). Use -[.clang-format](https://github.com/google/googletest/blob/master/.clang-format) -to check your formatting. +[.clang-format](https://github.com/google/googletest/blob/main/.clang-format) to +check your formatting. ## Requirements for Contributors If you plan to contribute a patch, you need to build Google Test, Google Mock, and their own tests from a git checkout, which has further requirements: -* [Python](https://www.python.org/) v2.3 or newer (for running some of the +* [Python](https://www.python.org/) v3.6 or newer (for running some of the tests and re-generating certain source files from templates) -* [CMake](https://cmake.org/) v2.6.4 or newer +* [CMake](https://cmake.org/) v2.8.12 or newer ## Developing Google Test and Google Mock @@ -101,42 +102,40 @@ To make sure your changes work as intended and don't break existing functionality, you'll want to compile and run Google Test and GoogleMock's own tests. For that you can use CMake: - mkdir mybuild - cd mybuild - cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} +``` +mkdir mybuild +cd mybuild +cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR} +``` To choose between building only Google Test or Google Mock, you may modify your cmake command to be one of each - cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests - cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests +``` +cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests +cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests +``` Make sure you have Python installed, as some of Google Test's tests are written in Python. If the cmake command complains about not being able to find Python (`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it explicitly where your Python executable can be found: - cmake -DPYTHON_EXECUTABLE=path/to/python ... +``` +cmake -DPYTHON_EXECUTABLE=path/to/python ... +``` Next, you can build Google Test and / or Google Mock and all desired tests. On \*nix, this is usually done by - make +``` +make +``` To run the tests, do - make test +``` +make test +``` All tests should pass. - -### Regenerating Source Files - -Some of Google Test's source files are generated from templates (not in the C++ -sense) using a script. For example, the file -*googlemock/include/gmock/gmock-generated-actions.h.pump* is used to generate -*gmock-generated-actions.h* in the same directory. - -You don't need to worry about regenerating the source files unless you need to -modify them. You would then modify the corresponding `.pump` files and run the -'[pump.py](googlemock/scripts/pump.py)' generator script. See the -[Pump Manual](googlemock/docs/pump_manual.md). diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/CONTRIBUTORS b/thirdparty_builtin/googletest/CONTRIBUTORS similarity index 62% rename from thirdparty_builtin/googletest-master-2020-01-07/googletest/CONTRIBUTORS rename to thirdparty_builtin/googletest/CONTRIBUTORS index 1e4afe218..77397a5b5 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/CONTRIBUTORS +++ b/thirdparty_builtin/googletest/CONTRIBUTORS @@ -5,34 +5,61 @@ Ajay Joshi Balázs Dán +Benoit Sigoure Bharat Mediratta +Bogdan Piloca Chandler Carruth Chris Prince Chris Taylor Dan Egnor +Dave MacLachlan +David Anderson +Dean Sturtevant Eric Roman +Gene Volovich Hady Zalek +Hal Burch Jeffrey Yasskin +Jim Keller +Joe Walnes +Jon Wray Jói Sigurðsson Keir Mierle Keith Ray Kenton Varda +Kostya Serebryany Krystian Kuzniarek +Lev Makhlis Manuel Klimek +Mario Tanev +Mark Paskin Markus Heule +Martijn Vels +Matthew Simmons Mika Raento +Mike Bland Miklós Fazekas +Neal Norwitz +Nermin Ozkiranartli +Owen Carlsen +Paneendra Ba Pasi Valminen Patrick Hanna Patrick Riley +Paul Menage Peter Kaminski +Piotr Kaminski Preston Jackson Rainer Klaffenboeck Russ Cox Russ Rufer Sean Mcafee Sigurður Ásgeirsson +Sverre Sundsdal +Szymon Sobik +Takeshi Yoshino Tracy Bialik Vadim Berman Vlad Losev +Wolfgang Klier Zhanyong Wan diff --git a/thirdparty_builtin/googletest-master-2020-01-07/LICENSE b/thirdparty_builtin/googletest/LICENSE similarity index 100% rename from thirdparty_builtin/googletest-master-2020-01-07/LICENSE rename to thirdparty_builtin/googletest/LICENSE diff --git a/thirdparty_builtin/googletest/README.md b/thirdparty_builtin/googletest/README.md new file mode 100644 index 000000000..23eb5026d --- /dev/null +++ b/thirdparty_builtin/googletest/README.md @@ -0,0 +1,123 @@ +# GoogleTest + +### Announcements + +#### Live at Head + +GoogleTest now follows the +[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support). +We recommend +[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it). + +#### Documentation Updates + +Our documentation is now live on GitHub Pages at +https://google.github.io/googletest/. We recommend browsing the documentation on +GitHub Pages rather than directly in the repository. + +#### Release 1.13.0 + +[Release 1.13.0](https://github.com/google/googletest/releases/tag/v1.13.0) is +now available. + +The 1.13.x branch requires at least C++14. + +#### Continuous Integration + +We use Google's internal systems for continuous integration. \ +GitHub Actions were added for the convenience of open source contributors. They +are exclusively maintained by the open source community and not used by the +GoogleTest team. + +#### Coming Soon + +* We are planning to take a dependency on + [Abseil](https://github.com/abseil/abseil-cpp). +* More documentation improvements are planned. + +## Welcome to **GoogleTest**, Google's C++ test framework! + +This repository is a merger of the formerly separate GoogleTest and GoogleMock +projects. These were so closely related that it makes sense to maintain and +release them together. + +### Getting Started + +See the [GoogleTest User's Guide](https://google.github.io/googletest/) for +documentation. We recommend starting with the +[GoogleTest Primer](https://google.github.io/googletest/primer.html). + +More information about building GoogleTest can be found at +[googletest/README.md](googletest/README.md). + +## Features + +* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework. +* Test discovery. +* A rich set of assertions. +* User-defined assertions. +* Death tests. +* Fatal and non-fatal failures. +* Value-parameterized tests. +* Type-parameterized tests. +* Various options for running the tests. +* XML test report generation. + +## Supported Platforms + +GoogleTest follows Google's +[Foundational C++ Support Policy](https://opensource.google/documentation/policies/cplusplus-support). +See +[this table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md) +for a list of currently supported versions compilers, platforms, and build +tools. + +## Who Is Using GoogleTest? + +In addition to many internal projects at Google, GoogleTest is also used by the +following notable projects: + +* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser + and Chrome OS). +* The [LLVM](http://llvm.org/) compiler. +* [Protocol Buffers](https://github.com/google/protobuf), Google's data + interchange format. +* The [OpenCV](http://opencv.org/) computer vision library. + +## Related Open Source Projects + +[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based +automated test-runner and Graphical User Interface with powerful features for +Windows and Linux platforms. + +[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that +runs your test binary, allows you to track its progress via a progress bar, and +displays a list of test failures. Clicking on one shows failure text. GoogleTest +UI is written in C#. + +[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event +listener for GoogleTest that implements the +[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test +result output. If your test runner understands TAP, you may find it useful. + +[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that +runs tests from your binary in parallel to provide significant speed-up. + +[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) +is a VS Code extension allowing to view GoogleTest in a tree view and run/debug +your tests. + +[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS +Code extension allowing to view GoogleTest in a tree view and run/debug your +tests. + +[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser +that generates stub code for GoogleTest. + +## Contributing Changes + +Please read +[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/main/CONTRIBUTING.md) +for details on how to contribute to this project. + +Happy testing! diff --git a/thirdparty_builtin/googletest/WORKSPACE b/thirdparty_builtin/googletest/WORKSPACE new file mode 100644 index 000000000..1c8ea24d3 --- /dev/null +++ b/thirdparty_builtin/googletest/WORKSPACE @@ -0,0 +1,27 @@ +workspace(name = "com_google_googletest") + +load("//:googletest_deps.bzl", "googletest_deps") +googletest_deps() + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "rules_python", # 2023-01-10T22:00:51Z + sha256 = "5de54486a60ad8948dabe49605bb1c08053e04001a431ab3e96745b4d97a4419", + strip_prefix = "rules_python-70cce26432187a60b4e950118791385e6fb3c26f", + urls = ["https://github.com/bazelbuild/rules_python/archive/70cce26432187a60b4e950118791385e6fb3c26f.zip"], +) + +http_archive( + name = "bazel_skylib", # 2022-11-16T18:29:32Z + sha256 = "a22290c26d29d3ecca286466f7f295ac6cbe32c0a9da3a91176a90e0725e3649", + strip_prefix = "bazel-skylib-5bfcb1a684550626ce138fe0fe8f5f702b3764c3", + urls = ["https://github.com/bazelbuild/bazel-skylib/archive/5bfcb1a684550626ce138fe0fe8f5f702b3764c3.zip"], +) + +http_archive( + name = "platforms", # 2022-11-09T19:18:22Z + sha256 = "b4a3b45dc4202e2b3e34e3bc49d2b5b37295fc23ea58d88fb9e01f3642ad9b55", + strip_prefix = "platforms-3fbc687756043fb58a407c2ea8c944bc2fe1d922", + urls = ["https://github.com/bazelbuild/platforms/archive/3fbc687756043fb58a407c2ea8c944bc2fe1d922.zip"], +) diff --git a/thirdparty_builtin/googletest/ci/linux-presubmit.sh b/thirdparty_builtin/googletest/ci/linux-presubmit.sh new file mode 100644 index 000000000..6bac88787 --- /dev/null +++ b/thirdparty_builtin/googletest/ci/linux-presubmit.sh @@ -0,0 +1,137 @@ +#!/bin/bash +# +# Copyright 2020, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +set -euox pipefail + +readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20230217" +readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20230120" + +if [[ -z ${GTEST_ROOT:-} ]]; then + GTEST_ROOT="$(realpath $(dirname ${0})/..)" +fi + +if [[ -z ${STD:-} ]]; then + STD="c++14 c++17 c++20" +fi + +# Test the CMake build +for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do + for cmake_off_on in OFF ON; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --tmpfs="/build:exec" \ + --workdir="/build" \ + --rm \ + --env="CC=${cc}" \ + --env=CXXFLAGS="-Werror -Wdeprecated" \ + ${LINUX_LATEST_CONTAINER} \ + /bin/bash -c " + cmake /src \ + -DCMAKE_CXX_STANDARD=14 \ + -Dgtest_build_samples=ON \ + -Dgtest_build_tests=ON \ + -Dgmock_build_tests=ON \ + -Dcxx_no_exception=${cmake_off_on} \ + -Dcxx_no_rtti=${cmake_off_on} && \ + make -j$(nproc) && \ + ctest -j$(nproc) --output-on-failure" + done +done + +# Do one test with an older version of GCC +time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/usr/local/bin/gcc" \ + --env="BAZEL_CXXOPTS=-std=c++14" \ + ${LINUX_GCC_FLOOR_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --copt="-Wno-error=pragmas" \ + --distdir="/bazel-distdir" \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors + +# Test GCC +for std in ${STD}; do + for absl in 0 1; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/usr/local/bin/gcc" \ + --env="BAZEL_CXXOPTS=-std=${std}" \ + ${LINUX_LATEST_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --define="absl=${absl}" \ + --distdir="/bazel-distdir" \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors + done +done + +# Test Clang +for std in ${STD}; do + for absl in 0 1; do + time docker run \ + --volume="${GTEST_ROOT}:/src:ro" \ + --workdir="/src" \ + --rm \ + --env="CC=/opt/llvm/clang/bin/clang" \ + --env="BAZEL_CXXOPTS=-std=${std}" \ + ${LINUX_LATEST_CONTAINER} \ + /usr/local/bin/bazel test ... \ + --copt="--gcc-toolchain=/usr/local" \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wuninitialized" \ + --copt="-Wundef" \ + --define="absl=${absl}" \ + --distdir="/bazel-distdir" \ + --features=external_include_paths \ + --keep_going \ + --linkopt="--gcc-toolchain=/usr/local" \ + --show_timestamps \ + --test_output=errors + done +done diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/upload_gtest.py b/thirdparty_builtin/googletest/ci/macos-presubmit.sh old mode 100755 new mode 100644 similarity index 52% rename from thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/upload_gtest.py rename to thirdparty_builtin/googletest/ci/macos-presubmit.sh index be19ae809..681ebc2a9 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/scripts/upload_gtest.py +++ b/thirdparty_builtin/googletest/ci/macos-presubmit.sh @@ -1,6 +1,6 @@ -#!/usr/bin/env python +#!/bin/bash # -# Copyright 2009, Google Inc. +# Copyright 2020, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without @@ -29,50 +29,48 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""upload_gtest.py v0.1.0 -- uploads a Google Test patch for review. +set -euox pipefail -This simple wrapper passes all command line flags and ---cc=googletestframework@googlegroups.com to upload.py. +if [[ -z ${GTEST_ROOT:-} ]]; then + GTEST_ROOT="$(realpath $(dirname ${0})/..)" +fi -USAGE: upload_gtest.py [options for upload.py] -""" +# Test the CMake build +for cmake_off_on in OFF ON; do + BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX) + cd ${BUILD_DIR} + time cmake ${GTEST_ROOT} \ + -DCMAKE_CXX_STANDARD=14 \ + -Dgtest_build_samples=ON \ + -Dgtest_build_tests=ON \ + -Dgmock_build_tests=ON \ + -Dcxx_no_exception=${cmake_off_on} \ + -Dcxx_no_rtti=${cmake_off_on} + time make + time ctest -j$(nproc) --output-on-failure +done -__author__ = 'wan@google.com (Zhanyong Wan)' +# Test the Bazel build -import os -import sys +# If we are running on Kokoro, check for a versioned Bazel binary. +KOKORO_GFILE_BAZEL_BIN="bazel-5.1.1-darwin-x86_64" +if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then + BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}" + chmod +x ${BAZEL_BIN} +else + BAZEL_BIN="bazel" +fi -CC_FLAG = '--cc=' -GTEST_GROUP = 'googletestframework@googlegroups.com' - - -def main(): - # Finds the path to upload.py, assuming it is in the same directory - # as this file. - my_dir = os.path.dirname(os.path.abspath(__file__)) - upload_py_path = os.path.join(my_dir, 'upload.py') - - # Adds Google Test discussion group to the cc line if it's not there - # already. - upload_py_argv = [upload_py_path] - found_cc_flag = False - for arg in sys.argv[1:]: - if arg.startswith(CC_FLAG): - found_cc_flag = True - cc_line = arg[len(CC_FLAG):] - cc_list = [addr for addr in cc_line.split(',') if addr] - if GTEST_GROUP not in cc_list: - cc_list.append(GTEST_GROUP) - upload_py_argv.append(CC_FLAG + ','.join(cc_list)) - else: - upload_py_argv.append(arg) - - if not found_cc_flag: - upload_py_argv.append(CC_FLAG + GTEST_GROUP) - - # Invokes upload.py with the modified command line flags. - os.execv(upload_py_path, upload_py_argv) - - -if __name__ == '__main__': - main() +cd ${GTEST_ROOT} +for absl in 0 1; do + ${BAZEL_BIN} test ... \ + --copt="-Wall" \ + --copt="-Werror" \ + --copt="-Wundef" \ + --cxxopt="-std=c++14" \ + --define="absl=${absl}" \ + --features=external_include_paths \ + --keep_going \ + --show_timestamps \ + --test_output=errors +done diff --git a/thirdparty_builtin/googletest/ci/windows-presubmit.bat b/thirdparty_builtin/googletest/ci/windows-presubmit.bat new file mode 100644 index 000000000..48962eb9e --- /dev/null +++ b/thirdparty_builtin/googletest/ci/windows-presubmit.bat @@ -0,0 +1,58 @@ +SETLOCAL ENABLEDELAYEDEXPANSION + +SET BAZEL_EXE=%KOKORO_GFILE_DIR%\bazel-5.1.1-windows-x86_64.exe + +SET PATH=C:\Python34;%PATH% +SET BAZEL_PYTHON=C:\python34\python.exe +SET BAZEL_SH=C:\tools\msys64\usr\bin\bash.exe +SET CMAKE_BIN="cmake.exe" +SET CTEST_BIN="ctest.exe" +SET CTEST_OUTPUT_ON_FAILURE=1 +SET CMAKE_BUILD_PARALLEL_LEVEL=16 +SET CTEST_PARALLEL_LEVEL=16 + +IF EXIST git\googletest ( + CD git\googletest +) ELSE IF EXIST github\googletest ( + CD github\googletest +) + +IF %errorlevel% neq 0 EXIT /B 1 + +:: ---------------------------------------------------------------------------- +:: CMake +MKDIR cmake_msvc2022 +CD cmake_msvc2022 + +%CMAKE_BIN% .. ^ + -G "Visual Studio 17 2022" ^ + -DPYTHON_EXECUTABLE:FILEPATH=c:\python37\python.exe ^ + -DPYTHON_INCLUDE_DIR:PATH=c:\python37\include ^ + -DPYTHON_LIBRARY:FILEPATH=c:\python37\lib\site-packages\pip ^ + -Dgtest_build_samples=ON ^ + -Dgtest_build_tests=ON ^ + -Dgmock_build_tests=ON +IF %errorlevel% neq 0 EXIT /B 1 + +%CMAKE_BIN% --build . --target ALL_BUILD --config Debug -- -maxcpucount +IF %errorlevel% neq 0 EXIT /B 1 + +%CTEST_BIN% -C Debug --timeout 600 +IF %errorlevel% neq 0 EXIT /B 1 + +CD .. +RMDIR /S /Q cmake_msvc2022 + +:: ---------------------------------------------------------------------------- +:: Bazel + +SET BAZEL_VS=C:\Program Files\Microsoft Visual Studio\2022\Community +%BAZEL_EXE% test ... ^ + --compilation_mode=dbg ^ + --copt=/std:c++14 ^ + --copt=/WX ^ + --features=external_include_paths ^ + --keep_going ^ + --test_output=errors ^ + --test_tag_filters=-no_test_msvc2017 +IF %errorlevel% neq 0 EXIT /B 1 diff --git a/thirdparty_builtin/googletest/docs/_config.yml b/thirdparty_builtin/googletest/docs/_config.yml new file mode 100644 index 000000000..d12867eab --- /dev/null +++ b/thirdparty_builtin/googletest/docs/_config.yml @@ -0,0 +1 @@ +title: GoogleTest diff --git a/thirdparty_builtin/googletest/docs/_data/navigation.yml b/thirdparty_builtin/googletest/docs/_data/navigation.yml new file mode 100644 index 000000000..9f3332708 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/_data/navigation.yml @@ -0,0 +1,43 @@ +nav: +- section: "Get Started" + items: + - title: "Supported Platforms" + url: "/platforms.html" + - title: "Quickstart: Bazel" + url: "/quickstart-bazel.html" + - title: "Quickstart: CMake" + url: "/quickstart-cmake.html" +- section: "Guides" + items: + - title: "GoogleTest Primer" + url: "/primer.html" + - title: "Advanced Topics" + url: "/advanced.html" + - title: "Mocking for Dummies" + url: "/gmock_for_dummies.html" + - title: "Mocking Cookbook" + url: "/gmock_cook_book.html" + - title: "Mocking Cheat Sheet" + url: "/gmock_cheat_sheet.html" +- section: "References" + items: + - title: "Testing Reference" + url: "/reference/testing.html" + - title: "Mocking Reference" + url: "/reference/mocking.html" + - title: "Assertions" + url: "/reference/assertions.html" + - title: "Matchers" + url: "/reference/matchers.html" + - title: "Actions" + url: "/reference/actions.html" + - title: "Testing FAQ" + url: "/faq.html" + - title: "Mocking FAQ" + url: "/gmock_faq.html" + - title: "Code Samples" + url: "/samples.html" + - title: "Using pkg-config" + url: "/pkgconfig.html" + - title: "Community Documentation" + url: "/community_created_documentation.html" diff --git a/thirdparty_builtin/googletest/docs/_layouts/default.html b/thirdparty_builtin/googletest/docs/_layouts/default.html new file mode 100644 index 000000000..c7f331b87 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/_layouts/default.html @@ -0,0 +1,58 @@ + + + + + + + +{% seo %} + + + + + + +
+
+ {{ content }} +
+ +
+ + + + diff --git a/thirdparty_builtin/googletest/docs/_sass/main.scss b/thirdparty_builtin/googletest/docs/_sass/main.scss new file mode 100644 index 000000000..92edc877a --- /dev/null +++ b/thirdparty_builtin/googletest/docs/_sass/main.scss @@ -0,0 +1,200 @@ +// Styles for GoogleTest docs website on GitHub Pages. +// Color variables are defined in +// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables + +$sidebar-width: 260px; + +body { + display: flex; + margin: 0; +} + +.sidebar { + background: $black; + color: $text-white; + flex-shrink: 0; + height: 100vh; + overflow: auto; + position: sticky; + top: 0; + width: $sidebar-width; +} + +.sidebar h1 { + font-size: 1.5em; +} + +.sidebar h2 { + color: $gray-light; + font-size: 0.8em; + font-weight: normal; + margin-bottom: 0.8em; + padding-left: 2.5em; + text-transform: uppercase; +} + +.sidebar .header { + background: $black; + padding: 2em; + position: sticky; + top: 0; + width: 100%; +} + +.sidebar .header a { + color: $text-white; + text-decoration: none; +} + +.sidebar .nav-toggle { + display: none; +} + +.sidebar .expander { + cursor: pointer; + display: none; + height: 3em; + position: absolute; + right: 1em; + top: 1.5em; + width: 3em; +} + +.sidebar .expander .arrow { + border: solid $white; + border-width: 0 3px 3px 0; + display: block; + height: 0.7em; + margin: 1em auto; + transform: rotate(45deg); + transition: transform 0.5s; + width: 0.7em; +} + +.sidebar nav { + width: 100%; +} + +.sidebar nav ul { + list-style-type: none; + margin-bottom: 1em; + padding: 0; + + &:last-child { + margin-bottom: 2em; + } + + a { + text-decoration: none; + } + + li { + color: $text-white; + padding-left: 2em; + text-decoration: none; + } + + li.active { + background: $border-gray-darker; + font-weight: bold; + } + + li:hover { + background: $border-gray-darker; + } +} + +.main { + background-color: $bg-gray; + width: calc(100% - #{$sidebar-width}); +} + +.main .main-inner { + background-color: $white; + padding: 2em; +} + +.main .footer { + margin: 0; + padding: 2em; +} + +.main table th { + text-align: left; +} + +.main .callout { + border-left: 0.25em solid $white; + padding: 1em; + + a { + text-decoration: underline; + } + + &.important { + background-color: $bg-yellow-light; + border-color: $bg-yellow; + color: $black; + } + + &.note { + background-color: $bg-blue-light; + border-color: $text-blue; + color: $text-blue; + } + + &.tip { + background-color: $green-000; + border-color: $green-700; + color: $green-700; + } + + &.warning { + background-color: $red-000; + border-color: $text-red; + color: $text-red; + } +} + +.main .good pre { + background-color: $bg-green-light; +} + +.main .bad pre { + background-color: $red-000; +} + +@media all and (max-width: 768px) { + body { + flex-direction: column; + } + + .sidebar { + height: auto; + position: relative; + width: 100%; + } + + .sidebar .expander { + display: block; + } + + .sidebar nav { + height: 0; + overflow: hidden; + } + + .sidebar .nav-toggle:checked { + & ~ nav { + height: auto; + } + + & + .expander .arrow { + transform: rotate(-135deg); + } + } + + .main { + width: 100%; + } +} diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/advanced.md b/thirdparty_builtin/googletest/docs/advanced.md similarity index 66% rename from thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/advanced.md rename to thirdparty_builtin/googletest/docs/advanced.md index 10af769ea..3871db13b 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/advanced.md +++ b/thirdparty_builtin/googletest/docs/advanced.md @@ -1,11 +1,9 @@ -# Advanced googletest Topics - - +# Advanced GoogleTest Topics ## Introduction -Now that you have read the [googletest Primer](primer.md) and learned how to -write tests using googletest, it's time to learn some new tricks. This document +Now that you have read the [GoogleTest Primer](primer.md) and learned how to +write tests using GoogleTest, it's time to learn some new tricks. This document will show you more assertions as well as how to construct complex failure messages, propagate fatal failures, reuse and speed up your test fixtures, and use various flags with your tests. @@ -17,73 +15,17 @@ assertions. ### Explicit Success and Failure -These three assertions do not actually test a value or expression. Instead, they -generate a success or failure directly. Like the macros that actually perform a -test, you may stream a custom failure message into them. - -```c++ -SUCCEED(); -``` - -Generates a success. This does **NOT** make the overall test succeed. A test is -considered successful only if none of its assertions fail during its execution. - -NOTE: `SUCCEED()` is purely documentary and currently doesn't generate any -user-visible output. However, we may add `SUCCEED()` messages to googletest's -output in the future. - -```c++ -FAIL(); -ADD_FAILURE(); -ADD_FAILURE_AT("file_path", line_number); -``` - -`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` -generate a nonfatal failure. These are useful when control flow, rather than a -Boolean expression, determines the test's success or failure. For example, you -might want to write something like: - -```c++ -switch(expression) { - case 1: - ... some checks ... - case 2: - ... some other checks ... - default: - FAIL() << "We shouldn't get here."; -} -``` - -NOTE: you can only use `FAIL()` in functions that return `void`. See the -[Assertion Placement section](#assertion-placement) for more information. +See [Explicit Success and Failure](reference/assertions.md#success-failure) in +the Assertions Reference. ### Exception Assertions -These are for verifying that a piece of code throws (or does not throw) an -exception of the given type: - -Fatal assertion | Nonfatal assertion | Verifies ------------------------------------------- | ------------------------------------------ | -------- -`ASSERT_THROW(statement, exception_type);` | `EXPECT_THROW(statement, exception_type);` | `statement` throws an exception of the given type -`ASSERT_ANY_THROW(statement);` | `EXPECT_ANY_THROW(statement);` | `statement` throws an exception of any type -`ASSERT_NO_THROW(statement);` | `EXPECT_NO_THROW(statement);` | `statement` doesn't throw any exception - -Examples: - -```c++ -ASSERT_THROW(Foo(5), bar_exception); - -EXPECT_NO_THROW({ - int n = 5; - Bar(&n); -}); -``` - -**Availability**: requires exceptions to be enabled in the build environment +See [Exception Assertions](reference/assertions.md#exceptions) in the Assertions +Reference. ### Predicate Assertions for Better Error Messages -Even though googletest has a rich set of assertions, they can never be complete, +Even though GoogleTest has a rich set of assertions, they can never be complete, as it's impossible (nor a good idea) to anticipate all scenarios a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a complex expression, for lack of a better macro. This has the problem of not @@ -93,66 +35,15 @@ failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this is awkward especially when the expression has side-effects or is expensive to evaluate. -googletest gives you three different options to solve this problem: +GoogleTest gives you three different options to solve this problem: #### Using an Existing Boolean Function If you already have a function or functor that returns `bool` (or a type that can be implicitly converted to `bool`), you can use it in a *predicate -assertion* to get the function arguments printed for free: - - - -| Fatal assertion | Nonfatal assertion | Verifies | -| --------------------------------- | --------------------------------- | --------------------------- | -| `ASSERT_PRED1(pred1, val1)` | `EXPECT_PRED1(pred1, val1)` | `pred1(val1)` is true | -| `ASSERT_PRED2(pred2, val1, val2)` | `EXPECT_PRED2(pred2, val1, val2)` | `pred2(val1, val2)` is true | -| `...` | `...` | `...` | - - -In the above, `predn` is an `n`-ary predicate function or functor, where `val1`, -`val2`, ..., and `valn` are its arguments. The assertion succeeds if the -predicate returns `true` when applied to the given arguments, and fails -otherwise. When the assertion fails, it prints the value of each argument. In -either case, the arguments are evaluated exactly once. - -Here's an example. Given - -```c++ -// Returns true if m and n have no common divisors except 1. -bool MutuallyPrime(int m, int n) { ... } - -const int a = 3; -const int b = 4; -const int c = 10; -``` - -the assertion - -```c++ - EXPECT_PRED2(MutuallyPrime, a, b); -``` - -will succeed, while the assertion - -```c++ - EXPECT_PRED2(MutuallyPrime, b, c); -``` - -will fail with the message - -```none -MutuallyPrime(b, c) is false, where -b is 4 -c is 10 -``` - -> NOTE: -> -> 1. If you see a compiler error "no matching function to call" when using -> `ASSERT_PRED*` or `EXPECT_PRED*`, please see -> [this](faq.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert-pred-how-do-i-fix-it) -> for how to resolve it. +assertion* to get the function arguments printed for free. See +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions +Reference for details. #### Using a Function That Returns an AssertionResult @@ -187,11 +78,11 @@ write a predicate function that returns `AssertionResult` instead of `bool`. For example, if you define `IsEven()` as: ```c++ -::testing::AssertionResult IsEven(int n) { +testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) - return ::testing::AssertionSuccess(); + return testing::AssertionSuccess(); else - return ::testing::AssertionFailure() << n << " is odd"; + return testing::AssertionFailure() << n << " is odd"; } ``` @@ -225,11 +116,11 @@ are fine with making the predicate slower in the success case, you can supply a success message: ```c++ -::testing::AssertionResult IsEven(int n) { +testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) - return ::testing::AssertionSuccess() << n << " is even"; + return testing::AssertionSuccess() << n << " is even"; else - return ::testing::AssertionFailure() << n << " is odd"; + return testing::AssertionFailure() << n << " is odd"; } ``` @@ -243,176 +134,53 @@ Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print #### Using a Predicate-Formatter -If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and -`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your -predicate do not support streaming to `ostream`, you can instead use the -following *predicate-formatter assertions* to *fully* customize how the message -is formatted: - -Fatal assertion | Nonfatal assertion | Verifies ------------------------------------------------- | ------------------------------------------------ | -------- -`ASSERT_PRED_FORMAT1(pred_format1, val1);` | `EXPECT_PRED_FORMAT1(pred_format1, val1);` | `pred_format1(val1)` is successful -`ASSERT_PRED_FORMAT2(pred_format2, val1, val2);` | `EXPECT_PRED_FORMAT2(pred_format2, val1, val2);` | `pred_format2(val1, val2)` is successful -`...` | `...` | ... - -The difference between this and the previous group of macros is that instead of -a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a *predicate-formatter* -(`pred_formatn`), which is a function or functor with the signature: - -```c++ -::testing::AssertionResult PredicateFormattern(const char* expr1, - const char* expr2, - ... - const char* exprn, - T1 val1, - T2 val2, - ... - Tn valn); -``` - -where `val1`, `val2`, ..., and `valn` are the values of the predicate arguments, -and `expr1`, `expr2`, ..., and `exprn` are the corresponding expressions as they -appear in the source code. The types `T1`, `T2`, ..., and `Tn` can be either -value types or reference types. For example, if an argument has type `Foo`, you -can declare it as either `Foo` or `const Foo&`, whichever is appropriate. - -As an example, let's improve the failure message in `MutuallyPrime()`, which was -used with `EXPECT_PRED2()`: - -```c++ -// Returns the smallest prime common divisor of m and n, -// or 1 when m and n are mutually prime. -int SmallestPrimeCommonDivisor(int m, int n) { ... } - -// A predicate-formatter for asserting that two integers are mutually prime. -::testing::AssertionResult AssertMutuallyPrime(const char* m_expr, - const char* n_expr, - int m, - int n) { - if (MutuallyPrime(m, n)) return ::testing::AssertionSuccess(); - - return ::testing::AssertionFailure() << m_expr << " and " << n_expr - << " (" << m << " and " << n << ") are not mutually prime, " - << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); -} -``` - -With this predicate-formatter, we can use - -```c++ - EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); -``` - -to generate the message - -```none -b and c (4 and 10) are not mutually prime, as they have a common divisor 2. -``` - -As you may have realized, many of the built-in assertions we introduced earlier -are special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are -indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. +If you find the default message generated by +[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and +[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some +arguments to your predicate do not support streaming to `ostream`, you can +instead use *predicate-formatter assertions* to *fully* customize how the +message is formatted. See +[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the +Assertions Reference for details. ### Floating-Point Comparison -Comparing floating-point numbers is tricky. Due to round-off errors, it is very -unlikely that two floating-points will match exactly. Therefore, `ASSERT_EQ` 's -naive comparison usually doesn't work. And since floating-points can have a wide -value range, no single fixed error bound works. It's better to compare by a -fixed relative error bound, except for values close to 0 due to the loss of -precision there. - -In general, for floating-point comparison to make sense, the user needs to -carefully choose the error bound. If they don't want or care to, comparing in -terms of Units in the Last Place (ULPs) is a good default, and googletest -provides assertions to do this. Full details about ULPs are quite long; if you -want to learn more, see -[here](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - -#### Floating-Point Macros - - - -| Fatal assertion | Nonfatal assertion | Verifies | -| ------------------------------- | ------------------------------- | ---------------------------------------- | -| `ASSERT_FLOAT_EQ(val1, val2);` | `EXPECT_FLOAT_EQ(val1, val2);` | the two `float` values are almost equal | -| `ASSERT_DOUBLE_EQ(val1, val2);` | `EXPECT_DOUBLE_EQ(val1, val2);` | the two `double` values are almost equal | - - - -By "almost equal" we mean the values are within 4 ULP's from each other. - -The following assertions allow you to choose the acceptable error bound: - - - -| Fatal assertion | Nonfatal assertion | Verifies | -| ------------------------------------- | ------------------------------------- | -------------------------------------------------------------------------------- | -| `ASSERT_NEAR(val1, val2, abs_error);` | `EXPECT_NEAR(val1, val2, abs_error);` | the difference between `val1` and `val2` doesn't exceed the given absolute error | - - +See [Floating-Point Comparison](reference/assertions.md#floating-point) in the +Assertions Reference. #### Floating-Point Predicate-Format Functions Some floating-point operations are useful, but not that often used. In order to avoid an explosion of new macros, we provide them as predicate-format functions -that can be used in predicate assertion macros (e.g. `EXPECT_PRED_FORMAT2`, -etc). - -```c++ -EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); -EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); -``` - -Verifies that `val1` is less than, or almost equal to, `val2`. You can replace -`EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. - -### Asserting Using gMock Matchers - -[gMock](../../googlemock) comes with a library of matchers for validating -arguments passed to mock objects. A gMock *matcher* is basically a predicate -that knows how to describe itself. It can be used in these assertion macros: - - - -| Fatal assertion | Nonfatal assertion | Verifies | -| ------------------------------ | ------------------------------ | --------------------- | -| `ASSERT_THAT(value, matcher);` | `EXPECT_THAT(value, matcher);` | value matches matcher | - - - -For example, `StartsWith(prefix)` is a matcher that matches a string starting -with `prefix`, and you can write: +that can be used in the predicate assertion macro +[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for +example: ```c++ -using ::testing::StartsWith; +using ::testing::FloatLE; +using ::testing::DoubleLE; ... - // Verifies that Foo() returns a string starting with "Hello". - EXPECT_THAT(Foo(), StartsWith("Hello")); +EXPECT_PRED_FORMAT2(FloatLE, val1, val2); +EXPECT_PRED_FORMAT2(DoubleLE, val1, val2); ``` -Read this -[recipe](../../googlemock/docs/cook_book.md#using-matchers-in-googletest-assertions) -in the gMock Cookbook for more details. +The above code verifies that `val1` is less than, or approximately equal to, +`val2`. -gMock has a rich set of matchers. You can do many things googletest cannot do -alone with them. For a list of matchers gMock provides, read -[this](../../googlemock/docs/cook_book.md##using-matchers). It's easy to write -your [own matchers](../../googlemock/docs/cook_book.md#NewMatchers) too. +### Asserting Using gMock Matchers -gMock is bundled with googletest, so you don't need to add any build dependency -in order to take advantage of this. Just include `"testing/base/public/gmock.h"` -and you're ready to go. +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. ### More String Assertions (Please read the [previous](#asserting-using-gmock-matchers) section first if you haven't.) -You can use the gMock -[string matchers](../../googlemock/docs/cheat_sheet.md#string-matchers) with -`EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks -(sub-string, prefix, suffix, regular expression, and etc). For example, +You can use the gMock [string matchers](reference/matchers.md#string-matchers) +with [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string +comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For +example, ```c++ using ::testing::HasSubstr; @@ -422,37 +190,10 @@ using ::testing::MatchesRegex; EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); ``` -If the string contains a well-formed HTML or XML document, you can check whether -its DOM tree matches an -[XPath expression](http://www.w3.org/TR/xpath/#contents): - -```c++ -// Currently still in //template/prototemplate/testing:xpath_matcher -#include "template/prototemplate/testing/xpath_matcher.h" -using prototemplate::testing::MatchesXPath; -EXPECT_THAT(html_string, MatchesXPath("//a[text()='click here']")); -``` - ### Windows HRESULT assertions -These assertions test for `HRESULT` success or failure. - -Fatal assertion | Nonfatal assertion | Verifies --------------------------------------- | -------------------------------------- | -------- -`ASSERT_HRESULT_SUCCEEDED(expression)` | `EXPECT_HRESULT_SUCCEEDED(expression)` | `expression` is a success `HRESULT` -`ASSERT_HRESULT_FAILED(expression)` | `EXPECT_HRESULT_FAILED(expression)` | `expression` is a failure `HRESULT` - -The generated output contains the human-readable error message associated with -the `HRESULT` code returned by `expression`. - -You might use them like this: - -```c++ -CComPtr shell; -ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); -CComVariant empty; -ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); -``` +See [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the +Assertions Reference. ### Type Assertions @@ -464,10 +205,9 @@ You can call the function to assert that types `T1` and `T2` are the same. The function does nothing if the assertion is satisfied. If the types are different, the function call will -fail to compile, the compiler error message will say that -`T1 and T2 are not the same type` and most likely (depending on the compiler) -show you the actual values of `T1` and `T2`. This is mainly useful inside -template code. +fail to compile, the compiler error message will say that `T1 and T2 are not the +same type` and most likely (depending on the compiler) show you the actual +values of `T1` and `T2`. This is mainly useful inside template code. **Caveat**: When used inside a member function of a class template or a function template, `StaticAssertTypeEq()` is effective only if the function is @@ -476,7 +216,7 @@ instantiated. For example, given: ```c++ template class Foo { public: - void Bar() { ::testing::StaticAssertTypeEq(); } + void Bar() { testing::StaticAssertTypeEq(); } }; ``` @@ -516,6 +256,7 @@ any assertion inside of it. If changing the function's type is not an option, you should just use assertions that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. +{: .callout .note} NOTE: Constructors and destructors are not considered void-returning functions, according to the C++ language specification, and so you may not use fatal assertions in them; you'll get a compilation error if you try. Instead, either @@ -523,16 +264,49 @@ call `abort` and crash the entire test executable, or put the fatal assertion in a `SetUp`/`TearDown` function; see [constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp) +{: .callout .warning} WARNING: A fatal assertion in a helper function (private void-returning method) -called from a constructor or destructor does not does not terminate the current -test, as your intuition might suggest: it merely returns from the constructor or +called from a constructor or destructor does not terminate the current test, as +your intuition might suggest: it merely returns from the constructor or destructor early, possibly leaving your object in a partially-constructed or partially-destructed state! You almost certainly want to `abort` or use `SetUp`/`TearDown` instead. -## Teaching googletest How to Print Your Values +## Skipping test execution + +Related to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test +execution at runtime with the `GTEST_SKIP()` macro. This is useful when you need +to check for preconditions of the system under test during runtime and skip +tests in a meaningful way. + +`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods +of classes derived from either `::testing::Environment` or `::testing::Test`. +For example: + +```c++ +TEST(SkipTest, DoesSkip) { + GTEST_SKIP() << "Skipping single test"; + EXPECT_EQ(0, 1); // Won't fail; it won't be executed +} + +class SkipFixture : public ::testing::Test { + protected: + void SetUp() override { + GTEST_SKIP() << "Skipping all tests for this fixture"; + } +}; + +// Tests for SkipFixture won't be executed. +TEST_F(SkipFixture, SkipsOneTest) { + EXPECT_EQ(5, 7); // Won't fail +} +``` + +As with assertion macros, you can stream a custom message into `GTEST_SKIP()`. + +## Teaching GoogleTest How to Print Your Values -When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument +When a test assertion such as `EXPECT_EQ` fails, GoogleTest prints the argument values to help you debug. It does this using a user-extensible value printer. This printer knows how to print built-in C++ types, native arrays, STL @@ -541,80 +315,103 @@ prints the raw bytes in the value and hopes that you the user can figure it out. As mentioned earlier, the printer is *extensible*. That means you can teach it to do a better job at printing your particular type than to dump the bytes. To -do that, define `<<` for your type: - -```c++ -#include +do that, define an `AbslStringify()` overload as a `friend` function template +for your type: +```cpp namespace foo { -class Bar { // We want googletest to be able to print instances of this. -... - // Create a free inline friend function. - friend std::ostream& operator<<(std::ostream& os, const Bar& bar) { - return os << bar.DebugString(); // whatever needed to print bar to os +class Point { // We want GoogleTest to be able to print instances of this. + ... + // Provide a friend overload. + template + friend void AbslStringify(Sink& sink, const Point& point) { + absl::Format(&sink, "(%d, %d)", point.x, point.y); } + + int x; + int y; }; // If you can't declare the function in the class it's important that the -// << operator is defined in the SAME namespace that defines Bar. C++'s look-up -// rules rely on that. -std::ostream& operator<<(std::ostream& os, const Bar& bar) { - return os << bar.DebugString(); // whatever needed to print bar to os +// AbslStringify overload is defined in the SAME namespace that defines Point. +// C++'s look-up rules rely on that. +enum class EnumWithStringify { kMany = 0, kChoices = 1 }; + +template +void AbslStringify(Sink& sink, EnumWithStringify e) { + absl::Format(&sink, "%s", e == EnumWithStringify::kMany ? "Many" : "Choices"); } } // namespace foo ``` -Sometimes, this might not be an option: your team may consider it bad style to -have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that -doesn't do what you want (and you cannot change it). If so, you can instead -define a `PrintTo()` function like this: +{: .callout .note} +Note: `AbslStringify()` utilizes a generic "sink" buffer to construct its +string. For more information about supported operations on `AbslStringify()`'s +sink, see go/abslstringify. + +`AbslStringify()` can also use `absl::StrFormat`'s catch-all `%v` type specifier +within its own format strings to perform type deduction. `Point` above could be +formatted as `"(%v, %v)"` for example, and deduce the `int` values as `%d`. + +Sometimes, `AbslStringify()` might not be an option: your team may wish to print +types with extra debugging information for testing purposes only. If so, you can +instead define a `PrintTo()` function like this: ```c++ #include namespace foo { -class Bar { +class Point { ... - friend void PrintTo(const Bar& bar, std::ostream* os) { - *os << bar.DebugString(); // whatever needed to print bar to os + friend void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; } + + int x; + int y; }; // If you can't declare the function in the class it's important that PrintTo() -// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely -// on that. -void PrintTo(const Bar& bar, std::ostream* os) { - *os << bar.DebugString(); // whatever needed to print bar to os +// is defined in the SAME namespace that defines Point. C++'s look-up rules +// rely on that. +void PrintTo(const Point& point, std::ostream* os) { + *os << "(" << point.x << "," << point.y << ")"; } } // namespace foo ``` -If you have defined both `<<` and `PrintTo()`, the latter will be used when -googletest is concerned. This allows you to customize how the value appears in -googletest's output without affecting code that relies on the behavior of its -`<<` operator. +If you have defined both `AbslStringify()` and `PrintTo()`, the latter will be +used by GoogleTest. This allows you to customize how the value appears in +GoogleTest's output without affecting code that relies on the behavior of +`AbslStringify()`. -If you want to print a value `x` using googletest's value printer yourself, just +If you have an existing `<<` operator and would like to define an +`AbslStringify()`, the latter will be used for GoogleTest printing. + +If you want to print a value `x` using GoogleTest's value printer yourself, just call `::testing::PrintToString(x)`, which returns an `std::string`: ```c++ -vector > bar_ints = GetBarIntVector(); +vector > point_ints = GetPointIntVector(); -EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) - << "bar_ints = " << ::testing::PrintToString(bar_ints); +EXPECT_TRUE(IsCorrectPointIntVector(point_ints)) + << "point_ints = " << testing::PrintToString(point_ints); ``` +For more details regarding `AbslStringify()` and its integration with other +libraries, see go/abslstringify. + ## Death Tests In many applications, there are assertions that can cause application failure if -a condition is not met. These sanity checks, which ensure that the program is in -a known good state, are there to fail at the earliest possible time after some -program state is corrupted. If the assertion checks the wrong condition, then -the program may proceed in an erroneous state, which could lead to memory +a condition is not met. These consistency checks, which ensure that the program +is in a known good state, are there to fail at the earliest possible time after +some program state is corrupted. If the assertion checks the wrong condition, +then the program may proceed in an erroneous state, which could lead to memory corruption, security holes, or worse. Hence it is vitally important to test that such assertion statements work as expected. @@ -628,73 +425,16 @@ exception and avoid the crash. If you want to verify exceptions thrown by your code, see [Exception Assertions](#ExceptionAssertions). If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see -Catching Failures +["Catching" Failures](#catching-failures). ### How to Write a Death Test -googletest has the following macros to support death tests: - -Fatal assertion | Nonfatal assertion | Verifies ------------------------------------------------- | ------------------------------------------------ | -------- -`ASSERT_DEATH(statement, matcher);` | `EXPECT_DEATH(statement, matcher);` | `statement` crashes with the given error -`ASSERT_DEATH_IF_SUPPORTED(statement, matcher);` | `EXPECT_DEATH_IF_SUPPORTED(statement, matcher);` | if death tests are supported, verifies that `statement` crashes with the given error; otherwise verifies nothing -`ASSERT_EXIT(statement, predicate, matcher);` | `EXPECT_EXIT(statement, predicate, matcher);` | `statement` exits with the given error, and its exit code matches `predicate` - -where `statement` is a statement that is expected to cause the process to die, -`predicate` is a function or function object that evaluates an integer exit -status, and `matcher` is either a gMock matcher matching a `const std::string&` -or a (Perl) regular expression - either of which is matched against the stderr -output of `statement`. For legacy reasons, a bare string (i.e. with no matcher) -is interpreted as `ContainsRegex(str)`, **not** `Eq(str)`. Note that `statement` -can be *any valid statement* (including *compound statement*) and doesn't have -to be an expression. - -As usual, the `ASSERT` variants abort the current test function, while the -`EXPECT` variants do not. - -> NOTE: We use the word "crash" here to mean that the process terminates with a -> *non-zero* exit status code. There are two possibilities: either the process -> has called `exit()` or `_exit()` with a non-zero value, or it may be killed by -> a signal. -> -> This means that if *`statement`* terminates the process with a 0 exit code, it -> is *not* considered a crash by `EXPECT_DEATH`. Use `EXPECT_EXIT` instead if -> this is the case, or if you want to restrict the exit code more precisely. - -A predicate here must accept an `int` and return a `bool`. The death test -succeeds only if the predicate returns `true`. googletest defines a few -predicates that handle the most common cases: +GoogleTest provides assertion macros to support death tests. See +[Death Assertions](reference/assertions.md#death) in the Assertions Reference +for details. -```c++ -::testing::ExitedWithCode(exit_code) -``` - -This expression is `true` if the program exited normally with the given exit -code. - -```c++ -::testing::KilledBySignal(signal_number) // Not available on Windows. -``` - -This expression is `true` if the program was killed by the given signal. - -The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate -that verifies the process' exit code is non-zero. - -Note that a death test only cares about three things: - -1. does `statement` abort or exit the process? -2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status - satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) - is the exit status non-zero? And -3. does the stderr output match `matcher`? - -In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it -will **not** cause the death test to fail, as googletest assertions don't abort -the process. - -To write a death test, simply use one of the above macros inside your test -function. For example, +To write a death test, simply use one of the macros inside your test function. +For example, ```c++ TEST(MyDeathTest, Foo) { @@ -706,11 +446,11 @@ TEST(MyDeathTest, Foo) { } TEST(MyDeathTest, NormalExit) { - EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); + EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); } -TEST(MyDeathTest, KillMyself) { - EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), +TEST(MyDeathTest, KillProcess) { + EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); } ``` @@ -720,13 +460,26 @@ verifies that: * calling `Foo(5)` causes the process to die with the given error message, * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and -* calling `KillMyself()` kills the process with signal `SIGKILL`. +* calling `KillProcess()` kills the process with signal `SIGKILL`. The test function body may contain other assertions and statements as well, if necessary. +Note that a death test only cares about three things: + +1. does `statement` abort or exit the process? +2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status + satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) + is the exit status non-zero? And +3. does the stderr output match `matcher`? + +In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it +will **not** cause the death test to fail, as GoogleTest assertions don't abort +the process. + ### Death Test Naming +{: .callout .important} IMPORTANT: We strongly recommend you to follow the convention of naming your **test suite** (not test) `*DeathTest` when it contains a death test, as demonstrated in the above example. The @@ -737,7 +490,7 @@ If a test fixture class is shared by normal tests and death tests, you can use duplicating its code: ```c++ -class FooTest : public ::testing::Test { ... }; +class FooTest : public testing::Test { ... }; using FooDeathTest = FooTest; @@ -752,12 +505,14 @@ TEST_F(FooDeathTest, DoesThat) { ### Regular Expression Syntax -On POSIX systems (e.g. Linux, Cygwin, and Mac), googletest uses the +When built with Bazel and using Abseil, GoogleTest uses the +[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX +systems (Linux, Cygwin, Mac), GoogleTest uses the [POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) -syntax. To learn about this syntax, you may want to read this -[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). +syntax. To learn about POSIX syntax, you may want to read this +[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_extended). -On Windows, googletest uses its own simple regular expression implementation. It +On Windows, GoogleTest uses its own simple regular expression implementation. It lacks many features. For example, we don't support union (`"x|y"`), grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among others. Below is what we do support (`A` denotes a literal character, period @@ -787,7 +542,7 @@ Expression | Meaning `$` | matches the end of a string (not that of each line) `xy` | matches `x` followed by `y` -To help you determine which capability is available on your system, googletest +To help you determine which capability is available on your system, GoogleTest defines macros to govern which regular expression it is using. The macros are: `GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death tests to work in all cases, you can either `#if` on these macros or use the more @@ -795,31 +550,8 @@ limited syntax only. ### How It Works -Under the hood, `ASSERT_EXIT()` spawns a new process and executes the death test -statement in that process. The details of how precisely that happens depend on -the platform and the variable ::testing::GTEST_FLAG(death_test_style) (which is -initialized from the command-line flag `--gtest_death_test_style`). - -* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the - child, after which: - * If the variable's value is `"fast"`, the death test statement is - immediately executed. - * If the variable's value is `"threadsafe"`, the child process re-executes - the unit test binary just as it was originally invoked, but with some - extra flags to cause just the single death test under consideration to - be run. -* On Windows, the child is spawned using the `CreateProcess()` API, and - re-executes the binary to cause just the single death test under - consideration to be run - much like the `threadsafe` mode on POSIX. - -Other values for the variable are illegal and will cause the death test to fail. -Currently, the flag's default value is **"fast"** - -1. the child's exit status satisfies the predicate, and -2. the child's stderr matches the regular expression. - -If the death test statement runs to completion without dying, the child process -will nonetheless terminate, and the assertion fails. +See [Death Assertions](reference/assertions.md#death) in the Assertions +Reference. ### Death Tests And Threads @@ -830,7 +562,7 @@ arrange that kind of environment. For example, statically-initialized modules may start threads before main is ever reached. Once threads have been created, it may be difficult or impossible to clean them up. -googletest has three features intended to raise awareness of threading issues. +GoogleTest has three features intended to raise awareness of threading issues. 1. A warning is emitted if multiple threads are running when a death test is encountered. @@ -853,7 +585,7 @@ The automated testing framework does not set the style flag. You can choose a particular style of death tests by setting the flag programmatically: ```c++ -testing::FLAGS_gtest_death_test_style="threadsafe" +GTEST_FLAG_SET(death_test_style, "threadsafe"); ``` You can do this in `main()` to set the style for all death tests in the binary, @@ -862,13 +594,13 @@ restored afterwards, so you need not do that yourself. For example: ```c++ int main(int argc, char** argv) { - InitGoogle(argv[0], &argc, &argv, true); - ::testing::FLAGS_gtest_death_test_style = "fast"; + testing::InitGoogleTest(&argc, argv); + GTEST_FLAG_SET(death_test_style, "fast"); return RUN_ALL_TESTS(); } TEST(MyDeathTest, TestOne) { - ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + GTEST_FLAG_SET(death_test_style, "threadsafe"); // This test is run in the "threadsafe" style: ASSERT_DEATH(ThisShouldDie(), ""); } @@ -883,7 +615,7 @@ TEST(MyDeathTest, TestTwo) { The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If it leaves the current function via a `return` statement or by throwing an -exception, the death test is considered to have failed. Some googletest macros +exception, the death test is considered to have failed. Some GoogleTest macros may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in `statement`. @@ -905,9 +637,15 @@ Despite the improved thread safety afforded by the "threadsafe" style of death test, thread problems such as deadlock are still possible in the presence of handlers registered with `pthread_atfork(3)`. - ## Using Assertions in Sub-routines +{: .callout .note} +Note: If you want to put a series of test assertions in a subroutine to check +for a complex condition, consider using +[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you +provide a more readable error message in case of failure and avoid all of the +issues described below. + ### Adding Traces to Assertions If a test sub-routine is called from several places, when an assertion inside it @@ -919,6 +657,7 @@ the `SCOPED_TRACE` macro or the `ScopedTrace` utility: ```c++ SCOPED_TRACE(message); ``` + ```c++ ScopedTrace trace("file_path", line_number, message); ``` @@ -955,7 +694,7 @@ path/to/foo_test.cc:11: Failure Value of: Bar(n) Expected: 1 Actual: 2 - Trace: +Google Test trace: path/to/foo_test.cc:17: A path/to/foo_test.cc:12: Failure @@ -1005,12 +744,12 @@ TEST(FooTest, Bar) { // in Subroutine() to abort the entire test. // The actual behavior: the function goes on after Subroutine() returns. - int* p = NULL; + int* p = nullptr; *p = 3; // Segfault! } ``` -To alleviate this, googletest provides three different solutions. You could use +To alleviate this, GoogleTest provides three different solutions. You could use either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the `HasFatalFailure()` function. They are described in the following two subsections. @@ -1044,7 +783,7 @@ in it, the test will continue after the subroutine returns. This may not be what you want. Often people want fatal failures to propagate like exceptions. For that -googletest offers the following macros: +GoogleTest offers the following macros: Fatal assertion | Nonfatal assertion | Verifies ------------------------------------- | ------------------------------------- | -------- @@ -1099,7 +838,7 @@ If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test fixture, you must add the `::testing::Test::` prefix, as in: ```c++ -if (::testing::Test::HasFatalFailure()) return; +if (testing::Test::HasFatalFailure()) return; ``` Similarly, `HasNonfatalFailure()` returns `true` if the current test has at @@ -1125,17 +864,18 @@ will output XML like this: ```xml ... - + ... ``` +{: .callout .note} > NOTE: > > * `RecordProperty()` is a static member of the `Test` class. Therefore it > needs to be prefixed with `::testing::Test::` if used outside of the > `TEST` body and the test fixture class. > * *`key`* must be a valid XML attribute name, and cannot conflict with the -> ones already used by googletest (`name`, `status`, `time`, `classname`, +> ones already used by GoogleTest (`name`, `status`, `time`, `classname`, > `type_param`, and `value_param`). > * Calling `RecordProperty()` outside of the lifespan of a test is allowed. > If it's called outside of a test but between a test suite's @@ -1146,13 +886,13 @@ will output XML like this: ## Sharing Resources Between Tests in the Same Test Suite -googletest creates a new test fixture object for each test in order to make +GoogleTest creates a new test fixture object for each test in order to make tests independent and easier to debug. However, sometimes tests use resources that are expensive to set up, making the one-copy-per-test model prohibitively expensive. If the tests don't change the resource, there's no harm in their sharing a -single resource copy. So, in addition to per-test set-up/tear-down, googletest +single resource copy. So, in addition to per-test set-up/tear-down, GoogleTest also supports per-test-suite set-up/tear-down. To use it: 1. In your test fixture class (say `FooTest` ), declare as `static` some member @@ -1164,7 +904,7 @@ also supports per-test-suite set-up/tear-down. To use it: `u`!) to set up the shared resources and a `static void TearDownTestSuite()` function to tear them down. -That's it! googletest automatically calls `SetUpTestSuite()` before running the +That's it! GoogleTest automatically calls `SetUpTestSuite()` before running the *first test* in the `FooTest` test suite (i.e. before creating the first `FooTest` object), and calls `TearDownTestSuite()` after running the *last test* in it (i.e. after deleting the last `FooTest` object). In between, the tests can @@ -1175,16 +915,31 @@ preceding or following another. Also, the tests must either not modify the state of any shared resource, or, if they do modify the state, they must restore the state to its original value before passing control to the next test. +Note that `SetUpTestSuite()` may be called multiple times for a test fixture +class that has derived classes, so you should not expect code in the function +body to be run only once. Also, derived classes still have access to shared +resources defined as static members, so careful consideration is needed when +managing shared resources to avoid memory leaks if shared resources are not +properly cleaned up in `TearDownTestSuite()`. + Here's an example of per-test-suite set-up and tear-down: ```c++ -class FooTest : public ::testing::Test { +class FooTest : public testing::Test { protected: // Per-test-suite set-up. // Called before the first test in this test suite. // Can be omitted if not needed. static void SetUpTestSuite() { shared_resource_ = new ...; + + // If `shared_resource_` is **not deleted** in `TearDownTestSuite()`, + // reallocation should be prevented because `SetUpTestSuite()` may be called + // in subclasses of FooTest and lead to memory leak. + // + // if (shared_resource_ == nullptr) { + // shared_resource_ = new ...; + // } } // Per-test-suite tear-down. @@ -1192,20 +947,20 @@ class FooTest : public ::testing::Test { // Can be omitted if not needed. static void TearDownTestSuite() { delete shared_resource_; - shared_resource_ = NULL; + shared_resource_ = nullptr; } // You can define per-test set-up logic as usual. - virtual void SetUp() { ... } + void SetUp() override { ... } // You can define per-test tear-down logic as usual. - virtual void TearDown() { ... } + void TearDown() override { ... } // Some expensive resource shared by all tests. static T* shared_resource_; }; -T* FooTest::shared_resource_ = NULL; +T* FooTest::shared_resource_ = nullptr; TEST_F(FooTest, Test1) { ... you can refer to shared_resource_ here ... @@ -1216,6 +971,7 @@ TEST_F(FooTest, Test2) { } ``` +{: .callout .note} NOTE: Though the above code declares `SetUpTestSuite()` protected, it may sometimes be necessary to declare it public, such as when using it with `TEST_P`. @@ -1241,7 +997,7 @@ class Environment : public ::testing::Environment { }; ``` -Then, you register an instance of your environment class with googletest by +Then, you register an instance of your environment class with GoogleTest by calling the `::testing::AddGlobalTestEnvironment()` function: ```c++ @@ -1258,7 +1014,7 @@ It's OK to register multiple environment objects. In this suite, their `SetUp()` will be called in the order they are registered, and their `TearDown()` will be called in the reverse order. -Note that googletest takes ownership of the registered environment objects. +Note that GoogleTest takes ownership of the registered environment objects. Therefore **do not delete them** by yourself. You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, @@ -1267,8 +1023,8 @@ probably in `main()`. If you use `gtest_main`, you need to call this before variable like this: ```c++ -::testing::Environment* const foo_env = - ::testing::AddGlobalTestEnvironment(new FooEnvironment); +testing::Environment* const foo_env = + testing::AddGlobalTestEnvironment(new FooEnvironment); ``` However, we strongly recommend you to write your own `main()` and call @@ -1303,13 +1059,14 @@ and `testing::WithParamInterface`. `T` can be any copyable type. If it's a raw pointer, you are responsible for managing the lifespan of the pointed values. +{: .callout .note} NOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()` they must be declared **public** rather than **protected** in order to use `TEST_P`. ```c++ class FooTest : - public testing::TestWithParam { + public testing::TestWithParam { // You can implement all the usual fixture class members here. // To access the test parameter, call GetParam() from class // TestWithParam. @@ -1320,7 +1077,7 @@ class BaseTest : public testing::Test { ... }; class BarTest : public BaseTest, - public testing::WithParamInterface { + public testing::WithParamInterface { ... }; ``` @@ -1342,80 +1099,85 @@ TEST_P(FooTest, HasBlahBlah) { } ``` -Finally, you can use `INSTANTIATE_TEST_SUITE_P` to instantiate the test suite -with any set of parameters you want. googletest defines a number of functions -for generating test parameters. They return what we call (surprise!) *parameter -generators*. Here is a summary of them, which are all in the `testing` -namespace: +Finally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the +test suite with any set of parameters you want. GoogleTest defines a number of +functions for generating test parameters—see details at +[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in +the Testing Reference. - - -| Parameter Generator | Behavior | -| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | -| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | -| `ValuesIn(container)` and `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)` | -| `Bool()` | Yields sequence `{false, true}`. | -| `Combine(g1, g2, ..., gN)` | Yields all combinations (Cartesian product) as std\:\:tuples of the values generated by the `N` generators. | - - - -For more details, see the comments at the definitions of these functions. - -The following statement will instantiate tests from the `FooTest` test suite -each with parameter values `"meeny"`, `"miny"`, and `"moe"`. +For example, the following statement will instantiate tests from the `FooTest` +test suite each with parameter values `"meeny"`, `"miny"`, and `"moe"` using the +[`Values`](reference/testing.md#param-generators) parameter generator: ```c++ -INSTANTIATE_TEST_SUITE_P(InstantiationName, +INSTANTIATE_TEST_SUITE_P(MeenyMinyMoe, FooTest, testing::Values("meeny", "miny", "moe")); ``` +{: .callout .note} NOTE: The code above must be placed at global or namespace scope, not at function scope. -NOTE: Don't forget this step! If you do your test will silently pass, but none -of its suites will ever run! +The first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the +instantiation of the test suite. The next argument is the name of the test +pattern, and the last is the +[parameter generator](reference/testing.md#param-generators). -To distinguish different instances of the pattern (yes, you can instantiate it -more than once), the first argument to `INSTANTIATE_TEST_SUITE_P` is a prefix -that will be added to the actual test suite name. Remember to pick unique -prefixes for different instantiations. The tests from the instantiation above -will have these names: +The parameter generator expression is not evaluated until GoogleTest is +initialized (via `InitGoogleTest()`). Any prior initialization done in the +`main` function will be accessible from the parameter generator, for example, +the results of flag parsing. -* `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` -* `InstantiationName/FooTest.DoesBlah/1` for `"miny"` -* `InstantiationName/FooTest.DoesBlah/2` for `"moe"` -* `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` -* `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` -* `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` +You can instantiate a test pattern more than once, so to distinguish different +instances of the pattern, the instantiation name is added as a prefix to the +actual test suite name. Remember to pick unique prefixes for different +instantiations. The tests from the instantiation above will have these names: + +* `MeenyMinyMoe/FooTest.DoesBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.DoesBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.DoesBlah/2` for `"moe"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `"meeny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `"miny"` +* `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `"moe"` You can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests). -This statement will instantiate all tests from `FooTest` again, each with -parameter values `"cat"` and `"dog"`: +The following statement will instantiate all tests from `FooTest` again, each +with parameter values `"cat"` and `"dog"` using the +[`ValuesIn`](reference/testing.md#param-generators) parameter generator: ```c++ -const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, - testing::ValuesIn(pets)); +constexpr absl::string_view kPets[] = {"cat", "dog"}; +INSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(kPets)); ``` The tests from the instantiation above will have these names: -* `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` -* `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` -* `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` -* `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` +* `Pets/FooTest.DoesBlah/0` for `"cat"` +* `Pets/FooTest.DoesBlah/1` for `"dog"` +* `Pets/FooTest.HasBlahBlah/0` for `"cat"` +* `Pets/FooTest.HasBlahBlah/1` for `"dog"` Please note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the given test suite, whether their definitions come before or *after* the `INSTANTIATE_TEST_SUITE_P` statement. +Additionally, by default, every `TEST_P` without a corresponding +`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite +`GoogleTestVerification`. If you have a test suite where that omission is not an +error, for example it is in a library that may be linked in for other reasons or +where the list of test cases is dynamic and may be empty, then this check can be +suppressed by tagging the test suite: + +```c++ +GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest); +``` + You can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples. -[sample7_unittest.cc]: ../samples/sample7_unittest.cc "Parameterized Test example" -[sample8_unittest.cc]: ../samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" +[sample7_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample7_unittest.cc "Parameterized Test example" +[sample8_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample8_unittest.cc "Parameterized Test example with multiple parameters" ### Creating Value-Parameterized Abstract Tests @@ -1452,6 +1214,7 @@ the test parameters. The function should accept one argument of type returns the value of `testing::PrintToString(GetParam())`. It does not work for `std::string` or C strings. +{: .callout .note} NOTE: test names must be non-empty, unique, and may only contain ASCII alphanumeric characters. In particular, they [should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore) @@ -1478,17 +1241,17 @@ for conciseness: ```c++ enum class MyType { MY_FOO = 0, MY_BAR = 1 }; -class MyTestSuite : public testing::TestWithParam> { +class MyTestSuite : public testing::TestWithParam> { }; INSTANTIATE_TEST_SUITE_P( MyGroup, MyTestSuite, testing::Combine( - testing::Values(MyType::VALUE_0, MyType::VALUE_1), - testing::ValuesIn("", "")), + testing::Values(MyType::MY_FOO, MyType::MY_BAR), + testing::Values("A", "B")), [](const testing::TestParamInfo& info) { - string name = absl::StrCat( - std::get<0>(info.param) == MY_FOO ? "Foo" : "Bar", "_", + std::string name = absl::StrCat( + std::get<0>(info.param) == MyType::MY_FOO ? "Foo" : "Bar", std::get<1>(info.param)); absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_'); return name; @@ -1517,10 +1280,10 @@ Remember to derive it from `::testing::Test`: ```c++ template -class FooTest : public ::testing::Test { +class FooTest : public testing::Test { public: ... - typedef std::list List; + using List = std::list; static T shared_; T value_; }; @@ -1565,7 +1328,7 @@ TYPED_TEST(FooTest, HasPropertyA) { ... } You can see [sample6_unittest.cc] for a complete example. -[sample6_unittest.cc]: ../samples/sample6_unittest.cc "Typed Test example" +[sample6_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc "Typed Test example" ## Type-Parameterized Tests @@ -1585,7 +1348,8 @@ First, define a fixture class template, as we did with typed tests: ```c++ template -class FooTest : public ::testing::Test { +class FooTest : public testing::Test { + void DoSomethingInteresting(); ... }; ``` @@ -1603,6 +1367,9 @@ this as many times as you want: TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; + + // You will need to use `this` explicitly to refer to fixture members. + this->DoSomethingInteresting() ... } @@ -1624,7 +1391,7 @@ put the above code in a header file, you can `#include` it in multiple C++ source files and instantiate it multiple times. ```c++ -typedef ::testing::Types MyTypes; +using MyTypes = ::testing::Types; INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); ``` @@ -1720,10 +1487,11 @@ To test them, we use the following special techniques: } ``` - Pay special attention when your class is defined in a namespace, as you - should define your test fixtures and tests in the same namespace if you want - them to be friends of your class. For example, if the code to be tested - looks like: + Pay special attention when your class is defined in a namespace. If you want + your test fixtures and tests to be friends of your class, then they must be + defined in the exact same namespace (no anonymous or inline namespaces). + + For example, if the code to be tested looks like: ```c++ namespace my_namespace { @@ -1743,7 +1511,7 @@ To test them, we use the following special techniques: ```c++ namespace my_namespace { - class FooTest : public ::testing::Test { + class FooTest : public testing::Test { protected: ... }; @@ -1756,16 +1524,16 @@ To test them, we use the following special techniques: ## "Catching" Failures -If you are building a testing utility on top of googletest, you'll want to test -your utility. What framework would you use to test it? googletest, of course. +If you are building a testing utility on top of GoogleTest, you'll want to test +your utility. What framework would you use to test it? GoogleTest, of course. The challenge is to verify that your testing utility reports failures correctly. In frameworks that report a failure by throwing an exception, you could catch -the exception and assert on it. But googletest doesn't use exceptions, so how do +the exception and assert on it. But GoogleTest doesn't use exceptions, so how do we test that a piece of code generates an expected failure? -gunit-spi.h contains some constructs to do this. After #including this header, -you can use +`"gtest/gtest-spi.h"` contains some constructs to do this. +After #including this header, you can use ```c++ EXPECT_FATAL_FAILURE(statement, substring); @@ -1790,6 +1558,7 @@ well, use one of the following macros instead: EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); ``` +{: .callout .note} NOTE: Assertions from multiple threads are currently not supported on Windows. For technical reasons, there are some caveats: @@ -1838,7 +1607,7 @@ undefined. Use case example: ```c++ -class MyFixture : public ::testing::Test { +class MyFixture : public testing::Test { public: // All of these optional, just like in regular macro usage. static void SetUpTestSuite() { ... } @@ -1858,7 +1627,7 @@ class MyTest : public MyFixture { void RegisterMyTests(const std::vector& values) { for (int v : values) { - ::testing::RegisterTest( + testing::RegisterTest( "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, std::to_string(v).c_str(), __FILE__, __LINE__, @@ -1868,43 +1637,30 @@ void RegisterMyTests(const std::vector& values) { } ... int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); std::vector values_to_test = LoadValuesFromConfig(); RegisterMyTests(values_to_test); ... return RUN_ALL_TESTS(); } ``` + ## Getting the Current Test's Name Sometimes a function may need to know the name of the currently running test. For example, you may be using the `SetUp()` method of your test fixture to set -the golden file name based on which test is running. The `::testing::TestInfo` -class has this information: - -```c++ -namespace testing { - -class TestInfo { - public: - // Returns the test suite name and the test name, respectively. - // - // Do NOT delete or free the return value - it's managed by the - // TestInfo class. - const char* test_suite_name() const; - const char* name() const; -}; - -} -``` +the golden file name based on which test is running. The +[`TestInfo`](reference/testing.md#TestInfo) class has this information. To obtain a `TestInfo` object for the currently running test, call -`current_test_info()` on the `UnitTest` singleton object: +`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest) +singleton object: ```c++ // Gets information about the currently running test. // Do NOT delete the returned object - it's managed by the UnitTest class. - const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); + const testing::TestInfo* const test_info = + testing::UnitTest::GetInstance()->current_test_info(); printf("We are in test %s of test suite %s.\n", test_info->name(), @@ -1912,13 +1668,13 @@ To obtain a `TestInfo` object for the currently running test, call ``` `current_test_info()` returns a null pointer if no test is running. In -particular, you cannot find the test suite name in `TestSuiteSetUp()`, -`TestSuiteTearDown()` (where you know the test suite name implicitly), or +particular, you cannot find the test suite name in `SetUpTestSuite()`, +`TearDownTestSuite()` (where you know the test suite name implicitly), or functions called from them. -## Extending googletest by Handling Test Events +## Extending GoogleTest by Handling Test Events -googletest provides an **event listener API** to let you receive notifications +GoogleTest provides an **event listener API** to let you receive notifications about the progress of a test program and test failures. The events you can listen to include the start and end of the test program, a test suite, or a test method, among others. You may use this API to augment or replace the standard @@ -1928,12 +1684,14 @@ checkpoints to implement a resource leak checker, for example. ### Defining Event Listeners -To define a event listener, you subclass either testing::TestEventListener or -testing::EmptyTestEventListener The former is an (abstract) interface, where -*each pure virtual method can be overridden to handle a test event* (For -example, when a test starts, the `OnTestStart()` method will be called.). The -latter provides an empty implementation of all methods in the interface, such -that a subclass only needs to override the methods it cares about. +To define a event listener, you subclass either +[`testing::TestEventListener`](reference/testing.md#TestEventListener) or +[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener) +The former is an (abstract) interface, where *each pure virtual method can be +overridden to handle a test event* (For example, when a test starts, the +`OnTestStart()` method will be called.). The latter provides an empty +implementation of all methods in the interface, such that a subclass only needs +to override the methods it cares about. When an event is fired, its context is passed to the handler function as an argument. The following argument types are used: @@ -1950,15 +1708,15 @@ interesting information about the event and the test program's state. Here's an example: ```c++ - class MinimalistPrinter : public ::testing::EmptyTestEventListener { + class MinimalistPrinter : public testing::EmptyTestEventListener { // Called before a test starts. - virtual void OnTestStart(const ::testing::TestInfo& test_info) { + void OnTestStart(const testing::TestInfo& test_info) override { printf("*** Test %s.%s starting.\n", test_info.test_suite_name(), test_info.name()); } // Called after a failed assertion or a SUCCESS(). - virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) { + void OnTestPartResult(const testing::TestPartResult& test_part_result) override { printf("%s in %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", test_part_result.file_name(), @@ -1967,7 +1725,7 @@ Here's an example: } // Called after a test ends. - virtual void OnTestEnd(const ::testing::TestInfo& test_info) { + void OnTestEnd(const testing::TestInfo& test_info) override { printf("*** Test %s.%s ending.\n", test_info.test_suite_name(), test_info.name()); } @@ -1977,17 +1735,18 @@ Here's an example: ### Using Event Listeners To use the event listener you have defined, add an instance of it to the -googletest event listener list (represented by class TestEventListeners - note -the "s" at the end of the name) in your `main()` function, before calling +GoogleTest event listener list (represented by class +[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the "s" +at the end of the name) in your `main()` function, before calling `RUN_ALL_TESTS()`: ```c++ int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); + testing::InitGoogleTest(&argc, argv); // Gets hold of the event listener list. - ::testing::TestEventListeners& listeners = - ::testing::UnitTest::GetInstance()->listeners(); - // Adds a listener to the end. googletest takes the ownership. + testing::TestEventListeners& listeners = + testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. GoogleTest takes the ownership. listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); } @@ -2008,7 +1767,7 @@ You can do so by adding one line: Now, sit back and enjoy a completely different output from your tests. For more details, see [sample9_unittest.cc]. -[sample9_unittest.cc]: ../samples/sample9_unittest.cc "Event listener example" +[sample9_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample9_unittest.cc "Event listener example" You may append more than one listener to the list. When an `On*Start()` or `OnTestPartResult()` event is fired, the listeners will receive it in the order @@ -2035,11 +1794,11 @@ by the former. See [sample10_unittest.cc] for an example of a failure-raising listener. -[sample10_unittest.cc]: ../samples/sample10_unittest.cc "Failure-raising listener example" +[sample10_unittest.cc]: https://github.com/google/googletest/blob/main/googletest/samples/sample10_unittest.cc "Failure-raising listener example" ## Running Test Programs: Advanced Options -googletest test programs are ordinary executables. Once built, you can run them +GoogleTest test programs are ordinary executables. Once built, you can run them directly and affect their behavior via the following environment variables and/or command line flags. For the flags to work, your programs must call `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. @@ -2072,10 +1831,10 @@ corresponding environment variable for this flag. #### Running a Subset of the Tests -By default, a googletest program runs all tests the user has defined. Sometimes, +By default, a GoogleTest program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the `GTEST_FILTER` environment variable or the -`--gtest_filter` flag to a filter string, googletest will only run the tests +`--gtest_filter` flag to a filter string, GoogleTest will only run the tests whose full names (in the form of `TestSuiteName.TestName`) match the filter. The format of a filter is a '`:`'-separated list of wildcard patterns (called @@ -2104,6 +1863,14 @@ For example: everything in test suite `FooTest` except `FooTest.Bar` and everything in test suite `BarTest` except `BarTest.Foo`. +#### Stop test execution upon first failure + +By default, a GoogleTest program runs all tests the user has defined. In some +cases (e.g. iterative test development & execution) it may be desirable stop +test execution upon first failure (trading improved latency for completeness). +If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set, +the test runner will stop execution as soon as the first test failure is found. + #### Temporarily Disabling Tests If you have a broken test that you cannot fix right away, you can add the @@ -2115,26 +1882,28 @@ If you need to disable all tests in a test suite, you can either add `DISABLED_` to the front of the name of each test, or alternatively add it to the front of the test suite name. -For example, the following tests won't be run by googletest, even though they +For example, the following tests won't be run by GoogleTest, even though they will still be compiled: ```c++ // Tests that Foo does Abc. TEST(FooTest, DISABLED_DoesAbc) { ... } -class DISABLED_BarTest : public ::testing::Test { ... }; +class DISABLED_BarTest : public testing::Test { ... }; // Tests that Bar does Xyz. TEST_F(DISABLED_BarTest, DoesXyz) { ... } ``` +{: .callout .note} NOTE: This feature should only be used for temporary pain-relief. You still have -to fix the disabled tests at a later date. As a reminder, googletest will print +to fix the disabled tests at a later date. As a reminder, GoogleTest will print a banner warning you if a test program contains any disabled tests. -TIP: You can easily count the number of disabled tests you have using `gsearch` -and/or `grep`. This number can be used as a metric for improving your test -quality. +{: .callout .tip} +TIP: You can easily count the number of disabled tests you have using +`grep`. This number can be used as a metric for +improving your test quality. #### Temporarily Enabling Disabled Tests @@ -2173,8 +1942,12 @@ Repeat the tests whose name matches the filter 1000 times. If your test program contains [global set-up/tear-down](#global-set-up-and-tear-down) code, it will be -repeated in each iteration as well, as the flakiness may be in it. You can also -specify the repeat count by setting the `GTEST_REPEAT` environment variable. +repeated in each iteration as well, as the flakiness may be in it. To avoid +repeating global set-up/tear-down, specify +`--gtest_recreate_environments_when_repeating=false`{.nowrap}. + +You can also specify the repeat count by setting the `GTEST_REPEAT` environment +variable. ### Shuffling the Tests @@ -2182,87 +1955,129 @@ You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` environment variable to `1`) to run the tests in a program in a random order. This helps to reveal bad dependencies between tests. -By default, googletest uses a random seed calculated from the current time. +By default, GoogleTest uses a random seed calculated from the current time. Therefore you'll get a different order every time. The console output includes the random seed value, such that you can reproduce an order-related test failure later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer in the range [0, 99999]. The seed value 0 is special: it tells -googletest to do the default behavior of calculating the seed from the current +GoogleTest to do the default behavior of calculating the seed from the current time. -If you combine this with `--gtest_repeat=N`, googletest will pick a different +If you combine this with `--gtest_repeat=N`, GoogleTest will pick a different random seed and re-shuffle the tests in each iteration. +### Distributing Test Functions to Multiple Machines + +If you have more than one machine you can use to run a test program, you might +want to run the test functions in parallel and get the result faster. We call +this technique *sharding*, where each machine is called a *shard*. + +GoogleTest is compatible with test sharding. To take advantage of this feature, +your test runner (not part of GoogleTest) needs to do the following: + +1. Allocate a number of machines (shards) to run the tests. +1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total + number of shards. It must be the same for all shards. +1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index + of the shard. Different shards must be assigned different indices, which + must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. +1. Run the same test program on all shards. When GoogleTest sees the above two + environment variables, it will select a subset of the test functions to run. + Across all shards, each test function in the program will be run exactly + once. +1. Wait for all shards to finish, then collect and report the results. + +Your project may have tests that were written without GoogleTest and thus don't +understand this protocol. In order for your test runner to figure out which test +supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` +to a non-existent file path. If a test program supports sharding, it will create +this file to acknowledge that fact; otherwise it will not create it. The actual +contents of the file are not important at this time, although we may put some +useful information in it in the future. + +Here's an example to make it clear. Suppose you have a test program `foo_test` +that contains the following 5 test functions: + +``` +TEST(A, V) +TEST(A, W) +TEST(B, X) +TEST(B, Y) +TEST(B, Z) +``` + +Suppose you have 3 machines at your disposal. To run the test functions in +parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set +`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would +run the same `foo_test` on each machine. + +GoogleTest reserves the right to change how the work is distributed across the +shards, but here's one possible scenario: + +* Machine #0 runs `A.V` and `B.X`. +* Machine #1 runs `A.W` and `B.Y`. +* Machine #2 runs `B.Z`. + ### Controlling Test Output #### Colored Terminal Output -googletest can use colors in its terminal output to make it easier to spot the +GoogleTest can use colors in its terminal output to make it easier to spot the important information: - -...
- [----------] 1 test from - FooTest
- [ RUN      ] - FooTest.DoesAbc
- [       OK ] - FooTest.DoesAbc
- [----------] - 2 tests from BarTest
- [ RUN      ] - BarTest.HasXyzProperty
- [       OK ] - BarTest.HasXyzProperty
- [ RUN      ] - BarTest.ReturnsTrueOnSuccess ... some error messages ...
- [   FAILED ] - BarTest.ReturnsTrueOnSuccess ...
- [==========] - 30 tests from 14 test suites ran.
- [   PASSED ] - 28 tests.
- [   FAILED ] - 2 tests, listed below:
- [   FAILED ] - BarTest.ReturnsTrueOnSuccess
- [   FAILED ] - AnotherTest.DoesXyz
-
- 2 FAILED TESTS -
-
+
...
+[----------] 1 test from FooTest
+[ RUN      ] FooTest.DoesAbc
+[       OK ] FooTest.DoesAbc
+[----------] 2 tests from BarTest
+[ RUN      ] BarTest.HasXyzProperty
+[       OK ] BarTest.HasXyzProperty
+[ RUN      ] BarTest.ReturnsTrueOnSuccess
+... some error messages ...
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+...
+[==========] 30 tests from 14 test suites ran.
+[   PASSED ] 28 tests.
+[   FAILED ] 2 tests, listed below:
+[   FAILED ] BarTest.ReturnsTrueOnSuccess
+[   FAILED ] AnotherTest.DoesXyz
+
+ 2 FAILED TESTS
+
You can set the `GTEST_COLOR` environment variable or the `--gtest_color` command line flag to `yes`, `no`, or `auto` (the default) to enable colors, -disable colors, or let googletest decide. When the value is `auto`, googletest +disable colors, or let GoogleTest decide. When the value is `auto`, GoogleTest will use colors if and only if the output goes to a terminal and (on non-Windows platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. +#### Suppressing test passes + +By default, GoogleTest prints 1 line of output for each test, indicating if it +passed or failed. To show only test failures, run the test program with +`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`. + #### Suppressing the Elapsed Time -By default, googletest prints the time it takes to run each test. To disable +By default, GoogleTest prints the time it takes to run each test. To disable that, run the test program with the `--gtest_print_time=0` command line flag, or set the GTEST_PRINT_TIME environment variable to `0`. #### Suppressing UTF-8 Text Output -In case of assertion failures, googletest prints expected and actual values of +In case of assertion failures, GoogleTest prints expected and actual values of type `string` both as hex-encoded strings as well as in readable UTF-8 text if they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 text because, for example, you don't have an UTF-8 compatible output medium, run the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` environment variable to `0`. - - #### Generating an XML Report -googletest can emit a detailed XML report to a file in addition to its normal +GoogleTest can emit a detailed XML report to a file in addition to its normal textual output. The report contains the duration of each test, and thus can help -you identify slow tests. The report is also used by the http://unittest -dashboard to show per-test-method error messages. +you identify slow tests. To generate the XML report, set the `GTEST_OUTPUT` environment variable or the `--gtest_output` flag to the string `"xml:path_to_output_file"`, which will @@ -2271,15 +2086,15 @@ in which case the output can be found in the `test_detail.xml` file in the current directory. If you specify a directory (for example, `"xml:output/directory/"` on Linux or -`"xml:output\directory\"` on Windows), googletest will create the XML file in +`"xml:output\directory\"` on Windows), GoogleTest will create the XML file in that directory, named after the test executable (e.g. `foo_test.xml` for test program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left -over from a previous run), googletest will pick a different name (e.g. +over from a previous run), GoogleTest will pick a different name (e.g. `foo_test_1.xml`) to avoid overwriting it. The report is based on the `junitreport` Ant task. Since that format was originally intended for Java, a little interpretation is required to make it -apply to googletest tests, as shown here: +apply to GoogleTest tests, as shown here: ```xml @@ -2294,8 +2109,8 @@ apply to googletest tests, as shown here: ``` * The root `` element corresponds to the entire test program. -* `` elements correspond to googletest test suites. -* `` elements correspond to googletest test functions. +* `` elements correspond to GoogleTest test suites. +* `` elements correspond to GoogleTest test functions. For instance, the following program @@ -2311,15 +2126,15 @@ could generate this report: - + ... ... - + - + @@ -2328,7 +2143,7 @@ could generate this report: Things to note: * The `tests` attribute of a `` or `` element tells how - many test functions the googletest program or test suite contains, while the + many test functions the GoogleTest program or test suite contains, while the `failures` attribute tells how many of them failed. * The `time` attribute expresses the duration of the test, test suite, or @@ -2337,12 +2152,15 @@ Things to note: * The `timestamp` attribute records the local date and time of the test execution. -* Each `` element corresponds to a single failed googletest +* The `file` and `line` attributes record the source file location, where the + test was defined. + +* Each `` element corresponds to a single failed GoogleTest assertion. #### Generating a JSON Report -googletest can also emit a JSON report as an alternative format to XML. To +GoogleTest can also emit a JSON report as an alternative format to XML. To generate the JSON report, set the `GTEST_OUTPUT` environment variable or the `--gtest_output` flag to the string `"json:path_to_output_file"`, which will create the file at the given location. You can also just use the string @@ -2376,6 +2194,8 @@ The report format conforms to the following JSON Schema: "type": "object", "properties": { "name": { "type": "string" }, + "file": { "type": "string" }, + "line": { "type": "integer" }, "status": { "type": "string", "enum": ["RUN", "NOTRUN"] @@ -2453,6 +2273,8 @@ message TestCase { message TestInfo { string name = 1; + string file = 6; + int32 line = 7; enum Status { RUN = 0; NOTRUN = 1; @@ -2496,6 +2318,8 @@ could generate this report: "testsuite": [ { "name": "Addition", + "file": "test.cpp", + "line": 1, "status": "RUN", "time": "0.007s", "classname": "", @@ -2512,6 +2336,8 @@ could generate this report: }, { "name": "Subtraction", + "file": "test.cpp", + "line": 2, "status": "RUN", "time": "0.005s", "classname": "" @@ -2527,6 +2353,8 @@ could generate this report: "testsuite": [ { "name": "NonContradiction", + "file": "test.cpp", + "line": 3, "status": "RUN", "time": "0.005s", "classname": "" @@ -2537,15 +2365,27 @@ could generate this report: } ``` +{: .callout .important} IMPORTANT: The exact format of the JSON document is subject to change. ### Controlling How Failures Are Reported +#### Detecting Test Premature Exit + +Google Test implements the _premature-exit-file_ protocol for test runners to +catch any kind of unexpected exits of test programs. Upon start, Google Test +creates the file which will be automatically deleted after all work has been +finished. Then, the test runner can check if this file exists. In case the file +remains undeleted, the inspected test has exited prematurely. + +This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment +variable has been set. + #### Turning Assertion Failures into Break-Points When running test programs under a debugger, it's very convenient if the debugger can catch an assertion failure and automatically drop into interactive -mode. googletest's *break-on-failure* mode supports this behavior. +mode. GoogleTest's *break-on-failure* mode supports this behavior. To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value other than `0`. Alternatively, you can use the `--gtest_break_on_failure` @@ -2553,9 +2393,9 @@ command line flag. #### Disabling Catching Test-Thrown Exceptions -googletest can be used either with or without exceptions enabled. If a test +GoogleTest can be used either with or without exceptions enabled. If a test throws a C++ exception or (on Windows) a structured exception (SEH), by default -googletest catches it, reports it as a test failure, and continues with the next +GoogleTest catches it, reports it as a test failure, and continues with the next test method. This maximizes the coverage of a test run. Also, on Windows an uncaught exception will cause a pop-up window, so catching the exceptions allows you to run the tests automatically. @@ -2565,3 +2405,32 @@ to be handled by the debugger, such that you can examine the call stack when an exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when running the tests. + +### Sanitizer Integration + +The +[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html), +[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer), +and +[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual) +all provide weak functions that you can override to trigger explicit failures +when they detect sanitizer errors, such as creating a reference from `nullptr`. +To override these functions, place definitions for them in a source file that +you compile as part of your main binary: + +``` +extern "C" { +void __ubsan_on_report() { + FAIL() << "Encountered an undefined behavior sanitizer error"; +} +void __asan_on_error() { + FAIL() << "Encountered an address sanitizer error"; +} +void __tsan_on_report() { + FAIL() << "Encountered a thread sanitizer error"; +} +} // extern "C" +``` + +After compiling your project with one of the sanitizers enabled, if a particular +test triggers a sanitizer error, GoogleTest will report that it failed. diff --git a/thirdparty_builtin/googletest/docs/assets/css/style.scss b/thirdparty_builtin/googletest/docs/assets/css/style.scss new file mode 100644 index 000000000..bb30f418d --- /dev/null +++ b/thirdparty_builtin/googletest/docs/assets/css/style.scss @@ -0,0 +1,5 @@ +--- +--- + +@import "jekyll-theme-primer"; +@import "main"; diff --git a/thirdparty_builtin/googletest/docs/community_created_documentation.md b/thirdparty_builtin/googletest/docs/community_created_documentation.md new file mode 100644 index 000000000..4569075ff --- /dev/null +++ b/thirdparty_builtin/googletest/docs/community_created_documentation.md @@ -0,0 +1,7 @@ +# Community-Created Documentation + +The following is a list, in no particular order, of links to documentation +created by the Googletest community. + +* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md), + by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy) diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/faq.md b/thirdparty_builtin/googletest/docs/faq.md similarity index 80% rename from thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/faq.md rename to thirdparty_builtin/googletest/docs/faq.md index 05ecdd7d8..192809729 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/faq.md +++ b/thirdparty_builtin/googletest/docs/faq.md @@ -1,9 +1,12 @@ -# Googletest FAQ - - +# GoogleTest FAQ ## Why should test suite names and test names not contain underscore? +{: .callout .note} +Note: GoogleTest reserves underscore (`_`) for special purpose keywords, such as +[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition +to the following rationale. + Underscore (`_`) is special, as C++ reserves the following to be used by the compiler and the standard library: @@ -47,42 +50,42 @@ Now, the two `TEST`s will both generate the same class So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and `TestName`. The rule is more constraining than necessary, but it's simple and -easy to remember. It also gives googletest some wiggle room in case its +easy to remember. It also gives GoogleTest some wiggle room in case its implementation needs to change in the future. If you violate the rule, there may not be immediate consequences, but your test may (just may) break with a new compiler (or a new version of the compiler you -are using) or with a new version of googletest. Therefore it's best to follow +are using) or with a new version of GoogleTest. Therefore it's best to follow the rule. -## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? +## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? -First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr, -ptr)`. This is the preferred syntax in the style guide because nullptr does not -have the type problems that NULL does. Which is why NULL does not work. +First of all, you can use `nullptr` with each of these macros, e.g. +`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`, +`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide +because `nullptr` does not have the type problems that `NULL` does. Due to some peculiarity of C++, it requires some non-trivial template meta programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where it's most needed -(otherwise we make the implementation of googletest harder to maintain and more +(otherwise we make the implementation of GoogleTest harder to maintain and more error-prone than necessary). -The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the -*actual* value as the second. It's reasonable that someone wants to write -`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times. -Therefore we implemented it. +Historically, the `EXPECT_EQ()` macro took the *expected* value as its first +argument and the *actual* value as the second, though this argument order is now +discouraged. It was reasonable that someone wanted +to write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested +several times. Therefore we implemented it. -The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion +The need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion fails, you already know that `ptr` must be `NULL`, so it doesn't add any information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)` works just as well. -If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to -support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a -convention on the order of the two arguments for `EXPECT_NE`. This means using -the template meta programming tricks twice in the implementation, making it even -harder to understand and maintain. We believe the benefit doesn't justify the -cost. +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to +support `EXPECT_NE(ptr, NULL)` as well. This means using the template meta +programming tricks twice in the implementation, making it even harder to +understand and maintain. We believe the benefit doesn't justify the cost. Finally, with the growth of the gMock matcher library, we are encouraging people to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One @@ -127,6 +130,7 @@ can much more easily decide which one to use the next time. ## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help! +{: .callout .note} **Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated* now. Please use `EqualsProto`, etc instead. @@ -158,7 +162,7 @@ methods, the parent process will think the calls have never occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` macro. -## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug? +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug? Actually, the bug is in `htonl()`. @@ -176,18 +180,6 @@ template argument, and thus doesn't compile in opt mode when `a` contains a call to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as the solution must work with different compilers on various platforms. -`htonl()` has some other problems as described in `//util/endian/endian.h`, -which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()` -does, only without its problems. We suggest you to use `ghtonl()` instead of -`htonl()`, both in your tests and production code. - -`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems -in `htons()`. - -Don't forget to add `//util/endian` to the list of dependencies in the `BUILD` -file wherever `ghtonl()` and `ghtons()` are used. The library consists of a -single header file and will not bloat your binary. - ## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? If your class has a static data member: @@ -207,10 +199,22 @@ const int Foo::kBar; // No initializer here. ``` Otherwise your code is **invalid C++**, and may break in unexpected ways. In -particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will +particular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will generate an "undefined reference" linker error. The fact that "it used to work" doesn't mean it's valid. It just means that you were lucky. :-) +If the declaration of the static data member is `constexpr` then it is +implicitly an `inline` definition, and a separate definition in `foo.cc` is not +needed: + +```c++ +// foo.h +class Foo { + ... + static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc. +}; +``` + ## Can I derive a test fixture from another? Yes. @@ -221,7 +225,7 @@ cases may want to use the same or slightly different fixtures. For example, you may want to make sure that all of a GUI library's test suites don't leak important system resources like fonts and brushes. -In googletest, you share a fixture among test suites by putting the shared logic +In GoogleTest, you share a fixture among test suites by putting the shared logic in a base test fixture, then deriving from that base a separate fixture for each test suite that wants to use this common logic. You then use `TEST_F()` to write tests using each derived fixture. @@ -260,10 +264,10 @@ TEST_F(FooTest, Baz) { ... } ``` If necessary, you can continue to derive test fixtures from a derived fixture. -googletest has no limit on how deep the hierarchy can be. +GoogleTest has no limit on how deep the hierarchy can be. For a complete example using derived test fixtures, see -[sample5_unittest.cc](../samples/sample5_unittest.cc). +[sample5_unittest.cc](https://github.com/google/googletest/blob/main/googletest/samples/sample5_unittest.cc). ## My compiler complains "void value not ignored as it ought to be." What does this mean? @@ -274,9 +278,10 @@ disabled by our build system. Please see more details ## My death test hangs (or seg-faults). How do I fix it? -In googletest, death tests are run in a child process and the way they work is -delicate. To write death tests you really need to understand how they work. -Please make sure you have read [this](advanced.md#how-it-works). +In GoogleTest, death tests are run in a child process and the way they work is +delicate. To write death tests you really need to understand how they work—see +the details at [Death Assertions](reference/assertions.md#death) in the +Assertions Reference. In particular, death tests don't like having multiple threads in the parent process. So the first thing you can try is to eliminate creating threads outside @@ -295,13 +300,13 @@ program from the beginning in the child process. Therefore make sure your program can run side-by-side with itself and is deterministic. In the end, this boils down to good concurrent programming. You have to make -sure that there is no race conditions or dead locks in your program. No silver +sure that there are no race conditions or deadlocks in your program. No silver bullet - sorry! ## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp} -The first thing to remember is that googletest does **not** reuse the same test -fixture object across multiple tests. For each `TEST_F`, googletest will create +The first thing to remember is that GoogleTest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, GoogleTest will create a **fresh** test fixture object, immediately call `SetUp()`, run the test body, call `TearDown()`, and then delete the test fixture object. @@ -323,7 +328,7 @@ You may still want to use `SetUp()/TearDown()` in the following cases: * C++ does not allow virtual function calls in constructors and destructors. You can call a method declared as virtual, but it will not use dynamic - dispatch, it will use the definition from the class the constructor of which + dispatch. It will use the definition from the class the constructor of which is currently executing. This is because calling a virtual method before the derived class constructor has a chance to run is very dangerous - the virtual method might operate on uninitialized data. Therefore, if you need @@ -332,89 +337,25 @@ You may still want to use `SetUp()/TearDown()` in the following cases: * In the body of a constructor (or destructor), it's not possible to use the `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal test failure that should prevent the test from running, it's necessary to - use `abort` and abort the whole test executable, - or to use `SetUp()` instead of a constructor. + use `abort` and abort the whole test + executable, or to use `SetUp()` instead of a constructor. * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. -* The googletest team is considering making the assertion macros throw on +* The GoogleTest team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use - googletest assertions in a destructor if your code could run on such a + GoogleTest assertions in a destructor if your code could run on such a platform. ## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? -If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is -overloaded or a template, the compiler will have trouble figuring out which -overloaded version it should use. `ASSERT_PRED_FORMAT*` and -`EXPECT_PRED_FORMAT*` don't have this problem. - -If you see this error, you might want to switch to -`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure -message. If, however, that is not an option, you can resolve the problem by -explicitly telling the compiler which version to pick. - -For example, suppose you have - -```c++ -bool IsPositive(int n) { - return n > 0; -} - -bool IsPositive(double x) { - return x > 0; -} -``` - -you will get a compiler error if you write - -```c++ -EXPECT_PRED1(IsPositive, 5); -``` - -However, this will work: - -```c++ -EXPECT_PRED1(static_cast(IsPositive), 5); -``` - -(The stuff inside the angled brackets for the `static_cast` operator is the type -of the function pointer for the `int`-version of `IsPositive()`.) - -As another example, when you have a template function - -```c++ -template -bool IsNegative(T x) { - return x < 0; -} -``` - -you can use it in a predicate assertion like this: - -```c++ -ASSERT_PRED1(IsNegative, -5); -``` - -Things are more interesting if your template has more than one parameters. The -following won't compile: - -```c++ -ASSERT_PRED2(GreaterThan, 5, 0); -``` - -as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which -is one more than expected. The workaround is to wrap the predicate function in -parentheses: - -```c++ -ASSERT_PRED2((GreaterThan), 5, 0); -``` +See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the +Assertions Reference. ## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? @@ -434,7 +375,7 @@ they write This is **wrong and dangerous**. The testing services needs to see the return value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()` function ignores it, your test will be considered successful even if it -has a googletest assertion failure. Very bad. +has a GoogleTest assertion failure. Very bad. We have decided to fix this (thanks to Michael Chastain for the idea). Now, your code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with @@ -469,7 +410,6 @@ C++ is case-sensitive. Did you spell it as `Setup()`? Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and wonder why it's never called. - ## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. You don't have to. Instead of @@ -500,14 +440,14 @@ TEST_F(BarTest, Abc) { ... } TEST_F(BarTest, Def) { ... } ``` -## googletest output is buried in a whole bunch of LOG messages. What do I do? +## GoogleTest output is buried in a whole bunch of LOG messages. What do I do? -The googletest output is meant to be a concise and human-friendly report. If -your test generates textual output itself, it will mix with the googletest +The GoogleTest output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the GoogleTest output, making it hard to read. However, there is an easy solution to this problem. -Since `LOG` messages go to stderr, we decided to let googletest output go to +Since `LOG` messages go to stderr, we decided to let GoogleTest output go to stdout. This way, you can easily separate the two using redirection. For example: @@ -555,7 +495,7 @@ TEST(MyDeathTest, ComplexExpression) { "(Func1|Method) failed"); } -// Death assertions can be used any where in a function. In +// Death assertions can be used anywhere in a function. In // particular, they can be inside a loop. TEST(MyDeathTest, InsideLoop) { // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. @@ -578,11 +518,9 @@ TEST(MyDeathTest, CompoundStatement) { } ``` -gtest-death-test_test.cc contains more examples if you are interested. - ## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? -Googletest needs to be able to create objects of your test fixture class, so it +GoogleTest needs to be able to create objects of your test fixture class, so it must have a default constructor. Normally the compiler will define one for you. However, there are cases where you have to define your own: @@ -597,7 +535,7 @@ However, there are cases where you have to define your own: ## Why does ASSERT_DEATH complain about previous threads that were already joined? With the Linux pthread library, there is no turning back once you cross the line -from single thread to multiple threads. The first time you create a thread, a +from a single thread to multiple threads. The first time you create a thread, a manager thread is created in addition, so you get 3, not 2, threads. Later when the thread you create joins the main thread, the thread count decrements by 1, but the manager thread will never be killed, so you still have 2 threads, which @@ -607,12 +545,12 @@ The new NPTL thread library doesn't suffer from this problem, as it doesn't create a manager thread. However, if you don't control which machine your test runs on, you shouldn't depend on this. -## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? +## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? -googletest does not interleave tests from different test suites. That is, it +GoogleTest does not interleave tests from different test suites. That is, it runs all tests in one test suite first, and then runs all tests in the next test -suite, and so on. googletest does this because it needs to set up a test suite -before the first test in it is run, and tear it down afterwords. Splitting up +suite, and so on. GoogleTest does this because it needs to set up a test suite +before the first test in it is run, and tear it down afterwards. Splitting up the test case would require multiple set-up and tear-down processes, which is inefficient and makes the semantics unclean. @@ -650,29 +588,30 @@ TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } ``` -## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? +## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` makes it harder to search for real problems in the parent's log. Therefore, -googletest only prints them when the death test has failed. +GoogleTest only prints them when the death test has failed. If you really need to see such LOG messages, a workaround is to temporarily break the death test (e.g. by changing the regex pattern it is expected to match). Admittedly, this is a hack. We'll consider a more permanent solution after the fork-and-exec-style death tests are implemented. -## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? +## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives? If you use a user-defined type `FooType` in an assertion, you must make sure there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function defined such that we can print a value of `FooType`. In addition, if `FooType` is declared in a name space, the `<<` operator also -needs to be defined in the *same* name space. See https://abseil.io/tips/49 for details. +needs to be defined in the *same* name space. See +[Tip of the Week #49](http://abseil.io/tips/49) for details. ## How do I suppress the memory leak messages on Windows? -Since the statically initialized googletest singleton requires allocations on +Since the statically initialized GoogleTest singleton requires allocations on the heap, the Visual C++ memory leak detector will report memory leaks at the end of the program run. The easiest way to avoid this is to use the `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any @@ -686,13 +625,13 @@ things accordingly, you are leaking test-only logic into production code and there is no easy way to ensure that the test-only code paths aren't run by mistake in production. Such cleverness also leads to [Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly -advise against the practice, and googletest doesn't provide a way to do it. +advise against the practice, and GoogleTest doesn't provide a way to do it. In general, the recommended way to cause the code to behave differently under -test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject +test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject different functionality from the test and from the production code. Since your production code doesn't link in the for-test logic at all (the -[`testonly`](https://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure +[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure that), there is no danger in accidentally running it. However, if you *really*, *really*, *really* have no choice, and if you follow @@ -703,12 +642,12 @@ whether the code is under test. ## How do I temporarily disable a test? If you have a broken test that you cannot fix right away, you can add the -DISABLED_ prefix to its name. This will exclude it from execution. This is -better than commenting out the code or using #if 0, as disabled tests are still -compiled (and thus won't rot). +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). To include disabled tests in test execution, just invoke the test program with -the --gtest_also_run_disabled_tests flag. +the `--gtest_also_run_disabled_tests` flag. ## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? @@ -733,7 +672,7 @@ TEST(CoolTest, DoSomething) { ``` However, the following code is **not allowed** and will produce a runtime error -from googletest because the test methods are using different test fixture +from GoogleTest because the test methods are using different test fixture classes with the same test suite name. ```c++ diff --git a/thirdparty_builtin/googletest/docs/gmock_cheat_sheet.md b/thirdparty_builtin/googletest/docs/gmock_cheat_sheet.md new file mode 100644 index 000000000..2fb0403e6 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/gmock_cheat_sheet.md @@ -0,0 +1,241 @@ +# gMock Cheat Sheet + +## Defining a Mock Class + +### Mocking a Normal Class {#MockClass} + +Given + +```cpp +class Foo { + public: + virtual ~Foo(); + virtual int GetSize() const = 0; + virtual string Describe(const char* name) = 0; + virtual string Describe(int type) = 0; + virtual bool Process(Bar elem, int count) = 0; +}; +``` + +(note that `~Foo()` **must** be virtual) we can define its mock as + +```cpp +#include "gmock/gmock.h" + +class MockFoo : public Foo { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(string, Describe, (const char* name), (override)); + MOCK_METHOD(string, Describe, (int type), (override)); + MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); +}; +``` + +To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, +which warns on all uninteresting calls, or a "strict" mock, which treats them as +failures: + +```cpp +using ::testing::NiceMock; +using ::testing::NaggyMock; +using ::testing::StrictMock; + +NiceMock nice_foo; // The type is a subclass of MockFoo. +NaggyMock naggy_foo; // The type is a subclass of MockFoo. +StrictMock strict_foo; // The type is a subclass of MockFoo. +``` + +{: .callout .note} +**Note:** A mock object is currently naggy by default. We may make it nice by +default in the future. + +### Mocking a Class Template {#MockTemplate} + +Class templates can be mocked just like any class. + +To mock + +```cpp +template +class StackInterface { + public: + virtual ~StackInterface(); + virtual int GetSize() const = 0; + virtual void Push(const Elem& x) = 0; +}; +``` + +(note that all member functions that are mocked, including `~StackInterface()` +**must** be virtual). + +```cpp +template +class MockStack : public StackInterface { + public: + MOCK_METHOD(int, GetSize, (), (const, override)); + MOCK_METHOD(void, Push, (const Elem& x), (override)); +}; +``` + +### Specifying Calling Conventions for Mock Functions + +If your mock function doesn't use the default calling convention, you can +specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. +For example, + +```cpp + MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); + MOCK_METHOD(int, Bar, (double x, double y), + (const, Calltype(STDMETHODCALLTYPE))); +``` + +where `STDMETHODCALLTYPE` is defined by `` on Windows. + +## Using Mocks in Tests {#UsingMocks} + +The typical work flow is: + +1. Import the gMock names you need to use. All gMock symbols are in the + `testing` namespace unless they are macros or otherwise noted. +2. Create the mock objects. +3. Optionally, set the default actions of the mock objects. +4. Set your expectations on the mock objects (How will they be called? What + will they do?). +5. Exercise code that uses the mock objects; if necessary, check the result + using googletest assertions. +6. When a mock object is destructed, gMock automatically verifies that all + expectations on it have been satisfied. + +Here's an example: + +```cpp +using ::testing::Return; // #1 + +TEST(BarTest, DoesThis) { + MockFoo foo; // #2 + + ON_CALL(foo, GetSize()) // #3 + .WillByDefault(Return(1)); + // ... other default actions ... + + EXPECT_CALL(foo, Describe(5)) // #4 + .Times(3) + .WillRepeatedly(Return("Category 5")); + // ... other expectations ... + + EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 +} // #6 +``` + +## Setting Default Actions {#OnCall} + +gMock has a **built-in default action** for any function that returns `void`, +`bool`, a numeric value, or a pointer. In C++11, it will additionally returns +the default-constructed value, if one exists for the given type. + +To customize the default action for functions with return type `T`, use +[`DefaultValue`](reference/mocking.md#DefaultValue). For example: + +```cpp + // Sets the default action for return type std::unique_ptr to + // creating a new Buzz every time. + DefaultValue>::SetFactory( + [] { return std::make_unique(AccessLevel::kInternal); }); + + // When this fires, the default action of MakeBuzz() will run, which + // will return a new Buzz object. + EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); + + auto buzz1 = mock_buzzer_.MakeBuzz("hello"); + auto buzz2 = mock_buzzer_.MakeBuzz("hello"); + EXPECT_NE(buzz1, nullptr); + EXPECT_NE(buzz2, nullptr); + EXPECT_NE(buzz1, buzz2); + + // Resets the default action for return type std::unique_ptr, + // to avoid interfere with other tests. + DefaultValue>::Clear(); +``` + +To customize the default action for a particular method of a specific mock +object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar +syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you +do not require that the mock method is called. See +[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed +discussion. + +## Setting Expectations {#ExpectCall} + +See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference. + +## Matchers {#MatcherList} + +See the [Matchers Reference](reference/matchers.md). + +## Actions {#ActionList} + +See the [Actions Reference](reference/actions.md). + +## Cardinalities {#CardinalityList} + +See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of +`EXPECT_CALL` in the Mocking Reference. + +## Expectation Order + +By default, expectations can be matched in *any* order. If some or all +expectations must be matched in a given order, you can use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) or +[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of +`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence). + +## Verifying and Resetting a Mock + +gMock will verify the expectations on a mock object when it is destructed, or +you can do it earlier: + +```cpp +using ::testing::Mock; +... +// Verifies and removes the expectations on mock_obj; +// returns true if and only if successful. +Mock::VerifyAndClearExpectations(&mock_obj); +... +// Verifies and removes the expectations on mock_obj; +// also removes the default actions set by ON_CALL(); +// returns true if and only if successful. +Mock::VerifyAndClear(&mock_obj); +``` + +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. + +You can also tell gMock that a mock object can be leaked and doesn't need to be +verified: + +```cpp +Mock::AllowLeak(&mock_obj); +``` + +## Mock Classes + +gMock defines a convenient mock class template + +```cpp +class MockFunction { + public: + MOCK_METHOD(R, Call, (A1, ..., An)); +}; +``` + +See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of +it. + +## Flags + +| Flag | Description | +| :----------------------------- | :---------------------------------------- | +| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | +| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/cook_book.md b/thirdparty_builtin/googletest/docs/gmock_cook_book.md similarity index 88% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/cook_book.md rename to thirdparty_builtin/googletest/docs/gmock_cook_book.md index a49352148..d11282fa6 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/cook_book.md +++ b/thirdparty_builtin/googletest/docs/gmock_cook_book.md @@ -1,10 +1,10 @@ # gMock Cookbook - - You can find recipes for using gMock here. If you haven't yet, please read -[this](for_dummies.md) first to make sure you understand the basics. +[the dummy guide](gmock_for_dummies.md) first to make sure you understand the +basics. +{: .callout .note} **Note:** gMock lives in the `testing` name space. For readability, it is recommended to write `using ::testing::Foo;` once in your file before using the name `Foo` defined by gMock. We omit such `using` statements in this section for @@ -35,13 +35,17 @@ generated method: `noexcept` method. * **`Calltype(...)`** - Sets the call type for the method (e.g. to `STDMETHODCALLTYPE`), useful in Windows. +* **`ref(...)`** - Marks the method with the reference qualification + specified. Required if overriding a method that has reference + qualifications. Eg `ref(&)` or `ref(&&)`. ### Dealing with unprotected commas Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent `MOCK_METHOD` from parsing its arguments correctly: -```cpp {.bad} +{: .bad} +```cpp class MockFoo { public: MOCK_METHOD(std::pair, GetPair, ()); // Won't compile! @@ -51,7 +55,8 @@ class MockFoo { Solution 1 - wrap with parentheses: -```cpp {.good} +{: .good} +```cpp class MockFoo { public: MOCK_METHOD((std::pair), GetPair, ()); @@ -64,7 +69,8 @@ invalid C++. `MOCK_METHOD` removes the parentheses. Solution 2 - define an alias: -```cpp {.good} +{: .good} +```cpp class MockFoo { public: using BoolAndInt = std::pair; @@ -138,6 +144,7 @@ class MockFoo : public Foo { }; ``` +{: .callout .note} **Note:** if you don't mock all versions of the overloaded method, the compiler will give you a warning about some methods in the base class being hidden. To fix that, use `using` to bring them in scope: @@ -177,8 +184,7 @@ class MockStack : public StackInterface { ### Mocking Non-virtual Methods {#MockingNonVirtualMethods} -gMock can mock non-virtual functions to be used in Hi-perf dependency -injection. +gMock can mock non-virtual functions to be used in Hi-perf dependency injection. In this case, instead of sharing a common base class with the real class, your mock class will be *unrelated* to the real class, but contain methods with the @@ -245,9 +251,9 @@ tests. ### Mocking Free Functions -It's possible to use gMock to mock a free function (i.e. a C-style function or a -static method). You just need to rewrite your code to use an interface (abstract -class). +It is not possible to directly mock a free function (i.e. a C-style function or +a static method). If you need to, you can rewrite your code to use an interface +(abstract class). Instead of calling a free function (say, `OpenFile`) directly, introduce an interface for it and have a concrete subclass that calls the free function: @@ -262,7 +268,7 @@ class FileInterface { class File : public FileInterface { public: ... - virtual bool Open(const char* path, const char* mode) { + bool Open(const char* path, const char* mode) override { return OpenFile(path, mode); } }; @@ -279,11 +285,17 @@ If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for [mocking non-virtual methods](#MockingNonVirtualMethods). +Alternatively, instead of introducing a new interface, you can rewrite your code +to accept a std::function instead of the free function, and then use +[MockFunction](#MockFunction) to mock the std::function. + ### Old-Style `MOCK_METHODn` Macros -Before the generic `MOCK_METHOD` macro was introduced, mocks where created using -a family of macros collectively called `MOCK_METHODn`. These macros are still -supported, though migration to the new `MOCK_METHOD` is recommended. +Before the generic `MOCK_METHOD` macro +[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2), +mocks where created using a family of macros collectively called `MOCK_METHODn`. +These macros are still supported, though migration to the new `MOCK_METHOD` is +recommended. The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`: @@ -297,44 +309,86 @@ The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`: Old macros and their new equivalents: - - - - - - - - - - - - - - - - - - - - - - - - - - +
Simple
Old `MOCK_METHOD1(Foo, bool(int))`
New `MOCK_METHOD(bool, Foo, (int))`
Const Method
Old -`MOCK_CONST_METHOD1(Foo, bool(int))`
New -`MOCK_METHOD(bool, Foo, (int), (const))`
Method in a Class Template
Old `MOCK_METHOD1_T(Foo, bool(int))`
New -`MOCK_METHOD(bool, Foo, (int))`
Const Method in a Class Template
Old - `MOCK_CONST_METHOD1_T(Foo, bool(int))`
New - `MOCK_METHOD(bool, Foo, (int), (const))`
Method with Call Type
Old -`MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))`
New `MOCK_METHOD(bool, Foo, (int), -(Calltype(STDMETHODCALLTYPE)))`
Const Method with Call Type
Old `MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))`
New `MOCK_METHOD(bool, Foo, (int), (const, -Calltype(STDMETHODCALLTYPE)))`
Method with Call Type in a Class Template
Old `MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, -bool(int))`
New `MOCK_METHOD(bool, Foo, (int), -(Calltype(STDMETHODCALLTYPE)))`
Const Method with Call Type in a Class Template
Old `MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, -Foo, bool(int))`
New `MOCK_METHOD(bool, Foo, -(int), (const, Calltype(STDMETHODCALLTYPE)))`
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Simple
OldMOCK_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method
OldMOCK_CONST_METHOD1(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method in a Class Template
OldMOCK_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int))
Const Method in a Class Template
OldMOCK_CONST_METHOD1_T(Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const))
Method with Call Type
OldMOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type
OldMOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
Method with Call Type in a Class Template
OldMOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))
Const Method with Call Type in a Class Template
OldMOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))
NewMOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))
### The Nice, the Strict, and the Naggy {#NiceStrictNaggy} @@ -342,8 +396,7 @@ Foo, bool(int))` New `MOCK_METHOD(bool, Foo, If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an "uninteresting call", and the default action (which can be specified using `ON_CALL()`) of the method will be taken. Currently, an uninteresting call will -also by default cause gMock to print a warning. (In the future, we might remove -this warning by default.) +also by default cause gMock to print a warning. However, sometimes you may want to ignore these uninteresting calls, and sometimes you may want to treat them as errors. gMock lets you make the decision @@ -405,13 +458,14 @@ TEST(...) { } ``` +{: .callout .note} NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of *methods* with no expectations); they do not affect *unexpected* calls (calls of methods with expectations, but they don't match). See [Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected). -There are some caveats though (I dislike them just as much as the next guy, but -sadly they are side effects of C++'s limitations): +There are some caveats though (sadly they are side effects of C++'s +limitations): 1. `NiceMock` and `StrictMock` only work for mock methods defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class. @@ -421,17 +475,7 @@ sadly they are side effects of C++'s limitations): `NiceMock >`) is **not** supported. 2. `NiceMock` and `StrictMock` may not work correctly if the destructor of `MockFoo` is not virtual. We would like to fix this, but it - requires cleaning up existing tests. http://b/28934720 tracks the issue. -3. During the constructor or destructor of `MockFoo`, the mock object is *not* - nice or strict. This may cause surprises if the constructor or destructor - calls a mock method on `this` object. (This behavior, however, is consistent - with C++'s general rule: if a constructor or destructor calls a virtual - method of `this` object, that method is treated as non-virtual. In other - words, to the base class's constructor or destructor, `this` object behaves - like an instance of the base class, not the derived class. This rule is - required for safety. Otherwise a base constructor may use members of a - derived class before they are initialized, or a base destructor may use - members of a derived class after they have been destroyed.) + requires cleaning up existing tests. Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you @@ -471,9 +515,9 @@ The trick is to redispatch the method in the mock class: class ScopedMockLog : public LogSink { public: ... - virtual void send(LogSeverity severity, const char* full_filename, + void send(LogSeverity severity, const char* full_filename, const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { + const char* message, size_t message_len) override { // We are only interested in the log severity, full file name, and // log message. Log(severity, full_filename, std::string(message, message_len)); @@ -513,7 +557,7 @@ argument matchers: ```cpp ON_CALL(factory, DoMakeTurtle) - .WillByDefault(MakeMockTurtle()); + .WillByDefault(Return(MakeMockTurtle())); ``` ### Alternative to Mocking Concrete Classes @@ -777,28 +821,12 @@ perhaps your test doesn't need to mock `Concrete()` at all (but it would be oh-so painful to have to define a new mock class whenever you don't need to mock one of its methods). -The trick is to leave a back door in your mock class for accessing the real -methods in the base class: - -```cpp -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD(void, Pure, (int n), (override)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD(int, Concrete, (const char* str), (override)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: +You can call `Foo::Concrete()` inside an action by: ```cpp ... EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) { - return foo.FooConcrete(str); + return foo.Foo::Concrete(str); }); ``` @@ -807,7 +835,7 @@ or tell the mock object that you don't want to mock `Concrete()`: ```cpp ... ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) { - return foo.FooConcrete(str); + return foo.Foo::Concrete(str); }); ``` @@ -848,7 +876,6 @@ A frequently used matcher is `_`, which matches anything: ```cpp EXPECT_CALL(foo, DoThat(_, NotNull())); ``` - ### Combining Matchers {#CombiningMatchers} @@ -871,6 +898,22 @@ using ::testing::Not; NULL)); ``` +Matchers are function objects, and parametrized matchers can be composed just +like any other function. However because their types can be long and rarely +provide meaningful information, it can be easier to express them with C++14 +generic lambdas to avoid specifying types. For example, + +```cpp +using ::testing::Contains; +using ::testing::Property; + +inline constexpr auto HasFoo = [](const auto& f) { + return Property("foo", &MyClass::foo, Contains(f)); +}; +... + EXPECT_THAT(x, HasFoo("blah")); +``` + ### Casting Matchers {#SafeMatcherCast} gMock matchers are statically typed, meaning that the compiler can catch your @@ -1044,11 +1087,12 @@ using ::testing::Lt; ``` says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y < -z`. Note that in this example, it wasn't necessary specify the positional +z`. Note that in this example, it wasn't necessary to specify the positional matchers. As a convenience and example, gMock provides some matchers for 2-tuples, -including the `Lt()` matcher above. See [here](#MultiArgMatchers) for the +including the `Lt()` matcher above. See +[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the complete list. Note that if you want to pass the arguments to a predicate of your own (e.g. @@ -1096,58 +1140,17 @@ Matches(AllOf(Ge(0), Le(100), Ne(50))) ### Using Matchers in googletest Assertions -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in googletest assertions. -It's called `ASSERT_THAT` and `EXPECT_THAT`: - -```cpp - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a googletest test you can write: - -```cpp -#include "gmock/gmock.h" - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; - -... - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and `Baz()`, and -verifies that: - -* `Foo()` returns a string that starts with `"Hello"`. -* `Bar()` returns a string that matches regular expression `"Line \\d+"`. -* `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that *they read like English*. They -generate informative messages too. For example, if the first `EXPECT_THAT()` -above fails, the message will be something like: - -```cpp -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was borrowed from Joe Walnes' -Hamcrest project, which adds `assertThat()` to JUnit. +See [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions +Reference. ### Using Predicates as Matchers -gMock provides a [built-in set](#MatcherList) of matchers. In case you find them -lacking, you can use an arbitrary unary predicate function or functor as a -matcher - as long as the predicate accepts a value of the type you want. You do -this by wrapping the predicate inside the `Truly()` function, for example: +gMock provides a set of built-in matchers for matching arguments with expected +values—see the [Matchers Reference](reference/matchers.md) for more information. +In case you find the built-in set lacking, you can use an arbitrary unary +predicate function or functor as a matcher - as long as the predicate accepts a +value of the type you want. You do this by wrapping the predicate inside the +`Truly()` function, for example: ```cpp using ::testing::Truly; @@ -1159,11 +1162,9 @@ int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } ``` Note that the predicate function / functor doesn't have to return `bool`. It -works as long as the return value can be used as the condition in in statement +works as long as the return value can be used as the condition in the statement `if (condition) ...`. - - ### Matching Arguments that Are Not Copyable When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of @@ -1180,15 +1181,14 @@ executed. Just tell gMock that it should save a reference to `bar`, instead of a copy of it. Here's how: ```cpp -using ::testing::ByRef; using ::testing::Eq; using ::testing::Lt; ... // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); + EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar)))); // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); + EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar)))); ``` Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the @@ -1218,17 +1218,17 @@ that satisfies matcher `m`. For example: - | Expression | Description | | :--------------------------- | :--------------------------------------- | | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument -and be declared as `const`. +and be declared as `const`. Don't use `Property()` against member functions that +you do not own, because taking addresses of functions is fragile and generally +not part of the contract of the function. -BTW, `Field()` and `Property()` can also match plain pointers to objects. For +`Field()` and `Property()` can also match plain pointers to objects. For instance, ```cpp @@ -1303,50 +1303,53 @@ What if you have a pointer to pointer? You guessed it - you can use nested `Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points to a number less than 3 (what a mouthful...). -### Testing a Certain Property of an Object +### Defining a Custom Matcher Class {#CustomMatcherClass} -Sometimes you want to specify that an object argument has a certain property, -but there is no existing matcher that does this. If you want good error -messages, you should [define a matcher](#NewMatchers). If you want to do it -quick and dirty, you could get away with writing an ordinary function. +Most matchers can be simply defined using [the MATCHER* macros](#NewMatchers), +which are terse and flexible, and produce good error messages. However, these +macros are not very explicit about the interfaces they create and are not always +suitable, especially for matchers that will be widely reused. -Let's say you have a mock function that takes an object of type `Foo`, which has -an `int bar()` method and an `int baz()` method, and you want to constrain that -the argument's `bar()` value plus its `baz()` value is a given number. Here's -how you can define a matcher to do it: +For more advanced cases, you may need to define your own matcher class. A custom +matcher allows you to test a specific invariant property of that object. Let's +take a look at how to do so. -```cpp -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; +Imagine you have a mock function that takes an object of type `Foo`, which has +an `int bar()` method and an `int baz()` method. You want to constrain that the +argument's `bar()` value plus its `baz()` value is a given number. (This is an +invariant.) Here's how we can write and use a matcher class to do so: -class BarPlusBazEqMatcher : public MatcherInterface { +```cpp +class BarPlusBazEqMatcher { public: + using is_gtest_matcher = void; + explicit BarPlusBazEqMatcher(int expected_sum) : expected_sum_(expected_sum) {} bool MatchAndExplain(const Foo& foo, - MatchResultListener* /* listener */) const override { + std::ostream* /* listener */) const { return (foo.bar() + foo.baz()) == expected_sum_; } - void DescribeTo(std::ostream* os) const override { + void DescribeTo(std::ostream* os) const { *os << "bar() + baz() equals " << expected_sum_; } - void DescribeNegationTo(std::ostream* os) const override { + void DescribeNegationTo(std::ostream* os) const { *os << "bar() + baz() does not equal " << expected_sum_; } private: const int expected_sum_; }; -Matcher BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); +::testing::Matcher BarPlusBazEq(int expected_sum) { + return BarPlusBazEqMatcher(expected_sum); } ... - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; + Foo foo; + EXPECT_THAT(foo, BarPlusBazEq(5))...; ``` ### Matching Containers @@ -1422,14 +1425,19 @@ using ::testing::ElementsAreArray; Use `Pair` when comparing maps or other associative containers. +{% raw %} + ```cpp -using testing::ElementsAre; -using testing::Pair; +using ::testing::UnorderedElementsAre; +using ::testing::Pair; ... - std::map m = {{"a", 1}, {"b", 2}, {"c", 3}}; - EXPECT_THAT(m, ElementsAre(Pair("a", 1), Pair("b", 2), Pair("c", 3))); + absl::flat_hash_map m = {{"a", 1}, {"b", 2}, {"c", 3}}; + EXPECT_THAT(m, UnorderedElementsAre( + Pair("a", 1), Pair("b", 2), Pair("c", 3))); ``` +{% endraw %} + **Tips:** * `ElementsAre*()` can be used to match *any* container that implements the @@ -1442,8 +1450,8 @@ using testing::Pair; * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. * The order of elements *matters* for `ElementsAre*()`. If you are using it - with containers whose element order are undefined (e.g. `hash_map`) you - should use `WhenSorted` around `ElementsAre`. + with containers whose element order are undefined (such as a + `std::unordered_map`) you should use `UnorderedElementsAre`. ### Sharing Matchers @@ -1453,7 +1461,7 @@ the pointer is copied. When the last matcher that references the implementation object dies, the implementation object will be deleted. Therefore, if you have some complex matcher that you want to use again and -again, there is no need to build it everytime. Just assign it to a matcher +again, there is no need to build it every time. Just assign it to a matcher variable and use that variable repeatedly! For example, ```cpp @@ -1468,6 +1476,7 @@ using ::testing::Matcher; ### Matchers must have no side-effects {#PureMatchers} +{: .callout .warning} WARNING: gMock does not guarantee when or how many times a matcher will be invoked. Therefore, all matchers must be *purely functional*: they cannot have any side effects, and the match result must not depend on anything other than @@ -1482,8 +1491,6 @@ mock object and gMock. ### Knowing When to Expect {#UseOnCall} - - **`ON_CALL`** is likely the *single most under-utilized construct* in gMock. There are basically two constructs for defining the behavior of a mock object: @@ -1675,11 +1682,11 @@ times from calling it with the wrong arguments. ### Expecting Ordered Calls {#OrderedCalls} -Although an `EXPECT_CALL()` statement defined earlier takes precedence when -gMock tries to match a function call with an expectation, by default calls don't -have to happen in the order `EXPECT_CALL()` statements are written. For example, -if the arguments match the matchers in the third `EXPECT_CALL()`, but not those -in the first two, then the third expectation will be used. +Although an `EXPECT_CALL()` statement defined later takes precedence when gMock +tries to match a function call with an expectation, by default calls don't have +to happen in the order `EXPECT_CALL()` statements are written. For example, if +the arguments match the matchers in the second `EXPECT_CALL()`, but not those in +the first and third, then the second expectation will be used. If you would rather have all calls occur in the order of the expectations, put the `EXPECT_CALL()` statements in a block where you define a variable of type @@ -1712,8 +1719,8 @@ brittle tests. For example, we may care about `A` occurring before both `B` and the test should reflect our real intent, instead of being overly constraining. gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the -calls. One way to express the DAG is to use the [After](#AfterClause) clause of -`EXPECT_CALL`. +calls. One way to express the DAG is to use the +[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`. Another way is via the `InSequence()` clause (not the same as the `InSequence` class), which we borrowed from jMock 2. It's less flexible than `After()`, but @@ -1756,7 +1763,7 @@ specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): | A ---| | - +---> C ---> D + +---> C ---> D ``` This means that A must occur before B and C, and C must occur before D. There's @@ -1851,10 +1858,9 @@ Methods"). However, gMock doesn't let you use `ReturnRef()` in a mock function whose return type is not a reference, as doing that usually indicates a user error. So, what shall you do? -Though you may be tempted, DO NOT use `ByRef()`: +Though you may be tempted, DO NOT use `std::ref()`: ```cpp -using testing::ByRef; using testing::Return; class MockFoo : public Foo { @@ -1865,7 +1871,7 @@ class MockFoo : public Foo { int x = 0; MockFoo foo; EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(Return(ByRef(x))); // Wrong! + .WillRepeatedly(Return(std::ref(x))); // Wrong! x = 42; EXPECT_EQ(42, foo.GetValue()); ``` @@ -1881,9 +1887,9 @@ Expected: 42 The reason is that `Return(*value*)` converts `value` to the actual return type of the mock function at the time when the action is *created*, not when it is *executed*. (This behavior was chosen for the action to be safe when `value` is -a proxy object that references some temporary objects.) As a result, `ByRef(x)` -is converted to an `int` value (instead of a `const int&`) when the expectation -is set, and `Return(ByRef(x))` will always return 0. +a proxy object that references some temporary objects.) As a result, +`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when +the expectation is set, and `Return(std::ref(x))` will always return 0. `ReturnPointee(pointer)` was provided to solve this problem specifically. It returns the value pointed to by `pointer` at the time the action is *executed*: @@ -1902,7 +1908,7 @@ using testing::ReturnPointee; ### Combining Actions Want to do more than one thing when a function is called? That's fine. `DoAll()` -allow you to do sequence of actions every time. Only the return value of the +allows you to do a sequence of actions every time. Only the return value of the last action in the sequence will be used. ```cpp @@ -1983,6 +1989,7 @@ If the mock method also needs to return a value as well, you can chain ```cpp using ::testing::_; +using ::testing::DoAll; using ::testing::Return; using ::testing::SetArgPointee; @@ -2036,10 +2043,7 @@ class MockRolodex : public Rolodex { } ... MockRolodex rolodex; - vector names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); + vector names = {"George", "John", "Thomas"}; EXPECT_CALL(rolodex, GetNames(_)) .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); ``` @@ -2128,7 +2132,7 @@ class MockFoo : public Foo { DefaultValue::Clear(); ``` -Please note that changing the default value for a type can make you tests hard +Please note that changing the default value for a type can make your tests hard to understand. We recommend you to use this feature judiciously. For example, you may want to make sure the `Set()` and `Clear()` calls are right next to the code that uses your mock. @@ -2174,9 +2178,7 @@ own precedence order distinct from the `ON_CALL` precedence order. ### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions} If the built-in actions don't suit you, you can use an existing callable -(function, `std::function`, method, functor, lambda as an action. - - +(function, `std::function`, method, functor, lambda) as an action. ```cpp using ::testing::_; using ::testing::Invoke; @@ -2203,6 +2205,7 @@ class Helper { .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1))); EXPECT_CALL(foo, ComplexJob(_)) .WillOnce(Invoke(&helper, &Helper::ComplexJob)) + .WillOnce([] { return true; }) .WillRepeatedly([](int x) { return x > 0; }); foo.Sum(5, 6); // Invokes CalculateSum(5, 6). @@ -2212,13 +2215,13 @@ class Helper { ``` The only requirement is that the type of the function, etc must be *compatible* -with the signature of the mock function, meaning that the latter's arguments can -be implicitly converted to the corresponding arguments of the former, and the -former's return type can be implicitly converted to that of the latter. So, you -can invoke something whose type is *not* exactly the same as the mock function, -as long as it's safe to do so - nice, huh? +with the signature of the mock function, meaning that the latter's arguments (if +it takes any) can be implicitly converted to the corresponding arguments of the +former, and the former's return type can be implicitly converted to that of the +latter. So, you can invoke something whose type is *not* exactly the same as the +mock function, as long as it's safe to do so - nice, huh? -**`Note:`{.escaped}** +Note that: * The action takes ownership of the callback and will delete it when the action itself is destructed. @@ -2267,19 +2270,20 @@ TEST_F(FooTest, Test) { ### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments -`Invoke()` is very useful for doing actions that are more complex. It passes the -mock function's arguments to the function, etc being invoked such that the -callee has the full context of the call to work with. If the invoked function is -not interested in some or all of the arguments, it can simply ignore them. +`Invoke()` passes the mock function's arguments to the function, etc being +invoked such that the callee has the full context of the call to work with. If +the invoked function is not interested in some or all of the arguments, it can +simply ignore them. Yet, a common pattern is that a test author wants to invoke a function without -the arguments of the mock function. `Invoke()` allows her to do that using a -wrapper function that throws away the arguments before invoking an underlining -nullary function. Needless to say, this can be tedious and obscures the intent -of the test. +the arguments of the mock function. She could do that using a wrapper function +that throws away the arguments before invoking an underlining nullary function. +Needless to say, this can be tedious and obscures the intent of the test. -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except that it -doesn't pass the mock function's arguments to the callee. Here's an example: +There are two solutions to this problem. First, you can pass any callable of +zero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like +`Invoke()` except that it doesn't pass the mock function's arguments to the +callee. Here's an example of each: ```cpp using ::testing::_; @@ -2296,14 +2300,14 @@ bool Job2(int n, char c) { ... } ... MockFoo foo; EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)) + .WillOnce([] { Job1(); }); .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a'))); foo.ComplexJob(10); // Invokes Job1(). foo.ComplexJob(20); // Invokes Job2(5, 'a'). ``` -**`Note:`{.escaped}** +Note that: * The action takes ownership of the callback and will delete it when the action itself is destructed. @@ -2346,6 +2350,7 @@ using ::testing::_; // second argument DoThis() receives. ``` +{: .callout .note} NOTE: The section below is legacy documentation from before C++ had lambdas: Arghh, you need to refer to a mock function argument but C++ has no lambda @@ -2374,7 +2379,7 @@ using ::testing::InvokeArgument; ``` What if the callable takes an argument by reference? No problem - just wrap it -inside `ByRef()`: +inside `std::ref()`: ```cpp ... @@ -2383,20 +2388,19 @@ inside `ByRef()`: (override)); ... using ::testing::_; - using ::testing::ByRef; using ::testing::InvokeArgument; ... MockFoo foo; Helper helper; ... EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callback. + .WillOnce(InvokeArgument<0>(5, std::ref(helper))); + // std::ref(helper) guarantees that a reference to helper, not a copy of + // it, will be passed to the callback. ``` What if the callable takes an argument by reference and we do **not** wrap the -argument in `ByRef()`? Then `InvokeArgument()` will *make a copy* of the +argument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the argument, and pass a *reference to the copy*, instead of a reference to the original value, to the callable. This is especially handy when the argument is a temporary value: @@ -2607,7 +2611,7 @@ efficient. When the last action that references the implementation object dies, the implementation object will be deleted. If you have some complex action that you want to use again and again, you may -not have to build it from scratch everytime. If the action doesn't have an +not have to build it from scratch every time. If the action doesn't have an internal state (i.e. if it always does the same thing no matter how many times it has been called), you can assign it to an action variable and use that variable repeatedly. For example: @@ -2667,26 +2671,18 @@ behavior nondeterministic. A better way is to use gMock actions and `Notification` objects to force your asynchronous test to behave synchronously. ```cpp -using ::testing::DoAll; -using ::testing::InvokeWithoutArgs; -using ::testing::Return; - class MockEventDispatcher : public EventDispatcher { MOCK_METHOD(bool, DispatchEvent, (int32), (override)); }; -ACTION_P(Notify, notification) { - notification->Notify(); -} - TEST(EventQueueTest, EnqueueEventTest) { MockEventDispatcher mock_event_dispatcher; EventQueue event_queue(&mock_event_dispatcher); const int32 kEventId = 321; - Notification done; + absl::Notification done; EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId)) - .WillOnce(Notify(&done)); + .WillOnce([&done] { done.Notify(); }); event_queue.EnqueueEvent(kEventId); done.WaitForNotification(); @@ -2699,6 +2695,7 @@ additional action to notify the `Notification` object. Now we can just call asynchronous call to finish. After that, our test suite is complete and we can safely exit. +{: .callout .note} Note: this example has a downside: namely, if the expectation is not satisfied, our test will run forever. It will eventually time-out and fail, but it will take longer and be slightly harder to debug. To alleviate this problem, you can @@ -2791,7 +2788,7 @@ If you just need to return a pre-defined move-only value, you can use the // When this fires, the unique_ptr<> specified by ByMove(...) will // be returned. EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) - .WillOnce(Return(ByMove(MakeUnique(AccessLevel::kInternal)))); + .WillOnce(Return(ByMove(std::make_unique(AccessLevel::kInternal)))); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world")); ``` @@ -2812,7 +2809,7 @@ pretty much anything you want: ```cpp EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) .WillRepeatedly([](StringPiece text) { - return MakeUnique(AccessLevel::kInternal); + return std::make_unique(AccessLevel::kInternal); }); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); @@ -2831,7 +2828,7 @@ can always use `Return`, or a [lambda or functor](#FunctionsAsActions): using ::testing::Unused; EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true)); - EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal)), + EXPECT_TRUE(mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal)), 0); EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce( @@ -2849,8 +2846,8 @@ work with non-copyable objects; you'll have to use functors instead. #### Legacy workarounds for move-only types {#LegacyMoveOnly} Support for move-only function arguments was only introduced to gMock in April -2017. In older code, you may encounter the following workaround for the lack of -this feature (it is no longer necessary - we're including it just for +of 2017. In older code, you may encounter the following workaround for the lack +of this feature (it is no longer necessary - we're including it just for reference): ```cpp @@ -2875,7 +2872,7 @@ method: // When one calls ShareBuzz() on the MockBuzzer like this, the call is // forwarded to DoShareBuzz(), which is mocked. Therefore this statement // will trigger the above EXPECT_CALL. - mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal), 0); + mock_buzzer_.ShareBuzz(std::make_unique(AccessLevel::kInternal), 0); ``` ### Making the Compilation Faster @@ -2978,36 +2975,27 @@ TEST(MyServerTest, ProcessesRequest) { } // server is destroyed when it goes out of scope here. ``` +{: .callout .tip} **Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to indicate whether the verification was successful (`true` for yes), so you can wrap that function call inside a `ASSERT_TRUE()` if there is no point going further when the verification has failed. -### Using Check Points {#UsingCheckPoints} - -Sometimes you may want to "reset" a mock object at various check points in your -test: at each check point, you verify that all existing expectations on the mock -object have been satisfied, and then you set some new expectations on it as if -it's newly created. This allows you to work with a mock object in "phases" whose -sizes are each manageable. +Do not set new expectations after verifying and clearing a mock after its use. +Setting expectations after code that exercises the mock has undefined behavior. +See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more +information. -One such scenario is that in your test's `SetUp()` function, you may want to put -the object you are testing into a certain state, with the help from a mock -object. Once in the desired state, you want to clear all expectations on the -mock, such that in the `TEST_F` body you can set fresh expectations on it. +### Using Checkpoints {#UsingCheckPoints} -As you may have figured out, the `Mock::VerifyAndClearExpectations()` function -we saw in the previous recipe can help you here. Or, if you are using -`ON_CALL()` to set default actions on the mock object and want to clear the -default actions as well, use `Mock::VerifyAndClear(&mock_object)` instead. This -function does what `Mock::VerifyAndClearExpectations(&mock_object)` does and -returns the same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. +Sometimes you might want to test a mock object's behavior in phases whose sizes +are each manageable, or you might want to set more detailed expectations about +which API calls invoke which mock functions. -Another trick you can use to achieve the same effect is to put the expectations -in sequences and insert calls to a dummy "check-point" function at specific -places. Then you can verify that the mock function calls do happen at the right -time. For example, if you are exercising code: +A technique you can use is to put the expectations in a sequence and insert +calls to a dummy "checkpoint" function at specific places. Then you can verify +that the mock function calls do happen at the right time. For example, if you +are exercising the code: ```cpp Foo(1); @@ -3016,7 +3004,7 @@ time. For example, if you are exercising code: ``` and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but -`Foo(2)` doesn't invoke anything. You can write: +`Foo(2)` doesn't invoke anything, you can write: ```cpp using ::testing::MockFunction; @@ -3042,10 +3030,10 @@ TEST(FooTest, InvokesBarCorrectly) { } ``` -The expectation spec says that the first `Bar("a")` must happen before check -point "1", the second `Bar("a")` must happen after check point "2", and nothing -should happen between the two check points. The explicit check points make it -easy to tell which `Bar("a")` is called by which call to `Foo()`. +The expectation spec says that the first `Bar("a")` call must happen before +checkpoint "1", the second `Bar("a")` call must happen after checkpoint "2", and +nothing should happen between the two checkpoints. The explicit checkpoints make +it clear which `Bar("a")` is called by which call to `Foo()`. ### Mocking Destructors @@ -3071,7 +3059,7 @@ class MockFoo : public Foo { ... // Add the following two lines to the mock class. MOCK_METHOD(void, Die, ()); - virtual ~MockFoo() { Die(); } + ~MockFoo() override { Die(); } }; ``` @@ -3270,8 +3258,6 @@ If you are interested in the mock call trace but not the stack traces, you can combine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test command line. - - ### Running Tests in Emacs If you build and run your tests in Emacs using the `M-x google-compile` command @@ -3296,6 +3282,7 @@ after typing `M-m`), or `M-up`/`M-down` to move back and forth between errors. ### Writing New Matchers Quickly {#NewMatchers} +{: .callout .warning} WARNING: gMock does not guarantee when or how many times a matcher will be invoked. Therefore, all matchers must be functionally pure. See [this section](#PureMatchers) for more details. @@ -3340,7 +3327,7 @@ or, ```cpp using ::testing::Not; ... - // Verifies that two values are divisible by 7. + // Verifies that a value is divisible by 7 and the other is not. EXPECT_THAT(some_expression, IsDivisibleBy7()); EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); ``` @@ -3399,6 +3386,7 @@ match succeeds in case of a success (unless it's obvious) - this is useful when the matcher is used inside `Not()`. There is no need to print the argument value itself, as gMock already prints it for you. +{: .callout .note} NOTE: The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the @@ -3537,51 +3525,39 @@ MATCHER_P2(Blah, a, b, description_string_2) { ... } ``` While it's tempting to always use the `MATCHER*` macros when defining a new -matcher, you should also consider implementing `MatcherInterface` or using -`MakePolymorphicMatcher()` instead (see the recipes that follow), especially if -you need to use the matcher a lot. While these approaches require more work, -they give you more control on the types of the value being matched and the -matcher parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers based on -parameter types (as opposed to just based on the number of parameters). +matcher, you should also consider implementing the matcher interface directly +instead (see the recipes that follow), especially if you need to use the matcher +a lot. While these approaches require more work, they give you more control on +the types of the value being matched and the matcher parameters, which in +general leads to better compiler error messages that pay off in the long run. +They also allow overloading matchers based on parameter types (as opposed to +just based on the number of parameters). ### Writing New Monomorphic Matchers -A matcher of argument type `T` implements `::testing::MatcherInterface` and -does two things: it tests whether a value of type `T` matches the matcher, and -can describe what kind of values it matches. The latter ability is used for +A matcher of argument type `T` implements the matcher interface for `T` and does +two things: it tests whether a value of type `T` matches the matcher, and can +describe what kind of values it matches. The latter ability is used for generating readable error messages when expectations are violated. -The interface looks like this: +A matcher of `T` must declare a typedef like: ```cpp -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - std::ostream* stream(); -}; +using is_gtest_matcher = void; +``` -template -class MatcherInterface { - public: - virtual ~MatcherInterface(); +and supports the following operations: - // Returns true if and only if the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(std::ostream* os) const = 0; +```cpp +// Match a value and optionally explain into an ostream. +bool matched = matcher.MatchAndExplain(value, maybe_os); +// where `value` is of type `T` and +// `maybe_os` is of type `std::ostream*`, where it can be null if the caller +// is not interested in there textual explanation. - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(std::ostream* os) const; -}; +matcher.DescribeTo(os); +matcher.DescribeNegationTo(os); +// where `os` is of type `std::ostream*`. ``` If you need a custom matcher but `Truly()` is not a good option (for example, @@ -3596,29 +3572,27 @@ For example, you can define a matcher to test whether an `int` is divisible by 7 and then use it like this: ```cpp -using ::testing::MakeMatcher; using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -class DivisibleBy7Matcher : public MatcherInterface { +class DivisibleBy7Matcher { public: - bool MatchAndExplain(int n, - MatchResultListener* /* listener */) const override { + using is_gtest_matcher = void; + + bool MatchAndExplain(int n, std::ostream*) const { return (n % 7) == 0; } - void DescribeTo(std::ostream* os) const override { + void DescribeTo(std::ostream* os) const { *os << "is divisible by 7"; } - void DescribeNegationTo(std::ostream* os) const override { + void DescribeNegationTo(std::ostream* os) const { *os << "is not divisible by 7"; } }; Matcher DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); + return DivisibleBy7Matcher(); } ... @@ -3626,16 +3600,15 @@ Matcher DivisibleBy7() { ``` You may improve the matcher message by streaming additional information to the -`listener` argument in `MatchAndExplain()`: +`os` argument in `MatchAndExplain()`: ```cpp -class DivisibleBy7Matcher : public MatcherInterface { +class DivisibleBy7Matcher { public: - bool MatchAndExplain(int n, - MatchResultListener* listener) const override { + bool MatchAndExplain(int n, std::ostream* os) const { const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; + if (remainder != 0 && os != nullptr) { + *os << "the remainder is " << remainder; } return remainder == 0; } @@ -3651,15 +3624,87 @@ Expected: is divisible by 7 Actual: 23 (the remainder is 2) ``` +{: .callout .tip} +Tip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*` +instead of `std::ostream*`. + ### Writing New Polymorphic Matchers -You've learned how to write your own matchers in the previous recipe. Just one -problem: a matcher created using `MakeMatcher()` only works for one particular -type of arguments. If you want a *polymorphic* matcher that works with arguments -of several types (for instance, `Eq(x)` can be used to match a *`value`* as long -as `value == x` compiles -- *`value`* and `x` don't have to share the same -type), you can learn the trick from `testing/base/public/gmock-matchers.h` but -it's a bit involved. +Expanding what we learned above to *polymorphic* matchers is now just as simple +as adding templates in the right place. + +```cpp + +class NotNullMatcher { + public: + using is_gtest_matcher = void; + + // To implement a polymorphic matcher, we just need to make MatchAndExplain a + // template on its first argument. + + // In this example, we want to use NotNull() with any pointer, so + // MatchAndExplain() accepts a pointer of any type as its first argument. + // In general, you can define MatchAndExplain() as an ordinary method or + // a method template, or even overload it. + template + bool MatchAndExplain(T* p, std::ostream*) const { + return p != nullptr; + } + + // Describes the property of a value matching this matcher. + void DescribeTo(std::ostream* os) const { *os << "is not NULL"; } + + // Describes the property of a value NOT matching this matcher. + void DescribeNegationTo(std::ostream* os) const { *os << "is NULL"; } +}; + +NotNullMatcher NotNull() { + return NotNullMatcher(); +} + +... + + EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. +``` + +### Legacy Matcher Implementation + +Defining matchers used to be somewhat more complicated, in which it required +several supporting classes and virtual functions. To implement a matcher for +type `T` using the legacy API you have to derive from `MatcherInterface` and +call `MakeMatcher` to construct the object. + +The interface looks like this: + +```cpp +class MatchResultListener { + public: + ... + // Streams x to the underlying ostream; does nothing if the ostream + // is NULL. + template + MatchResultListener& operator<<(const T& x); + + // Returns the underlying ostream. + std::ostream* stream(); +}; + +template +class MatcherInterface { + public: + virtual ~MatcherInterface(); + + // Returns true if and only if the matcher matches x; also explains the match + // result to 'listener'. + virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; + + // Describes this matcher to an ostream. + virtual void DescribeTo(std::ostream* os) const = 0; + + // Describes the negation of this matcher to an ostream. + virtual void DescribeNegationTo(std::ostream* os) const; +}; +``` Fortunately, most of the time you can define a polymorphic matcher easily with the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as @@ -3704,6 +3749,7 @@ PolymorphicMatcher NotNull() { EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. ``` +{: .callout .note} **Note:** Your polymorphic matcher class does **not** need to inherit from `MatcherInterface` or any other class, and its methods do **not** need to be virtual. @@ -3717,8 +3763,8 @@ A cardinality is used in `Times()` to tell gMock how many times you expect a call to occur. It doesn't have to be exact. For example, you can say `AtLeast(5)` or `Between(2, 4)`. -If the [built-in set](cheat_sheet.md#CardinalityList) of cardinalities doesn't -suit you, you are free to define your own by implementing the following +If the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities +doesn't suit you, you are free to define your own by implementing the following interface (in namespace `testing`): ```cpp @@ -3770,22 +3816,19 @@ Cardinality EvenNumber() { .Times(EvenNumber()); ``` -### Writing New Actions Quickly {#QuickNewActions} +### Writing New Actions {#QuickNewActions} If the built-in actions don't work for you, you can easily define your own one. -Just define a functor class with a (possibly templated) call operator, matching -the signature of your action. +All you need is a call operator with a signature compatible with the mocked +function. So you can use a lambda: -```cpp -struct Increment { - template - T operator()(T* arg) { - return ++(*arg); - } -} +``` +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; }); +EXPECT_EQ(14, mock.AsStdFunction()(2)); ``` -The same approach works with stateful functors (or any callable, really): +Or a struct with a call operator (even a templated one): ``` struct MultiplyBy { @@ -3793,12 +3836,54 @@ struct MultiplyBy { T operator()(T arg) { return arg * multiplier; } int multiplier; -} +}; // Then use: // EXPECT_CALL(...).WillOnce(MultiplyBy{7}); ``` +It's also fine for the callable to take no arguments, ignoring the arguments +supplied to the mock function: + +``` +MockFunction mock; +EXPECT_CALL(mock, Call).WillOnce([] { return 17; }); +EXPECT_EQ(17, mock.AsStdFunction()(0)); +``` + +When used with `WillOnce`, the callable can assume it will be called at most +once and is allowed to be a move-only type: + +``` +// An action that contains move-only types and has an &&-qualified operator, +// demanding in the type system that it be called at most once. This can be +// used with WillOnce, but the compiler will reject it if handed to +// WillRepeatedly. +struct MoveOnlyAction { + std::unique_ptr move_only_state; + std::unique_ptr operator()() && { return std::move(move_only_state); } +}; + +MockFunction()> mock; +EXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique(17)}); +EXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17))); +``` + +More generally, to use with a mock function whose signature is `R(Args...)` the +object can be anything convertible to `OnceAction` or +`Action. The difference between the two is that `OnceAction` has +weaker requirements (`Action` requires a copy-constructible input that can be +called repeatedly whereas `OnceAction` requires only move-constructible and +supports `&&`-qualified call operators), but can be used only with `WillOnce`. +`OnceAction` is typically relevant only when supporting move-only types or +actions that want a type-system guarantee that they will be called at most once. + +Typically the `OnceAction` and `Action` templates need not be referenced +directly in your actions: a struct or class with a call operator is sufficient, +as in the examples above. But fancier polymorphic actions that need to know the +specific return type of the mock function can define templated conversion +operators to make that possible. See `gmock-actions.h` for examples. + #### Legacy macro-based Actions Before C++11, the functor-based actions were not supported; the old way of @@ -4041,23 +4126,18 @@ If you are writing a function that returns an `ACTION` object, you'll need to know its type. The type depends on the macro used to define the action and the parameter types. The rule is relatively simple: + | Given Definition | Expression | Has Type | | ----------------------------- | ------------------- | --------------------- | | `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo,` | `Foo()` : t_m>` : -: `AND_0_VALUE_PARAMS())` : : : +| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo()` | `FooAction` | | `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | -| `ACTION_TEMPLATE(Bar,` | `Bar` | `FooActionP` : -: `AND_1_VALUE_PARAMS(p1))` : : : -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value,` | `BazActionP2` : -| `ACTION_TEMPLATE(Baz,` | `Baz` | `FooActionP2` : -: `AND_2_VALUE_PARAMS(p1, p2))` : `int_value)` : : +| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar(int_value)` | `BarActionP` | +| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz(bool_value, int_value)` | `BazActionP2` | | ... | ... | ... | + Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, and etc) for actions with different numbers of value parameters, or the action definitions cannot be overloaded on the number of them. @@ -4157,7 +4237,7 @@ This implementation class does *not* need to inherit from any particular class. What matters is that it must have a `Perform()` method template. This method template takes the mock function's arguments as a tuple in a **single** argument, and returns the result of the action. It can be either `const` or not, -but must be invokable with exactly one template argument, which is the result +but must be invocable with exactly one template argument, which is the result type. In other words, you must be able to call `Perform(args)` where `R` is the mock function's return type and `args` is its arguments in a tuple. @@ -4206,7 +4286,7 @@ value printer. This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the `<<` operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. -[googletest's advanced guide](../../googletest/docs/advanced.md#teaching-googletest-how-to-print-your-values) +[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values) explains how to extend the printer to do a better job at printing your particular type than to dump the bytes. @@ -4265,5 +4345,3 @@ expectations. Although `std::function` supports unlimited number of arguments, `MockFunction` implementation is limited to ten. If you ever hit that limit... well, your callback has bigger problems than being mockable. :-) - - diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/gmock_faq.md b/thirdparty_builtin/googletest/docs/gmock_faq.md similarity index 96% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/gmock_faq.md rename to thirdparty_builtin/googletest/docs/gmock_faq.md index 214aabf12..8f220bf7a 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/gmock_faq.md +++ b/thirdparty_builtin/googletest/docs/gmock_faq.md @@ -1,11 +1,9 @@ -## Legacy gMock FAQ {#GMockFaq} - - +# Legacy gMock FAQ ### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? In order for a method to be mocked, it must be *virtual*, unless you use the -[high-perf dependency injection technique](#MockingNonVirtualMethods). +[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods). ### Can I mock a variadic function? @@ -81,8 +79,6 @@ void Bar(int* p); // Neither p nor *p is const. void Bar(const int* p); // p is not const, but *p is. ``` - - ### I can't figure out why gMock thinks my expectations are not satisfied. What should I do? You might want to run your test with `--gmock_verbose=info`. This flag lets @@ -91,7 +87,7 @@ trace, you'll gain insights on why the expectations you set are not met. If you see the message "The mock function has no default action set, and its return type has no default value set.", then try -[adding a default action](for_dummies.md#DefaultValue). Due to a known issue, +[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue, unexpected calls on mocks without default actions don't print out a detailed comparison between the actual arguments and the expected arguments. @@ -126,8 +122,6 @@ using ::testing::_; .Times(0); ``` - - ### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? When gMock detects a failure, it prints relevant information (the mock function @@ -375,8 +369,8 @@ Usually, if your action is for a particular function type, defining it using different types (e.g. if you are defining `Return(*value*)`), `MakePolymorphicAction()` is easiest. Sometimes you want precise control on what types of functions the action can be used in, and implementing `ActionInterface` -is the way to go here. See the implementation of `Return()` in -`testing/base/public/gmock-actions.h` for an example. +is the way to go here. See the implementation of `Return()` in `gmock-actions.h` +for an example. ### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean? @@ -386,8 +380,8 @@ doesn't say what the return value should be. You need `DoAll()` to chain a `SetArgPointee()` with a `Return()` that provides a value appropriate to the API being mocked. -See this [recipe](cook_book.md#mocking-side-effects) for more details and an -example. +See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and +an example. ### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/for_dummies.md b/thirdparty_builtin/googletest/docs/gmock_for_dummies.md similarity index 91% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/for_dummies.md rename to thirdparty_builtin/googletest/docs/gmock_for_dummies.md index 93cf06f38..b7264d358 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/docs/for_dummies.md +++ b/thirdparty_builtin/googletest/docs/gmock_for_dummies.md @@ -1,8 +1,6 @@ -## gMock for Dummies {#GMockForDummies} +# gMock for Dummies - - -### What Is gMock? +## What Is gMock? When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real @@ -10,9 +8,9 @@ object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). -**Note:** It is easy to confuse the term *fake objects* with mock objects. Fakes -and mocks actually mean very different things in the Test-Driven Development -(TDD) community: +It is easy to confuse the term *fake objects* with mock objects. Fakes and mocks +actually mean very different things in the Test-Driven Development (TDD) +community: * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them @@ -39,7 +37,7 @@ When using gMock, 3. then you exercise code that uses the mock objects. gMock will catch any violation to the expectations as soon as it arises. -### Why gMock? +## Why gMock? While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is *hard*: @@ -53,9 +51,9 @@ them fast and reliable, using mocks manually in C++ is *hard*: one. In contrast, Java and Python programmers have some fine mock frameworks (jMock, -EasyMock, [Mox](http://wtf/mox), etc), which automate the creation of mocks. As -a result, mocking is a proven effective technique and widely adopted practice in -those communities. Having the right tool absolutely makes the difference. +EasyMock, etc), which automate the creation of mocks. As a result, mocking is a +proven effective technique and widely adopted practice in those communities. +Having the right tool absolutely makes the difference. gMock was built to help C++ programmers. It was inspired by jMock and EasyMock, but designed with C++'s specifics in mind. It is your friend if any of the @@ -85,11 +83,11 @@ We encourage you to use gMock as * a *testing* tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. -### Getting Started +## Getting Started gMock is bundled with googletest. -### A Case for Mock Turtles +## A Case for Mock Turtles Let's look at an example. Suppose you are developing a graphics program that relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like @@ -106,7 +104,7 @@ the API in an interface (say, `Turtle`) and code to that interface: ```cpp class Turtle { ... - virtual ~Turtle() {}; + virtual ~Turtle() {} virtual void PenUp() = 0; virtual void PenDown() = 0; virtual void Forward(int distance) = 0; @@ -135,20 +133,20 @@ because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run *much, much faster*. -### Writing the Mock Class +## Writing the Mock Class If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - gMock turns this task into a fun game! (Well, almost.) -#### How to Define It +### How to Define It Using the `Turtle` interface as example, here are the simple steps you need to follow: * Derive a class `MockTurtle` from `Turtle`. * Take a *virtual* function of `Turtle` (while it's possible to - [mock non-virtual methods using templates](cook_book.md#MockingNonVirtualMethods), + [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods), it's much more involved). * In the `public:` section of the child class, write `MOCK_METHOD();` * Now comes the fun part: you take the function signature, cut-and-paste it @@ -184,7 +182,7 @@ class MockTurtle : public Turtle { You don't need to define these mock methods somewhere else - the `MOCK_METHOD` macro will generate the definitions for you. It's that simple! -#### Where to Put It +### Where to Put It When you define a mock class, you need to decide where to put its definition. Some people put it in a `_test.cc`. This is fine when the interface being mocked @@ -192,10 +190,10 @@ Some people put it in a `_test.cc`. This is fine when the interface being mocked `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, -define the mock class in `Foo`'s package (better, in a `testing` sub-package -such that you can clearly separate production code and testing utilities), put -it in a `.h` and a `cc_library`. Then everyone can reference them from their +Generally, you should not mock classes you don't own. If you must mock such a +class owned by others, define the mock class in `Foo`'s Bazel package (usually +the same directory or a `testing` sub-directory), and put it in a `.h` and a +`cc_library` with `testonly=True`. Then everyone can reference them from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. @@ -206,9 +204,7 @@ choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - - -### Using Mocks in Tests +## Using Mocks in Tests Once you have a mock class, using it is easy. The typical work flow is: @@ -257,8 +253,8 @@ Stack trace: ... ``` -**Tip 1:** If you run the test from an Emacs buffer, you can hit on the -line number to jump right to the failed expectation. +**Tip 1:** If you run the test from an Emacs buffer, you can hit `` on +the line number to jump right to the failed expectation. **Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to turn on the heap checker in your tests @@ -266,8 +262,9 @@ when you allocate mocks on the heap. You get that automatically if you use the `gtest_main` library already. **Important note:** gMock requires expectations to be set **before** the mock -functions are called, otherwise the behavior is **undefined**. In particular, -you mustn't interleave `EXPECT_CALL()s` and calls to the mock functions. +functions are called, otherwise the behavior is **undefined**. Do not alternate +between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set +any expectations on a mock after passing the mock to an API. This means `EXPECT_CALL()` should be read as expecting that a call will occur *in the future*, not that a call has occurred. Why does gMock work like that? @@ -279,7 +276,7 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using gMock. However, as we shall reveal soon, gMock allows you to do *so much more* with the mocks. -### Setting Expectations +## Setting Expectations The key to using a mock object successfully is to set the *right expectations* on it. If you set the expectations too strict, your test will fail as the result @@ -288,7 +285,7 @@ to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. gMock provides the necessary means for you to do it "just right." -#### General Syntax +### General Syntax In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: @@ -314,8 +311,8 @@ EXPECT_CALL(mock_object, non-overloaded-method) This syntax allows the test writer to specify "called with any arguments" without explicitly specifying the number or types of arguments. To avoid -unintended ambiguity, this syntax may only be used for methods which are not -overloaded +unintended ambiguity, this syntax may only be used for methods that are not +overloaded. Either form of the macro can be followed by some optional *clauses* that provide more information about the expectation. We'll discuss how each clause works in @@ -338,12 +335,13 @@ says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). +{: .callout .note} **Note:** Why do we use a macro to do this? Well it serves two purposes: first -it makes expectations easily identifiable (either by `gsearch` or by a human +it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows gMock to include the source file location of a failed expectation in messages, making debugging easier. -#### Matchers: What Arguments Do We Expect? +### Matchers: What Arguments Do We Expect? When a mock function takes arguments, we may specify what arguments we are expecting, for example: @@ -374,8 +372,8 @@ convenient way of saying "any value". In the above examples, `100` and `50` are also matchers; implicitly, they are the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be equal (using `operator==`) to the matcher argument. There are many -[built-in matchers](#MatcherList) for common types (as well as -[custom matchers](cook_book.md#NewMatchers)); for example: +[built-in matchers](reference/matchers.md) for common types (as well as +[custom matchers](gmock_cook_book.md#NewMatchers)); for example: ```cpp using ::testing::Ge; @@ -397,9 +395,9 @@ EXPECT_CALL(turtle, GoTo); This works for all non-overloaded methods; if a method is overloaded, you need to help gMock resolve which overload is expected by specifying the number of arguments and possibly also the -[types of the arguments](cook_book.md#SelectOverload). +[types of the arguments](gmock_cook_book.md#SelectOverload). -#### Cardinalities: How Many Times Will It Be Called? +### Cardinalities: How Many Times Will It Be Called? The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells *how many times* the call should @@ -414,7 +412,7 @@ called. We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see -[here](cheat_sheet.md#CardinalityList). +[here](gmock_cheat_sheet.md#CardinalityList). The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer the cardinality for you.** The rules are easy to remember: @@ -429,7 +427,7 @@ the cardinality for you.** The rules are easy to remember: **Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? -#### Actions: What Should It Do? +### Actions: What Should It Do? Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in @@ -482,8 +480,8 @@ the *default* action for the function every time (unless, of course, you have a `WillRepeatedly()`.). What can we do inside `WillOnce()` besides `Return()`? You can return a -reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among -[others](cook_book.md#using-actions). +reference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function, +among [others](gmock_cook_book.md#using-actions). **Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you @@ -503,7 +501,7 @@ always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the -[cook book](http://). +[cook book](gmock_cook_book.md). Time for another quiz! What do you think the following means? @@ -522,7 +520,7 @@ will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. -#### Using Multiple Expectations {#MultiExpectations} +### Using Multiple Expectations {#MultiExpectations} So far we've only shown examples where you have a single expectation. More realistically, you'll specify expectations on multiple mock methods which may be @@ -547,6 +545,7 @@ error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. +{: .callout .note} **Note:** Why does gMock search for a match in the *reverse* order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase @@ -555,15 +554,16 @@ body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. +{: .callout .tip} **Tip:** It is very common to start with a catch-all expectation for a method and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if overloaded). This makes any calls to the method expected. This is not necessary for methods that are not mentioned at all (these are "uninteresting"), but is useful for methods that have some expectations, but for which other calls are ok. See -[Understanding Uninteresting vs Unexpected Calls](cook_book.md#uninteresting-vs-unexpected). +[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected). -#### Ordered vs Unordered Calls {#OrderedCalls} +### Ordered vs Unordered Calls {#OrderedCalls} By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the @@ -598,9 +598,9 @@ order as written. If a call is made out-of-order, it will be an error. (What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! The -details can be found [here](cook_book.md#OrderedCalls).) +details can be found [here](gmock_cook_book.md#OrderedCalls).) -#### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations} +### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations} Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin *exactly twice* @@ -688,7 +688,7 @@ it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). -#### Uninteresting Calls +### Uninteresting Calls A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and @@ -697,4 +697,4 @@ For example, in some tests we may not care about how many times `GetX()` and In gMock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. This is called "naggy" behavior; to change, see -[The Nice, the Strict, and the Naggy](cook_book.md#NiceStrictNaggy). +[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy). diff --git a/thirdparty_builtin/googletest/docs/index.md b/thirdparty_builtin/googletest/docs/index.md new file mode 100644 index 000000000..b162c7401 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/index.md @@ -0,0 +1,22 @@ +# GoogleTest User's Guide + +## Welcome to GoogleTest! + +GoogleTest is Google's C++ testing and mocking framework. This user's guide has +the following contents: + +* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using + GoogleTest. Read this first if you are new to GoogleTest. +* [GoogleTest Advanced](advanced.md) - Read this when you've finished the + Primer and want to utilize GoogleTest to its full potential. +* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples. +* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here + first. +* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock + objects and use them in tests. +* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to + common mocking use cases. +* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for + matchers, actions, invariants, and more. +* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific + questions. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/pkgconfig.md b/thirdparty_builtin/googletest/docs/pkgconfig.md similarity index 77% rename from thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/pkgconfig.md rename to thirdparty_builtin/googletest/docs/pkgconfig.md index 117166cf6..18a2546a3 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/pkgconfig.md +++ b/thirdparty_builtin/googletest/docs/pkgconfig.md @@ -45,77 +45,6 @@ splitting the pkg-config `Cflags` variable into include dirs and macros for goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens to discard `-L` flags and `-pthread`. -### Autotools - -Finding GoogleTest in Autoconf and using it from Automake is also fairly easy: - -In your `configure.ac`: - -``` -AC_PREREQ([2.69]) -AC_INIT([my_gtest_pkgconfig], [0.0.1]) -AC_CONFIG_SRCDIR([samples/sample3_unittest.cc]) -AC_PROG_CXX - -PKG_CHECK_MODULES([GTEST], [gtest_main]) - -AM_INIT_AUTOMAKE([foreign subdir-objects]) -AC_CONFIG_FILES([Makefile]) -AC_OUTPUT -``` - -and in your `Makefile.am`: - -``` -check_PROGRAMS = testapp -TESTS = $(check_PROGRAMS) - -testapp_SOURCES = samples/sample3_unittest.cc -testapp_CXXFLAGS = $(GTEST_CFLAGS) -testapp_LDADD = $(GTEST_LIBS) -``` - -### Meson - -Meson natively uses pkgconfig to query dependencies: - -``` -project('my_gtest_pkgconfig', 'cpp', version : '0.0.1') - -gtest_dep = dependency('gtest_main') - -testapp = executable( - 'testapp', - files(['samples/sample3_unittest.cc']), - dependencies : gtest_dep, - install : false) - -test('first_and_only_test', testapp) -``` - -### Plain Makefiles - -Since `pkg-config` is a small Unix command-line utility, it can be used in -handwritten `Makefile`s too: - -```makefile -GTEST_CFLAGS = `pkg-config --cflags gtest_main` -GTEST_LIBS = `pkg-config --libs gtest_main` - -.PHONY: tests all - -tests: all - ./testapp - -all: testapp - -testapp: testapp.o - $(CXX) $(CXXFLAGS) $(LDFLAGS) $< -o $@ $(GTEST_LIBS) - -testapp.o: samples/sample3_unittest.cc - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ $(GTEST_CFLAGS) -``` - ### Help! pkg-config can't find GoogleTest! Let's say you have a `CMakeLists.txt` along the lines of the one in this @@ -176,7 +105,7 @@ includedir=/usr/include Name: gtest Description: GoogleTest (without main() function) -Version: 1.10.0 +Version: 1.11.0 URL: https://github.com/google/googletest Libs: -L${libdir} -lgtest -lpthread Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread @@ -216,4 +145,4 @@ $ pkg-config --libs gtest which contains the correct sysroot now. For a more comprehensive guide to also including `${CHOST}` in build system calls, see the excellent tutorial by Diego -Elio Pettenò: https://autotools.io/pkgconfig/cross-compiling.html +Elio Pettenò: diff --git a/thirdparty_builtin/googletest/docs/platforms.md b/thirdparty_builtin/googletest/docs/platforms.md new file mode 100644 index 000000000..eba6ef805 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/platforms.md @@ -0,0 +1,35 @@ +# Supported Platforms + +GoogleTest requires a codebase and compiler compliant with the C++11 standard or +newer. + +The GoogleTest code is officially supported on the following platforms. +Operating systems or tools not listed below are community-supported. For +community-supported platforms, patches that do not complicate the code may be +considered. + +If you notice any problems on your platform, please file an issue on the +[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues). +Pull requests containing fixes are welcome! + +### Operating systems + +* Linux +* macOS +* Windows + +### Compilers + +* gcc 5.0+ +* clang 5.0+ +* MSVC 2015+ + +**macOS users:** Xcode 9.3+ provides clang 5.0+. + +### Build systems + +* [Bazel](https://bazel.build/) +* [CMake](https://cmake.org/) + +Bazel is the build system used by the team internally and in tests. CMake is +supported on a best-effort basis and by the community. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/primer.md b/thirdparty_builtin/googletest/docs/primer.md similarity index 63% rename from thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/primer.md rename to thirdparty_builtin/googletest/docs/primer.md index f581d77a9..31d63160e 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/primer.md +++ b/thirdparty_builtin/googletest/docs/primer.md @@ -1,85 +1,84 @@ -# Googletest Primer +# GoogleTest Primer -## Introduction: Why googletest? +## Introduction: Why GoogleTest? -*googletest* helps you write better C++ tests. +*GoogleTest* helps you write better C++ tests. -googletest is a testing framework developed by the Testing Technology team with +GoogleTest is a testing framework developed by the Testing Technology team with Google's specific requirements and constraints in mind. Whether you work on -Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it +Linux, Windows, or a Mac, if you write C++ code, GoogleTest can help you. And it supports *any* kind of tests, not just unit tests. -So what makes a good test, and how does googletest fit in? We believe: +So what makes a good test, and how does GoogleTest fit in? We believe: 1. Tests should be *independent* and *repeatable*. It's a pain to debug a test - that succeeds or fails as a result of other tests. googletest isolates the + that succeeds or fails as a result of other tests. GoogleTest isolates the tests by running each of them on a different object. When a test fails, - googletest allows you to run it in isolation for quick debugging. + GoogleTest allows you to run it in isolation for quick debugging. 2. Tests should be well *organized* and reflect the structure of the tested - code. googletest groups related tests into test suites that can share data + code. GoogleTest groups related tests into test suites that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base. 3. Tests should be *portable* and *reusable*. Google has a lot of code that is - platform-neutral; its tests should also be platform-neutral. googletest + platform-neutral; its tests should also be platform-neutral. GoogleTest works on different OSes, with different compilers, with or without - exceptions, so googletest tests can work with a variety of configurations. + exceptions, so GoogleTest tests can work with a variety of configurations. 4. When tests fail, they should provide as much *information* about the problem - as possible. googletest doesn't stop at the first test failure. Instead, it + as possible. GoogleTest doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle. 5. The testing framework should liberate test writers from housekeeping chores - and let them focus on the test *content*. googletest automatically keeps + and let them focus on the test *content*. GoogleTest automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them. -6. Tests should be *fast*. With googletest, you can reuse shared resources +6. Tests should be *fast*. With GoogleTest, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other. -Since googletest is based on the popular xUnit architecture, you'll feel right +Since GoogleTest is based on the popular xUnit architecture, you'll feel right at home if you've used JUnit or PyUnit before. If not, it will take you about 10 minutes to learn the basics and get started. So let's go! ## Beware of the nomenclature -_Note:_ There might be some confusion arising from different definitions of the -terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these. +{: .callout .note} +*Note:* There might be some confusion arising from different definitions of the +terms *Test*, *Test Case* and *Test Suite*, so beware of misunderstanding these. -Historically, googletest started to use the term _Test Case_ for grouping +Historically, GoogleTest started to use the term *Test Case* for grouping related tests, whereas current publications, including International Software Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and various textbooks on software quality, use the term -_[Test Suite][istqb test suite]_ for this. +*[Test Suite][istqb test suite]* for this. -The related term _Test_, as it is used in googletest, corresponds to the term -_[Test Case][istqb test case]_ of ISTQB and others. +The related term *Test*, as it is used in GoogleTest, corresponds to the term +*[Test Case][istqb test case]* of ISTQB and others. -The term _Test_ is commonly of broad enough sense, including ISTQB's definition -of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as +The term *Test* is commonly of broad enough sense, including ISTQB's definition +of *Test Case*, so it's not much of a problem here. But the term *Test Case* as was used in Google Test is of contradictory sense and thus confusing. -googletest recently started replacing the term _Test Case_ with _Test Suite_. +GoogleTest recently started replacing the term *Test Case* with *Test Suite*. The preferred API is *TestSuite*. The older TestCase API is being slowly deprecated and refactored away. So please be aware of the different definitions of the terms: - -Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term +Meaning | GoogleTest Term | [ISTQB](http://www.istqb.org/) Term :----------------------------------------------------------------------------------- | :---------------------- | :---------------------------------- Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case] - [istqb test case]: http://glossary.istqb.org/en/search/test%20case [istqb test suite]: http://glossary.istqb.org/en/search/test%20suite ## Basic Concepts -When using googletest, you start by writing *assertions*, which are statements +When using GoogleTest, you start by writing *assertions*, which are statements that check whether a condition is true. An assertion's result can be *success*, *nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the current function; otherwise the program continues normally. @@ -99,11 +98,11 @@ assertion level and building up to tests and test suites. ## Assertions -googletest assertions are macros that resemble function calls. You test a class +GoogleTest assertions are macros that resemble function calls. You test a class or function by making assertions about its behavior. When an assertion fails, -googletest prints the assertion's source file and line number location, along +GoogleTest prints the assertion's source file and line number location, along with a failure message. You may also supply a custom failure message which will -be appended to googletest's message. +be appended to GoogleTest's message. The assertions come in pairs that test the same thing but have different effects on the current function. `ASSERT_*` versions generate fatal failures when they @@ -119,7 +118,9 @@ Depending on the nature of the leak, it may or may not be worth fixing - so keep this in mind if you get a heap checker error in addition to assertion errors. To provide a custom failure message, simply stream it into the macro using the -`<<` operator or a sequence of such operators. An example: +`<<` operator or a sequence of such operators. See the following example, using +the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to +verify value equality: ```c++ ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; @@ -134,112 +135,12 @@ macro--in particular, C strings and `string` objects. If a wide string (`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an assertion, it will be translated to UTF-8 when printed. -### Basic Assertions - -These assertions do basic true/false condition testing. - -Fatal assertion | Nonfatal assertion | Verifies --------------------------- | -------------------------- | -------------------- -`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true -`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false - -Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the -current function, while `EXPECT_*` yields a nonfatal failure, allowing the -function to continue running. In either case, an assertion failure means its -containing test fails. - -**Availability**: Linux, Windows, Mac. - -### Binary Comparison - -This section describes assertions that compare two values. - -Fatal assertion | Nonfatal assertion | Verifies ------------------------- | ------------------------ | -------------- -`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2` -`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2` -`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2` -`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2` -`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2` -`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2` - -Value arguments must be comparable by the assertion's comparison operator or -you'll get a compiler error. We used to require the arguments to support the -`<<` operator for streaming to an `ostream`, but this is no longer necessary. If -`<<` is supported, it will be called to print the arguments when the assertion -fails; otherwise googletest will attempt to print them in the best way it can. -For more details and how to customize the printing of the arguments, see the -[documentation](../../googlemock/docs/cook_book.md#teaching-gmock-how-to-print-your-values). - -These assertions can work with a user-defined type, but only if you define the -corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged -by the Google -[C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading), -you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of -two objects of a user-defined type. - -However, when possible, `ASSERT_EQ(actual, expected)` is preferred to -`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s -values on failure. - -Arguments are always evaluated exactly once. Therefore, it's OK for the -arguments to have side effects. However, as with any ordinary C/C++ function, -the arguments' evaluation order is undefined (i.e., the compiler is free to -choose any order), and your code should not depend on any particular argument -evaluation order. - -`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it -tests if they are in the same memory location, not if they have the same value. -Therefore, if you want to compare C strings (e.g. `const char*`) by value, use -`ASSERT_STREQ()`, which will be described later on. In particular, to assert -that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider using -`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string` -objects, you should use `ASSERT_EQ`. - -When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)` -instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is -typed, while `NULL` is not. See the [FAQ](faq.md) for more details. - -If you're working with floating point numbers, you may want to use the floating -point variations of some of these macros in order to avoid problems caused by -rounding. See [Advanced googletest Topics](advanced.md) for details. - -Macros in this section work with both narrow and wide string objects (`string` -and `wstring`). - -**Availability**: Linux, Windows, Mac. - -**Historical note**: Before February 2016 `*_EQ` had a convention of calling it -as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now -`*_EQ` treats both parameters in the same way. - -### String Comparison - -The assertions in this group compare two **C strings**. If you want to compare -two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. - - - -| Fatal assertion | Nonfatal assertion | Verifies | -| -------------------------- | ------------------------------ | -------------------------------------------------------- | -| `ASSERT_STREQ(str1,str2);` | `EXPECT_STREQ(str1,str2);` | the two C strings have the same content | -| `ASSERT_STRNE(str1,str2);` | `EXPECT_STRNE(str1,str2);` | the two C strings have different contents | -| `ASSERT_STRCASEEQ(str1,str2);` | `EXPECT_STRCASEEQ(str1,str2);` | the two C strings have the same content, ignoring case | -| `ASSERT_STRCASENE(str1,str2);` | `EXPECT_STRCASENE(str1,str2);` | the two C strings have different contents, ignoring case | - - - -Note that "CASE" in an assertion name means that case is ignored. A `NULL` -pointer and an empty string are considered *different*. - -`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison -of two wide strings fails, their values will be printed as UTF-8 narrow strings. - -**Availability**: Linux, Windows, Mac. - -**See also**: For more string comparison tricks (substring, prefix, suffix, and -regular expression matching, for example), see [this](advanced.md) in the -Advanced googletest Guide. +GoogleTest provides a collection of assertions for verifying the behavior of +your code in various ways. You can check Boolean conditions, compare values +based on relational operators, verify string values, floating-point values, and +much more. There are even assertions that enable you to verify more complex +states by providing custom predicates. For the complete list of assertions +provided by GoogleTest, see the [Assertions Reference](reference/assertions.md). ## Simple Tests @@ -248,7 +149,7 @@ To create a test: 1. Use the `TEST()` macro to define and name a test function. These are ordinary C++ functions that don't return a value. 2. In this function, along with any valid C++ statements you want to include, - use the various googletest assertions to check values. + use the various GoogleTest assertions to check values. 3. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds. @@ -261,9 +162,9 @@ TEST(TestSuiteName, TestName) { `TEST()` arguments go from general to specific. The *first* argument is the name of the test suite, and the *second* argument is the test's name within the test -suite. Both names must be valid C++ identifiers, and they should not contain -any underscores (`_`). A test's *full name* consists of its containing test suite and -its individual name. Tests from different test suites can have the same +suite. Both names must be valid C++ identifiers, and they should not contain any +underscores (`_`). A test's *full name* consists of its containing test suite +and its individual name. Tests from different test suites can have the same individual name. For example, let's take a simple integer function: @@ -289,7 +190,7 @@ TEST(FactorialTest, HandlesPositiveInput) { } ``` -googletest groups the test results by test suites, so logically related tests +GoogleTest groups the test results by test suites, so logically related tests should be in the same test suite; in other words, the first argument to their `TEST()` should be the same. In the above example, we have two tests, `HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test @@ -326,14 +227,14 @@ When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to access objects and subroutines in the test fixture: ```c++ -TEST_F(TestFixtureName, TestName) { +TEST_F(TestFixtureClassName, TestName) { ... test body ... } ``` -Like `TEST()`, the first argument is the test suite name, but for `TEST_F()` -this must be the name of the test fixture class. You've probably guessed: `_F` -is for fixture. +Unlike `TEST()`, in `TEST_F()` the first argument must be the name of the test +fixture class. (`_F` stands for "Fixture"). No test suite name is specified for +this macro. Unfortunately, the C++ macro system does not allow us to create a single macro that can handle both types of tests. Using the wrong macro causes a compiler @@ -343,12 +244,12 @@ Also, you must first define a test fixture class before using it in a `TEST_F()`, or you'll get the compiler error "`virtual outside class declaration`". -For each test defined with `TEST_F()`, googletest will create a *fresh* test -fixture at runtime, immediately initialize it via `SetUp()`, run the test, -clean up by calling `TearDown()`, and then delete the test fixture. Note that +For each test defined with `TEST_F()`, GoogleTest will create a *fresh* test +fixture at runtime, immediately initialize it via `SetUp()`, run the test, clean +up by calling `TearDown()`, and then delete the test fixture. Note that different tests in the same test suite have different test fixture objects, and -googletest always deletes a test fixture before it creates the next one. -googletest does **not** reuse the same test fixture for multiple tests. Any +GoogleTest always deletes a test fixture before it creates the next one. +GoogleTest does **not** reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests. As an example, let's write tests for a FIFO queue class named `Queue`, which has @@ -373,6 +274,7 @@ First, define a fixture class. By convention, you should give it the name class QueueTest : public ::testing::Test { protected: void SetUp() override { + // q0_ remains empty q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); @@ -418,12 +320,12 @@ The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is to use `EXPECT_*` when you want the test to continue to reveal more errors after the assertion failure, and use `ASSERT_*` when continuing after failure doesn't make sense. For example, the second assertion in the `Dequeue` test is -`ASSERT_NE(nullptr, n)`, as we need to dereference the pointer `n` later, which +`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which would lead to a segfault when `n` is `NULL`. When these tests run, the following happens: -1. googletest constructs a `QueueTest` object (let's call it `t1`). +1. GoogleTest constructs a `QueueTest` object (let's call it `t1`). 2. `t1.SetUp()` initializes `t1`. 3. The first test (`IsEmptyInitially`) runs on `t1`. 4. `t1.TearDown()` cleans up after the test finishes. @@ -435,18 +337,18 @@ When these tests run, the following happens: ## Invoking the Tests -`TEST()` and `TEST_F()` implicitly register their tests with googletest. So, +`TEST()` and `TEST_F()` implicitly register their tests with GoogleTest. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them. After defining your tests, you can run them with `RUN_ALL_TESTS()`, which returns `0` if all the tests are successful, or `1` otherwise. Note that -`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from -different test suites, or even different source files. +`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different +test suites, or even different source files. When invoked, the `RUN_ALL_TESTS()` macro: -* Saves the state of all googletest flags. +* Saves the state of all GoogleTest flags. * Creates a test fixture object for the first test. @@ -458,12 +360,13 @@ When invoked, the `RUN_ALL_TESTS()` macro: * Deletes the fixture. -* Restores the state of all googletest flags. +* Restores the state of all GoogleTest flags. * Repeats the above steps for the next test, until all tests have run. If a fatal failure happens the subsequent steps will be skipped. +{: .callout .important} > IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or > you will get a compiler error. The rationale for this design is that the > automated testing service determines whether a test has passed based on its @@ -471,14 +374,14 @@ If a fatal failure happens the subsequent steps will be skipped. > return the value of `RUN_ALL_TESTS()`. > > Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than -> once conflicts with some advanced googletest features (e.g., thread-safe +> once conflicts with some advanced GoogleTest features (e.g., thread-safe > [death tests](advanced.md#death-tests)) and thus is not supported. **Availability**: Linux, Windows, Mac. ## Writing the main() Function -Most users should _not_ need to write their own `main` function and instead link +Most users should *not* need to write their own `main` function and instead link with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry point. See the end of this section for details. The remainder of this section should only apply when you need to do something custom before the tests run that @@ -553,9 +456,9 @@ int main(int argc, char **argv) { ``` The `::testing::InitGoogleTest()` function parses the command line for -googletest flags, and removes all recognized flags. This allows the user to -control a test program's behavior via various flags, which we'll cover in -the [AdvancedGuide](advanced.md). You **must** call this function before calling +GoogleTest flags, and removes all recognized flags. This allows the user to +control a test program's behavior via various flags, which we'll cover in the +[AdvancedGuide](advanced.md). You **must** call this function before calling `RUN_ALL_TESTS()`, or the flags won't be properly initialized. On Windows, `InitGoogleTest()` also works with wide strings, so it can be used @@ -566,13 +469,14 @@ agree with you completely, and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with the `gtest_main` library and you are good to go. +{: .callout .note} NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. ## Known Limitations * Google Test is designed to be thread-safe. The implementation is thread-safe on systems where the `pthreads` library is available. It is currently - _unsafe_ to use Google Test assertions from two threads concurrently on + *unsafe* to use Google Test assertions from two threads concurrently on other systems (e.g. Windows). In most tests this is not an issue as usually the assertions are done in the main thread. If you want to help, you can volunteer to implement the necessary synchronization primitives in diff --git a/thirdparty_builtin/googletest/docs/quickstart-bazel.md b/thirdparty_builtin/googletest/docs/quickstart-bazel.md new file mode 100644 index 000000000..15c27a22e --- /dev/null +++ b/thirdparty_builtin/googletest/docs/quickstart-bazel.md @@ -0,0 +1,146 @@ +# Quickstart: Building with Bazel + +This tutorial aims to get you up and running with GoogleTest using the Bazel +build system. If you're using GoogleTest for the first time or need a refresher, +we recommend this tutorial as a starting point. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [Bazel](https://bazel.build/), the preferred build system used by the + GoogleTest team. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have Bazel installed, see the +[Bazel installation guide](https://bazel.build/install). + +{: .callout .note} Note: The terminal commands in this tutorial show a Unix +shell prompt, but the commands work on the Windows command line as well. + +## Set up a Bazel workspace + +A +[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace) +is a directory on your filesystem that you use to manage source files for the +software you want to build. Each workspace directory has a text file named +`WORKSPACE` which may be empty, or may contain references to external +dependencies required to build the outputs. + +First, create a directory for your workspace: + +``` +$ mkdir my_workspace && cd my_workspace +``` + +Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and +recommended way to depend on GoogleTest is to use a +[Bazel external dependency](https://docs.bazel.build/versions/main/external.html) +via the +[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive). +To do this, in the root directory of your workspace (`my_workspace/`), create a +file named `WORKSPACE` with the following contents: + +``` +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + +http_archive( + name = "com_google_googletest", + urls = ["https://github.com/google/googletest/archive/5ab508a01f9eb089207ee87fd547d290da39d015.zip"], + strip_prefix = "googletest-5ab508a01f9eb089207ee87fd547d290da39d015", +) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +as a ZIP archive from GitHub. In the above example, +`5ab508a01f9eb089207ee87fd547d290da39d015` is the Git commit hash of the +GoogleTest version to use; we recommend updating the hash often to point to the +latest version. Use a recent hash on the `main` branch. + +Now you're ready to build C++ code that uses GoogleTest. + +## Create and run a binary + +With your Bazel workspace set up, you can now use GoogleTest code within your +own project. + +As an example, create a file named `hello_test.cc` in your `my_workspace` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, create a file named `BUILD` in the same directory with the +following contents: + +``` +cc_test( + name = "hello_test", + size = "small", + srcs = ["hello_test.cc"], + deps = ["@com_google_googletest//:gtest_main"], +) +``` + +This `cc_test` rule declares the C++ test binary you want to build, and links to +GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE` +file (`@com_google_googletest`). For more information about Bazel `BUILD` files, +see the +[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html). + +Now you can build and run your test: + +
+my_workspace$ bazel test --test_output=all //:hello_test
+INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
+INFO: Found 1 test target...
+INFO: From Testing //:hello_test:
+==================== Test output for //:hello_test:
+Running main() from gmock_main.cc
+[==========] Running 1 test from 1 test suite.
+[----------] Global test environment set-up.
+[----------] 1 test from HelloTest
+[ RUN      ] HelloTest.BasicAssertions
+[       OK ] HelloTest.BasicAssertions (0 ms)
+[----------] 1 test from HelloTest (0 ms total)
+
+[----------] Global test environment tear-down
+[==========] 1 test from 1 test suite ran. (0 ms total)
+[  PASSED  ] 1 test.
+================================================================================
+Target //:hello_test up-to-date:
+  bazel-bin/hello_test
+INFO: Elapsed time: 4.190s, Critical Path: 3.05s
+INFO: 27 processes: 8 internal, 19 linux-sandbox.
+INFO: Build completed successfully, 27 total actions
+//:hello_test                                                     PASSED in 0.1s
+
+INFO: Build completed successfully, 27 total actions
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/thirdparty_builtin/googletest/docs/quickstart-cmake.md b/thirdparty_builtin/googletest/docs/quickstart-cmake.md new file mode 100644 index 000000000..5abe50441 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/quickstart-cmake.md @@ -0,0 +1,156 @@ +# Quickstart: Building with CMake + +This tutorial aims to get you up and running with GoogleTest using CMake. If +you're using GoogleTest for the first time or need a refresher, we recommend +this tutorial as a starting point. If your project uses Bazel, see the +[Quickstart for Bazel](quickstart-bazel.md) instead. + +## Prerequisites + +To complete this tutorial, you'll need: + +* A compatible operating system (e.g. Linux, macOS, Windows). +* A compatible C++ compiler that supports at least C++14. +* [CMake](https://cmake.org/) and a compatible build tool for building the + project. + * Compatible build tools include + [Make](https://www.gnu.org/software/make/), + [Ninja](https://ninja-build.org/), and others - see + [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html) + for more information. + +See [Supported Platforms](platforms.md) for more information about platforms +compatible with GoogleTest. + +If you don't already have CMake installed, see the +[CMake installation guide](https://cmake.org/install). + +{: .callout .note} +Note: The terminal commands in this tutorial show a Unix shell prompt, but the +commands work on the Windows command line as well. + +## Set up a project + +CMake uses a file named `CMakeLists.txt` to configure the build system for a +project. You'll use this file to set up your project and declare a dependency on +GoogleTest. + +First, create a directory for your project: + +``` +$ mkdir my_project && cd my_project +``` + +Next, you'll create the `CMakeLists.txt` file and declare a dependency on +GoogleTest. There are many ways to express dependencies in the CMake ecosystem; +in this quickstart, you'll use the +[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html). +To do this, in your project directory (`my_project`), create a file named +`CMakeLists.txt` with the following contents: + +```cmake +cmake_minimum_required(VERSION 3.14) +project(my_project) + +# GoogleTest requires at least C++14 +set(CMAKE_CXX_STANDARD 14) + +include(FetchContent) +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) +``` + +The above configuration declares a dependency on GoogleTest which is downloaded +from GitHub. In the above example, `03597a01ee50ed33e9dfd640b249b4be3799d395` is +the Git commit hash of the GoogleTest version to use; we recommend updating the +hash often to point to the latest version. + +For more information about how to create `CMakeLists.txt` files, see the +[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html). + +## Create and run a binary + +With GoogleTest declared as a dependency, you can use GoogleTest code within +your own project. + +As an example, create a file named `hello_test.cc` in your `my_project` +directory with the following contents: + +```cpp +#include + +// Demonstrate some basic assertions. +TEST(HelloTest, BasicAssertions) { + // Expect two strings not to be equal. + EXPECT_STRNE("hello", "world"); + // Expect equality. + EXPECT_EQ(7 * 6, 42); +} +``` + +GoogleTest provides [assertions](primer.md#assertions) that you use to test the +behavior of your code. The above sample includes the main GoogleTest header file +and demonstrates some basic assertions. + +To build the code, add the following to the end of your `CMakeLists.txt` file: + +```cmake +enable_testing() + +add_executable( + hello_test + hello_test.cc +) +target_link_libraries( + hello_test + GTest::gtest_main +) + +include(GoogleTest) +gtest_discover_tests(hello_test) +``` + +The above configuration enables testing in CMake, declares the C++ test binary +you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The +last two lines enable CMake's test runner to discover the tests included in the +binary, using the +[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html). + +Now you can build and run your test: + +
+my_project$ cmake -S . -B build
+-- The C compiler identification is GNU 10.2.1
+-- The CXX compiler identification is GNU 10.2.1
+...
+-- Build files have been written to: .../my_project/build
+
+my_project$ cmake --build build
+Scanning dependencies of target gtest
+...
+[100%] Built target gmock_main
+
+my_project$ cd build && ctest
+Test project .../my_project/build
+    Start 1: HelloTest.BasicAssertions
+1/1 Test #1: HelloTest.BasicAssertions ........   Passed    0.00 sec
+
+100% tests passed, 0 tests failed out of 1
+
+Total Test time (real) =   0.01 sec
+
+ +Congratulations! You've successfully built and run a test binary using +GoogleTest. + +## Next steps + +* [Check out the Primer](primer.md) to start learning how to write simple + tests. +* [See the code samples](samples.md) for more examples showing how to use a + variety of GoogleTest features. diff --git a/thirdparty_builtin/googletest/docs/reference/actions.md b/thirdparty_builtin/googletest/docs/reference/actions.md new file mode 100644 index 000000000..ab81a129e --- /dev/null +++ b/thirdparty_builtin/googletest/docs/reference/actions.md @@ -0,0 +1,115 @@ +# Actions Reference + +[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a +mock function should do when invoked. This page lists the built-in actions +provided by GoogleTest. All actions are defined in the `::testing` namespace. + +## Returning a Value + +| Action | Description | +| :-------------------------------- | :-------------------------------------------- | +| `Return()` | Return from a `void` mock function. | +| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed. | +| `ReturnArg()` | Return the `N`-th (0-based) argument. | +| `ReturnNew(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | +| `ReturnNull()` | Return a null pointer. | +| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | +| `ReturnRef(variable)` | Return a reference to `variable`. | +| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | +| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | + +## Side Effects + +| Action | Description | +| :--------------------------------- | :-------------------------------------- | +| `Assign(&variable, value)` | Assign `value` to variable. | +| `DeleteArg()` | Delete the `N`-th (0-based) argument, which must be a pointer. | +| `SaveArg(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | +| `SaveArgPointee(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | +| `SetArgReferee(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. | +| `SetArgPointee(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | +| `SetArgumentPointee(value)` | Same as `SetArgPointee(value)`. Deprecated. Will be removed in v1.7.0. | +| `SetArrayArgument(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. | +| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | +| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | + +## Using a Function, Functor, or Lambda as an Action + +In the following, by "callable" we mean a free function, `std::function`, +functor, or lambda. + +| Action | Description | +| :---------------------------------- | :------------------------------------- | +| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. | +| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | +| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | +| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | +| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | +| `InvokeArgument(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. | + +The return value of the invoked function is used as the return value of the +action. + +When defining a callable to be used with `Invoke*()`, you can declare any unused +parameters as `Unused`: + +```cpp +using ::testing::Invoke; +double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } +... +EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); +``` + +`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of +`callback`, which must be permanent. The type of `callback` must be a base +callback type instead of a derived one, e.g. + +```cpp + BlockingClosure* done = new BlockingClosure; + ... Invoke(done) ...; // This won't compile! + + Closure* done2 = new BlockingClosure; + ... Invoke(done2) ...; // This works. +``` + +In `InvokeArgument(...)`, if an argument needs to be passed by reference, +wrap it inside `std::ref()`. For example, + +```cpp +using ::testing::InvokeArgument; +... +InvokeArgument<2>(5, string("Hi"), std::ref(foo)) +``` + +calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by +value, and `foo` by reference. + +## Default Action + +| Action | Description | +| :------------ | :----------------------------------------------------- | +| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | + +{: .callout .note} +**Note:** due to technical reasons, `DoDefault()` cannot be used inside a +composite action - trying to do so will result in a run-time error. + +## Composite Actions + +| Action | Description | +| :----------------------------- | :------------------------------------------ | +| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. | +| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | +| `WithArg(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | +| `WithArgs(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | +| `WithoutArgs(a)` | Perform action `a` without any arguments. | + +## Defining Actions + +| Macro | Description | +| :--------------------------------- | :-------------------------------------- | +| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | +| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | +| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | + +The `ACTION*` macros cannot be used inside a function or class. diff --git a/thirdparty_builtin/googletest/docs/reference/assertions.md b/thirdparty_builtin/googletest/docs/reference/assertions.md new file mode 100644 index 000000000..1cdff266e --- /dev/null +++ b/thirdparty_builtin/googletest/docs/reference/assertions.md @@ -0,0 +1,633 @@ +# Assertions Reference + +This page lists the assertion macros provided by GoogleTest for verifying code +behavior. To use them, include the header `gtest/gtest.h`. + +The majority of the macros listed below come as a pair with an `EXPECT_` variant +and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal +failures and allow the current function to continue running, while `ASSERT_` +macros generate fatal failures and abort the current function. + +All assertion macros support streaming a custom failure message into them with +the `<<` operator, for example: + +```cpp +EXPECT_TRUE(my_condition) << "My condition is not true"; +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro—in particular, C strings and string objects. If a wide string (`wchar_t*`, +`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an +assertion, it will be translated to UTF-8 when printed. + +## Explicit Success and Failure {#success-failure} + +The assertions in this section generate a success or failure directly instead of +testing a value or expression. These are useful when control flow, rather than a +Boolean expression, determines the test's success or failure, as shown by the +following example: + +```c++ +switch(expression) { + case 1: + ... some checks ... + case 2: + ... some other checks ... + default: + FAIL() << "We shouldn't get here."; +} +``` + +### SUCCEED {#SUCCEED} + +`SUCCEED()` + +Generates a success. This *does not* make the overall test succeed. A test is +considered successful only if none of its assertions fail during its execution. + +The `SUCCEED` assertion is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED` messages to GoogleTest output +in the future. + +### FAIL {#FAIL} + +`FAIL()` + +Generates a fatal failure, which returns from the current function. + +Can only be used in functions that return `void`. See +[Assertion Placement](../advanced.md#assertion-placement) for more information. + +### ADD_FAILURE {#ADD_FAILURE} + +`ADD_FAILURE()` + +Generates a nonfatal failure, which allows the current function to continue +running. + +### ADD_FAILURE_AT {#ADD_FAILURE_AT} + +`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)` + +Generates a nonfatal failure at the file and line number specified. + +## Generalized Assertion {#generalized} + +The following assertion allows [matchers](matchers.md) to be used to verify +values. + +### EXPECT_THAT {#EXPECT_THAT} + +`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \ +`ASSERT_THAT(`*`value`*`,`*`matcher`*`)` + +Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*. + +For example, the following code verifies that the string `value1` starts with +`"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and +10: + +```cpp +#include "gmock/gmock.h" + +using ::testing::AllOf; +using ::testing::Gt; +using ::testing::Lt; +using ::testing::MatchesRegex; +using ::testing::StartsWith; + +... +EXPECT_THAT(value1, StartsWith("Hello")); +EXPECT_THAT(value2, MatchesRegex("Line \\d+")); +ASSERT_THAT(value3, AllOf(Gt(5), Lt(10))); +``` + +Matchers enable assertions of this form to read like English and generate +informative failure messages. For example, if the above assertion on `value1` +fails, the resulting message will be similar to the following: + +``` +Value of: value1 + Actual: "Hi, world!" +Expected: starts with "Hello" +``` + +GoogleTest provides a built-in library of matchers—see the +[Matchers Reference](matchers.md). It is also possible to write your own +matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers). +The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion. + +*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project, +which adds `assertThat()` to JUnit.* + +## Boolean Conditions {#boolean} + +The following assertions test Boolean conditions. + +### EXPECT_TRUE {#EXPECT_TRUE} + +`EXPECT_TRUE(`*`condition`*`)` \ +`ASSERT_TRUE(`*`condition`*`)` + +Verifies that *`condition`* is true. + +### EXPECT_FALSE {#EXPECT_FALSE} + +`EXPECT_FALSE(`*`condition`*`)` \ +`ASSERT_FALSE(`*`condition`*`)` + +Verifies that *`condition`* is false. + +## Binary Comparison {#binary-comparison} + +The following assertions compare two values. The value arguments must be +comparable by the assertion's comparison operator, otherwise a compiler error +will result. + +If an argument supports the `<<` operator, it will be called to print the +argument when the assertion fails. Otherwise, GoogleTest will attempt to print +them in the best way it can—see +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values). + +Arguments are always evaluated exactly once, so it's OK for the arguments to +have side effects. However, the argument evaluation order is undefined and +programs should not depend on any particular argument evaluation order. + +These assertions work with both narrow and wide string objects (`string` and +`wstring`). + +See also the [Floating-Point Comparison](#floating-point) assertions to compare +floating-point numbers and avoid problems caused by rounding. + +### EXPECT_EQ {#EXPECT_EQ} + +`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`==`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in the same memory location, not if they have the same value. Use +[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead +of `EXPECT_EQ(`*`ptr`*`, NULL)`. + +### EXPECT_NE {#EXPECT_NE} + +`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_NE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`!=`*`val2`*. + +Does pointer equality on pointers. If used on two C strings, it tests if they +are in different memory locations, not if they have different values. Use +[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by +value. + +When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead +of `EXPECT_NE(`*`ptr`*`, NULL)`. + +### EXPECT_LT {#EXPECT_LT} + +`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<`*`val2`*. + +### EXPECT_LE {#EXPECT_LE} + +`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_LE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`<=`*`val2`*. + +### EXPECT_GT {#EXPECT_GT} + +`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GT(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>`*`val2`*. + +### EXPECT_GE {#EXPECT_GE} + +`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_GE(`*`val1`*`,`*`val2`*`)` + +Verifies that *`val1`*`>=`*`val2`*. + +## String Comparison {#c-strings} + +The following assertions compare two **C strings**. To compare two `string` +objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead. + +These assertions also accept wide C strings (`wchar_t*`). If a comparison of two +wide strings fails, their values will be printed as UTF-8 narrow strings. + +To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or +`EXPECT_NE(`*`c_string`*`, nullptr)`. + +### EXPECT_STREQ {#EXPECT_STREQ} + +`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents. + +### EXPECT_STRNE {#EXPECT_STRNE} + +`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents. + +### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ} + +`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have the same contents, +ignoring case. + +### EXPECT_STRCASENE {#EXPECT_STRCASENE} + +`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \ +`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)` + +Verifies that the two C strings *`str1`* and *`str2`* have different contents, +ignoring case. + +## Floating-Point Comparison {#floating-point} + +The following assertions compare two floating-point values. + +Due to rounding errors, it is very unlikely that two floating-point values will +match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point +comparison to make sense, the user needs to carefully choose the error bound. + +GoogleTest also provides assertions that use a default error bound based on +Units in the Last Place (ULPs). To learn more about ULPs, see the article +[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ} + +`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `float` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ} + +`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \ +`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` + +Verifies that the two `double` values *`val1`* and *`val2`* are approximately +equal, to within 4 ULPs from each other. + +### EXPECT_NEAR {#EXPECT_NEAR} + +`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \ +`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` + +Verifies that the difference between *`val1`* and *`val2`* does not exceed the +absolute error bound *`abs_error`*. + +## Exception Assertions {#exceptions} + +The following assertions verify that a piece of code throws, or does not throw, +an exception. Usage requires exceptions to be enabled in the build environment. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_NO_THROW({ + int n = 5; + DoSomething(&n); +}); +``` + +### EXPECT_THROW {#EXPECT_THROW} + +`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \ +`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)` + +Verifies that *`statement`* throws an exception of type *`exception_type`*. + +### EXPECT_ANY_THROW {#EXPECT_ANY_THROW} + +`EXPECT_ANY_THROW(`*`statement`*`)` \ +`ASSERT_ANY_THROW(`*`statement`*`)` + +Verifies that *`statement`* throws an exception of any type. + +### EXPECT_NO_THROW {#EXPECT_NO_THROW} + +`EXPECT_NO_THROW(`*`statement`*`)` \ +`ASSERT_NO_THROW(`*`statement`*`)` + +Verifies that *`statement`* does not throw any exception. + +## Predicate Assertions {#predicates} + +The following assertions enable more complex predicates to be verified while +printing a more clear failure message than if `EXPECT_TRUE` were used alone. + +### EXPECT_PRED* {#EXPECT_PRED} + +`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \ +`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \ +`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred`* returns `true` when passed the given values +as arguments. + +The parameter *`pred`* is a function or functor that accepts as many arguments +as the corresponding macro accepts values. If *`pred`* returns `true` for the +given arguments, the assertion succeeds, otherwise the assertion fails. + +When the assertion fails, it prints the value of each argument. Arguments are +always evaluated exactly once. + +As an example, see the following code: + +```cpp +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds +EXPECT_PRED2(MutuallyPrime, b, c); // Fails +``` + +In the above example, the first assertion succeeds, and the second fails with +the following message: + +``` +MutuallyPrime(b, c) is false, where +b is 4 +c is 10 +``` + +Note that if the given predicate is an overloaded function or a function +template, the assertion macro might not be able to determine which version to +use, and it might be necessary to explicitly specify the type of the function. +For example, for a Boolean function `IsPositive()` overloaded to take either a +single `int` or `double` argument, it would be necessary to write one of the +following: + +```cpp +EXPECT_PRED1(static_cast(IsPositive), 5); +EXPECT_PRED1(static_cast(IsPositive), 3.14); +``` + +Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error. +Similarly, to use a template function, specify the template arguments: + +```cpp +template +bool IsNegative(T x) { + return x < 0; +} +... +EXPECT_PRED1(IsNegative, -5); // Must specify type for IsNegative +``` + +If a template has multiple parameters, wrap the predicate in parentheses so the +macro arguments are parsed correctly: + +```cpp +ASSERT_PRED2((MyPredicate), 5, 0); +``` + +### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT} + +`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \ +`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \ +`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \ +`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` +\ +`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)` + +Verifies that the predicate *`pred_formatter`* succeeds when passed the given +values as arguments. + +The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function +or functor with the signature: + +```cpp +testing::AssertionResult PredicateFormatter(const char* expr1, + const char* expr2, + ... + const char* exprn, + T1 val1, + T2 val2, + ... + Tn valn); +``` + +where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate +arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding +expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn` +can be either value types or reference types; if an argument has type `T`, it +can be declared as either `T` or `const T&`, whichever is appropriate. For more +about the return type `testing::AssertionResult`, see +[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult). + +As an example, see the following code: + +```cpp +// Returns the smallest prime common divisor of m and n, +// or 1 when m and n are mutually prime. +int SmallestPrimeCommonDivisor(int m, int n) { ... } + +// Returns true if m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } + +// A predicate-formatter for asserting that two integers are mutually prime. +testing::AssertionResult AssertMutuallyPrime(const char* m_expr, + const char* n_expr, + int m, + int n) { + if (MutuallyPrime(m, n)) return testing::AssertionSuccess(); + + return testing::AssertionFailure() << m_expr << " and " << n_expr + << " (" << m << " and " << n << ") are not mutually prime, " + << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); +} + +... +const int a = 3; +const int b = 4; +const int c = 10; +... +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails +``` + +In the above example, the final assertion fails and the predicate-formatter +produces the following failure message: + +``` +b and c (4 and 10) are not mutually prime, as they have a common divisor 2 +``` + +## Windows HRESULT Assertions {#HRESULT} + +The following assertions test for `HRESULT` success or failure. For example: + +```cpp +CComPtr shell; +ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); +CComVariant empty; +ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); +``` + +The generated output contains the human-readable error message associated with +the returned `HRESULT` code. + +### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED} + +`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \ +`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)` + +Verifies that *`expression`* is a success `HRESULT`. + +### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED} + +`EXPECT_HRESULT_FAILED(`*`expression`*`)` \ +`ASSERT_HRESULT_FAILED(`*`expression`*`)` + +Verifies that *`expression`* is a failure `HRESULT`. + +## Death Assertions {#death} + +The following assertions verify that a piece of code causes the process to +terminate. For context, see [Death Tests](../advanced.md#death-tests). + +These assertions spawn a new process and execute the code under test in that +process. How that happens depends on the platform and the variable +`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the +command-line flag `--gtest_death_test_style`. + +* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the + child, after which: + * If the variable's value is `"fast"`, the death test statement is + immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes + the unit test binary just as it was originally invoked, but with some + extra flags to cause just the single death test under consideration to + be run. +* On Windows, the child is spawned using the `CreateProcess()` API, and + re-executes the binary to cause just the single death test under + consideration to be run - much like the `"threadsafe"` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to fail. +Currently, the flag's default value is +**`"fast"`**. + +If the death test statement runs to completion without dying, the child process +will nonetheless terminate, and the assertion fails. + +Note that the piece of code under test can be a compound statement, for example: + +```cpp +EXPECT_DEATH({ + int n = 5; + DoSomething(&n); +}, "Error on line .* of DoSomething()"); +``` + +### EXPECT_DEATH {#EXPECT_DEATH} + +`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with a nonzero exit +status and produces `stderr` output that matches *`matcher`*. + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `DoSomething(42)` causes +the process to die with an error message that contains the text `My error`: + +```cpp +EXPECT_DEATH(DoSomething(42), "My error"); +``` + +### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED} + +`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` + +If death tests are supported, behaves the same as +[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing. + +### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH} + +`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \ +`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` + +In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in +debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*. + +### EXPECT_EXIT {#EXPECT_EXIT} + +`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \ +`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` + +Verifies that *`statement`* causes the process to terminate with an exit status +that satisfies *`predicate`*, and produces `stderr` output that matches +*`matcher`*. + +The parameter *`predicate`* is a function or functor that accepts an `int` exit +status and returns a `bool`. GoogleTest provides two predicates to handle common +cases: + +```cpp +// Returns true if the program exited normally with the given exit status code. +::testing::ExitedWithCode(exit_code); + +// Returns true if the program was killed by the given signal. +// Not available on Windows. +::testing::KilledBySignal(signal_number); +``` + +The parameter *`matcher`* is either a [matcher](matchers.md) for a `const +std::string&`, or a regular expression (see +[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare +string *`s`* (with no matcher) is treated as +[`ContainsRegex(s)`](matchers.md#string-matchers), **not** +[`Eq(s)`](matchers.md#generic-comparison). + +For example, the following code verifies that calling `NormalExit()` causes the +process to print a message containing the text `Success` to `stderr` and exit +with exit status code 0: + +```cpp +EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success"); +``` diff --git a/thirdparty_builtin/googletest/docs/reference/matchers.md b/thirdparty_builtin/googletest/docs/reference/matchers.md new file mode 100644 index 000000000..243e3f951 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/reference/matchers.md @@ -0,0 +1,302 @@ +# Matchers Reference + +A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or +`EXPECT_CALL()`, or use it to validate a value directly using two macros: + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | +| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | + +{: .callout .warning} +**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)` +is supported, however note that implicit conversions can cause surprising +results. For example, `EXPECT_THAT(some_bool, "some string")` will compile and +may pass unintentionally. + +**BEST PRACTICE:** Prefer to make the comparison explicit via +`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, +expected_value)`. + +Built-in matchers (where `argument` is the function argument, e.g. +`actual_value` in the example above, or when used in the context of +`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are +divided into several categories. All matchers are defined in the `::testing` +namespace unless otherwise noted. + +## Wildcard + +Matcher | Description +:-------------------------- | :----------------------------------------------- +`_` | `argument` can be any value of the correct type. +`A()` or `An()` | `argument` can be any value of type `type`. + +## Generic Comparison + +| Matcher | Description | +| :--------------------- | :-------------------------------------------------- | +| `Eq(value)` or `value` | `argument == value` | +| `Ge(value)` | `argument >= value` | +| `Gt(value)` | `argument > value` | +| `Le(value)` | `argument <= value` | +| `Lt(value)` | `argument < value` | +| `Ne(value)` | `argument != value` | +| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | +| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | +| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | +| `NotNull()` | `argument` is a non-null pointer (raw or smart). | +| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| +| `VariantWith(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | +| `Ref(variable)` | `argument` is a reference to `variable`. | +| `TypedEq(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | + +Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or +destructed later. If the compiler complains that `value` doesn't have a public +copy constructor, try wrap it in `std::ref()`, e.g. +`Eq(std::ref(non_copyable_value))`. If you do that, make sure +`non_copyable_value` is not changed afterwards, or the meaning of your matcher +will be changed. + +`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types +that can be explicitly converted to Boolean, but are not implicitly converted to +Boolean. In other cases, you can use the basic +[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions. + +## Floating-Point Matchers {#FpMatchers} + +| Matcher | Description | +| :------------------------------- | :--------------------------------- | +| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | +| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | +| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | +| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | +| `IsNan()` | `argument` is any floating-point type with a NaN value. | + +The above matchers use ULP-based comparison (the same as used in googletest). +They automatically pick a reasonable error bound based on the absolute value of +the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard, +which requires comparing two NaNs for equality to return false. The +`NanSensitive*` version instead treats two NaNs as equal, which is often what a +user wants. + +| Matcher | Description | +| :------------------------------------------------ | :----------------------- | +| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | +| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | +| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | + +## String Matchers + +The `argument` can be either a C string or a C++ string object: + +| Matcher | Description | +| :---------------------- | :------------------------------------------------- | +| `ContainsRegex(string)` | `argument` matches the given regular expression. | +| `EndsWith(suffix)` | `argument` ends with string `suffix`. | +| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | +| `IsEmpty()` | `argument` is an empty string. | +| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. | +| `StartsWith(prefix)` | `argument` starts with string `prefix`. | +| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | +| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | +| `StrEq(string)` | `argument` is equal to `string`. | +| `StrNe(string)` | `argument` is not equal to `string`. | +| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. The web-safe format from [RFC 4648](https://www.rfc-editor.org/rfc/rfc4648#section-5) is supported. | + +`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They +use the regular expression syntax defined +[here](../advanced.md#regular-expression-syntax). All of these matchers, except +`ContainsRegex()` and `MatchesRegex()` work for wide strings as well. + +## Container Matchers + +Most STL-style containers support `==`, so you can use `Eq(expected_container)` +or simply `expected_container` to match a container exactly. If you want to +write the elements in-line, match them more flexibly, or get more informative +messages, you can use: + +| Matcher | Description | +| :---------------------------------------- | :------------------------------- | +| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | +| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | +| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | +| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. | +| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | +| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | +| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | +| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | +| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | +| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | +| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | +| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | +| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. | +| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. | +| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | + +**Notes:** + +* These matchers can also match: + 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), + and + 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, + int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). +* The array being matched may be multi-dimensional (i.e. its elements can be + arrays). +* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a + matcher for `::std::tuple` where `T` and `U` are the element type of + the actual container and the expected container, respectively. For example, + to compare two `Foo` containers where `Foo` doesn't support `operator==`, + one might write: + + ```cpp + MATCHER(FooEq, "") { + return std::get<0>(arg).Equals(std::get<1>(arg)); + } + ... + EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); + ``` + +## Member Matchers + +| Matcher | Description | +| :------------------------------ | :----------------------------------------- | +| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | +| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. | +| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. | +| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | +| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size`+`get(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. | +| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. | +| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message. + +**Notes:** + +* You can use `FieldsAre()` to match any type that supports structured + bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate + types. For example: + + ```cpp + std::tuple my_tuple{7, "hello world"}; + EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello"))); + + struct MyStruct { + int value = 42; + std::string greeting = "aloha"; + }; + MyStruct s; + EXPECT_THAT(s, FieldsAre(42, "aloha")); + ``` + +* Don't use `Property()` against member functions that you do not own, because + taking addresses of functions is fragile and generally not part of the + contract of the function. + +## Matching the Result of a Function, Functor, or Callback + +| Matcher | Description | +| :--------------- | :------------------------------------------------ | +| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | +| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message. + +## Pointer Matchers + +| Matcher | Description | +| :------------------------ | :---------------------------------------------- | +| `Address(m)` | the result of `std::addressof(argument)` matches `m`. | +| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. | +| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. | +| `WhenDynamicCastTo(m)` | when `argument` is passed through `dynamic_cast()`, it matches matcher `m`. | + +## Multi-argument Matchers {#MultiArgMatchers} + +Technically, all matchers match a *single* value. A "multi-argument" matcher is +just one that matches a *tuple*. The following matchers can be used to match a +tuple `(x, y)`: + +Matcher | Description +:------ | :---------- +`Eq()` | `x == y` +`Ge()` | `x >= y` +`Gt()` | `x > y` +`Le()` | `x <= y` +`Lt()` | `x < y` +`Ne()` | `x != y` + +You can use the following selectors to pick a subset of the arguments (or +reorder them) to participate in the matching: + +| Matcher | Description | +| :------------------------- | :---------------------------------------------- | +| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. | +| `Args(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. | + +## Composite Matchers + +You can make a matcher from one or more other matchers: + +| Matcher | Description | +| :------------------------------- | :-------------------------------------- | +| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. | +| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | +| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | +| `Not(m)` | `argument` doesn't match matcher `m`. | +| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.| + +## Adapters for Matchers + +| Matcher | Description | +| :---------------------- | :------------------------------------ | +| `MatcherCast(m)` | casts matcher `m` to type `Matcher`. | +| `SafeMatcherCast(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher`. | +| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. | + +`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, +which must be a permanent callback. + +## Using Matchers as Predicates {#MatchersAsPredicatesCheat} + +| Matcher | Description | +| :---------------------------- | :------------------------------------------ | +| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | +| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | +| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | + +## Defining Matchers + +| Macro | Description | +| :----------------------------------- | :------------------------------------ | +| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | +| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. | +| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | + +**Notes:** + +1. The `MATCHER*` macros cannot be used inside a function or class. +2. The matcher body must be *purely functional* (i.e. it cannot have any side + effect, and the result must not depend on anything other than the value + being matched and the matcher parameters). +3. You can use `PrintToString(x)` to convert a value `x` of any type to a + string. +4. You can use `ExplainMatchResult()` in a custom matcher to wrap another + matcher, for example: + + ```cpp + MATCHER_P(NestedPropertyMatches, matcher, "") { + return ExplainMatchResult(matcher, arg.nested().property(), result_listener); + } + ``` + +5. You can use `DescribeMatcher<>` to describe another matcher. For example: + + ```cpp + MATCHER_P(XAndYThat, matcher, + "X that " + DescribeMatcher(matcher, negation) + + (negation ? " or" : " and") + " Y that " + + DescribeMatcher(matcher, negation)) { + return ExplainMatchResult(matcher, arg.x(), result_listener) && + ExplainMatchResult(matcher, arg.y(), result_listener); + } + ``` diff --git a/thirdparty_builtin/googletest/docs/reference/mocking.md b/thirdparty_builtin/googletest/docs/reference/mocking.md new file mode 100644 index 000000000..e414ffbd0 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/reference/mocking.md @@ -0,0 +1,589 @@ +# Mocking Reference + +This page lists the facilities provided by GoogleTest for creating and working +with mock objects. To use them, include the header +`gmock/gmock.h`. + +## Macros {#macros} + +GoogleTest defines the following macros for working with mocks. + +### MOCK_METHOD {#MOCK_METHOD} + +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \ +`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`), +(`*`specs...`*`));` + +Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and +return type *`return_type`* within a mock class. + +The parameters of `MOCK_METHOD` mirror the method declaration. The optional +fourth parameter *`specs...`* is a comma-separated list of qualifiers. The +following qualifiers are accepted: + +| Qualifier | Meaning | +| -------------------------- | -------------------------------------------- | +| `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. | +| `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. | +| `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. | +| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. | +| `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. | + +Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments +correctly if they are not appropriately surrounded by parentheses. See the +following example: + +```cpp +class MyMock { + public: + // The following 2 lines will not compile due to commas in the arguments: + MOCK_METHOD(std::pair, GetPair, ()); // Error! + MOCK_METHOD(bool, CheckMap, (std::map, bool)); // Error! + + // One solution - wrap arguments that contain commas in parentheses: + MOCK_METHOD((std::pair), GetPair, ()); + MOCK_METHOD(bool, CheckMap, ((std::map), bool)); + + // Another solution - use type aliases: + using BoolAndInt = std::pair; + MOCK_METHOD(BoolAndInt, GetPair, ()); + using MapIntDouble = std::map; + MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool)); +}; +``` + +`MOCK_METHOD` must be used in the `public:` section of a mock class definition, +regardless of whether the method being mocked is `public`, `protected`, or +`private` in the base class. + +### EXPECT_CALL {#EXPECT_CALL} + +`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the +method *`method_name`* of the object *`mock_object`* is called with arguments +that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any +code that exercises the mock object. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The expectation will +apply only to calls of *`method_name`* whose arguments match all of the +matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to modify the expectation, and they +must be used in the following order: + +```cpp +EXPECT_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .Times(cardinality) // Can be used at most once + .InSequence(sequences...) // Can be used any number of times + .After(expectations...) // Can be used any number of times + .WillOnce(action) // Can be used any number of times + .WillRepeatedly(action) // Can be used at most once + .RetiresOnSaturation(); // Can be used at most once +``` + +See details for each modifier clause below. + +#### With {#EXPECT_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the expectation to apply only to mock function calls whose arguments +as a whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the expectation that +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +... +EXPECT_CALL(my_mock, SetPosition(_, _)) + .With(Lt()); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once on an expectation and must be the +first clause. + +#### Times {#EXPECT_CALL.Times} + +`.Times(`*`cardinality`*`)` + +Specifies how many times the mock function call is expected. + +The parameter *`cardinality`* represents the number of expected calls and can be +one of the following, all defined in the `::testing` namespace: + +| Cardinality | Meaning | +| ------------------- | --------------------------------------------------- | +| `AnyNumber()` | The function can be called any number of times. | +| `AtLeast(n)` | The function call is expected at least *n* times. | +| `AtMost(n)` | The function call is expected at most *n* times. | +| `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. | +| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. | + +If the `Times` clause is omitted, GoogleTest infers the cardinality as follows: + +* If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor + [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred + cardinality is `Times(1)`. +* If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where + *n* >= 1, the inferred cardinality is `Times(n)`. +* If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where + *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`. + +The `Times` clause can be used at most once on an expectation. + +#### InSequence {#EXPECT_CALL.InSequence} + +`.InSequence(`*`sequences...`*`)` + +Specifies that the mock function call is expected in a certain sequence. + +The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects. +Expected calls assigned to the same sequence are expected to occur in the order +the expectations are declared. + +For example, the following code sets the expectation that the `Reset()` method +of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()` +and `Describe()` can occur in any order relative to each other: + +```cpp +using ::testing::Sequence; +Sequence s1, s2; +... +EXPECT_CALL(my_mock, Reset()) + .InSequence(s1, s2); +EXPECT_CALL(my_mock, GetSize()) + .InSequence(s1); +EXPECT_CALL(my_mock, Describe()) + .InSequence(s2); +``` + +The `InSequence` clause can be used any number of times on an expectation. + +See also the [`InSequence` class](#InSequence). + +#### After {#EXPECT_CALL.After} + +`.After(`*`expectations...`*`)` + +Specifies that the mock function call is expected to occur after one or more +other calls. + +The parameter *`expectations...`* can be up to five +[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects. +The mock function call is expected to occur after all of the given expectations. + +For example, the following code sets the expectation that the `Describe()` +method of `my_mock` is called only after both `InitX()` and `InitY()` have been +called. + +```cpp +using ::testing::Expectation; +... +Expectation init_x = EXPECT_CALL(my_mock, InitX()); +Expectation init_y = EXPECT_CALL(my_mock, InitY()); +EXPECT_CALL(my_mock, Describe()) + .After(init_x, init_y); +``` + +The `ExpectationSet` object is helpful when the number of prerequisites for an +expectation is large or variable, for example: + +```cpp +using ::testing::ExpectationSet; +... +ExpectationSet all_inits; +// Collect all expectations of InitElement() calls +for (int i = 0; i < element_count; i++) { + all_inits += EXPECT_CALL(my_mock, InitElement(i)); +} +EXPECT_CALL(my_mock, Describe()) + .After(all_inits); // Expect Describe() call after all InitElement() calls +``` + +The `After` clause can be used any number of times on an expectation. + +#### WillOnce {#EXPECT_CALL.WillOnce} + +`.WillOnce(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for a single +matching function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillOnce` implicitly sets a cardinality on the expectation when +`Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +Each matching function call will perform the next action in the order declared. +For example, the following code specifies that `my_mock.GetNumber()` is expected +to be called exactly 3 times and will return `1`, `2`, and `3` respectively on +the first, second, and third calls: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillOnce(Return(3)); +``` + +The `WillOnce` clause can be used any number of times on an expectation. Unlike +`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most +once, so may be a move-only type and/or have an `&&`-qualified call operator. + +#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly} + +`.WillRepeatedly(`*`action`*`)` + +Specifies the mock function's actual behavior when invoked, for all subsequent +matching function calls. Takes effect after the actions specified in the +[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +The use of `WillRepeatedly` implicitly sets a cardinality on the expectation +when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times). + +If any `WillOnce` clauses have been specified, matching function calls will +perform those actions before the action specified by `WillRepeatedly`. See the +following example: + +```cpp +using ::testing::Return; +... +EXPECT_CALL(my_mock, GetName()) + .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls + +EXPECT_CALL(my_mock, GetNumber()) + .WillOnce(Return(42)) // Return 42 on the first call + .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls +``` + +The `WillRepeatedly` clause can be used at most once on an expectation. + +#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation} + +`.RetiresOnSaturation()` + +Indicates that the expectation will no longer be active after the expected +number of matching function calls has been reached. + +The `RetiresOnSaturation` clause is only meaningful for expectations with an +upper-bounded cardinality. The expectation will *retire* (no longer match any +function calls) after it has been *saturated* (the upper bound has been +reached). See the following example: + +```cpp +using ::testing::_; +using ::testing::AnyNumber; +... +EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1 + .Times(AnyNumber()); +EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2 + .Times(2) + .RetiresOnSaturation(); +``` + +In the above example, the first two calls to `my_mock.SetNumber(7)` match +expectation 2, which then becomes inactive and no longer matches any calls. A +third call to `my_mock.SetNumber(7)` would then match expectation 1. Without +`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)` +would match expectation 2 again, producing a failure since the limit of 2 calls +was exceeded. + +The `RetiresOnSaturation` clause can be used at most once on an expectation and +must be the last clause. + +### ON_CALL {#ON_CALL} + +`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))` + +Defines what happens when the method *`method_name`* of the object +*`mock_object`* is called with arguments that match the given matchers +*`matchers...`*. Requires a modifier clause to specify the method's behavior. +*Does not* set any expectations that the method will be called. + +The parameter *`matchers...`* is a comma-separated list of +[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that +correspond to each argument of the method *`method_name`*. The `ON_CALL` +specification will apply only to calls of *`method_name`* whose arguments match +all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if +each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard). +See the [Matchers Reference](matchers.md) for a list of all built-in matchers. + +The following chainable clauses can be used to set the method's behavior, and +they must be used in the following order: + +```cpp +ON_CALL(mock_object, method_name(matchers...)) + .With(multi_argument_matcher) // Can be used at most once + .WillByDefault(action); // Required +``` + +See details for each modifier clause below. + +#### With {#ON_CALL.With} + +`.With(`*`multi_argument_matcher`*`)` + +Restricts the specification to only mock function calls whose arguments as a +whole match the multi-argument matcher *`multi_argument_matcher`*. + +GoogleTest passes all of the arguments as one tuple into the matcher. The +parameter *`multi_argument_matcher`* must thus be a matcher of type +`Matcher>`, where `A1, ..., An` are the types of the +function arguments. + +For example, the following code sets the default behavior when +`my_mock.SetPosition()` is called with any two arguments, the first argument +being less than the second: + +```cpp +using ::testing::_; +using ::testing::Lt; +using ::testing::Return; +... +ON_CALL(my_mock, SetPosition(_, _)) + .With(Lt()) + .WillByDefault(Return(true)); +``` + +GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()` +matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers). + +The `With` clause can be used at most once with each `ON_CALL` statement. + +#### WillByDefault {#ON_CALL.WillByDefault} + +`.WillByDefault(`*`action`*`)` + +Specifies the default behavior of a matching mock function call. + +The parameter *`action`* represents the +[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function +call will perform. See the [Actions Reference](actions.md) for a list of +built-in actions. + +For example, the following code specifies that by default, a call to +`my_mock.Greet()` will return `"hello"`: + +```cpp +using ::testing::Return; +... +ON_CALL(my_mock, Greet()) + .WillByDefault(Return("hello")); +``` + +The action specified by `WillByDefault` is superseded by the actions specified +on a matching `EXPECT_CALL` statement, if any. See the +[`WillOnce`](#EXPECT_CALL.WillOnce) and +[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`. + +The `WillByDefault` clause must be used exactly once with each `ON_CALL` +statement. + +## Classes {#classes} + +GoogleTest defines the following classes for working with mocks. + +### DefaultValue {#DefaultValue} + +`::testing::DefaultValue` + +Allows a user to specify the default value for a type `T` that is both copyable +and publicly destructible (i.e. anything that can be used as a function return +type). For mock functions with a return type of `T`, this default value is +returned from function calls that do not specify an action. + +Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the +default value: + +```cpp +// Sets the default value to be returned. T must be copy constructible. +DefaultValue::Set(value); + +// Sets a factory. Will be invoked on demand. T must be move constructible. +T MakeT(); +DefaultValue::SetFactory(&MakeT); + +// Unsets the default value. +DefaultValue::Clear(); +``` + +### NiceMock {#NiceMock} + +`::testing::NiceMock` + +Represents a mock object that suppresses warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NiceMock` is analogous to usage of `T`. `NiceMock` is a subclass +of `T`, so it can be used wherever an object of type `T` is accepted. In +addition, `NiceMock` can be constructed with any arguments that a constructor +of `T` accepts. + +For example, the following code suppresses warnings on the mock `my_mock` of +type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NiceMock; +... +NiceMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`NiceMock` only works for mock methods defined using the `MOCK_METHOD` macro +directly in the definition of class `T`. If a mock method is defined in a base +class of `T`, a warning might still be generated. + +`NiceMock` might not work correctly if the destructor of `T` is not virtual. + +### NaggyMock {#NaggyMock} + +`::testing::NaggyMock` + +Represents a mock object that generates warnings on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `NaggyMock` is analogous to usage of `T`. `NaggyMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `NaggyMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates warnings on the mock `my_mock` of type +`MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::NaggyMock; +... +NaggyMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +Mock objects of type `T` by default behave the same way as `NaggyMock`. + +### StrictMock {#StrictMock} + +`::testing::StrictMock` + +Represents a mock object that generates test failures on +[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The +template parameter `T` is any mock class, except for another `NiceMock`, +`NaggyMock`, or `StrictMock`. + +Usage of `StrictMock` is analogous to usage of `T`. `StrictMock` is a +subclass of `T`, so it can be used wherever an object of type `T` is accepted. +In addition, `StrictMock` can be constructed with any arguments that a +constructor of `T` accepts. + +For example, the following code generates a test failure on the mock `my_mock` +of type `MockClass` if a method other than `DoSomething()` is called: + +```cpp +using ::testing::StrictMock; +... +StrictMock my_mock("some", "args"); +EXPECT_CALL(my_mock, DoSomething()); +... code that uses my_mock ... +``` + +`StrictMock` only works for mock methods defined using the `MOCK_METHOD` +macro directly in the definition of class `T`. If a mock method is defined in a +base class of `T`, a failure might not be generated. + +`StrictMock` might not work correctly if the destructor of `T` is not +virtual. + +### Sequence {#Sequence} + +`::testing::Sequence` + +Represents a chronological sequence of expectations. See the +[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage. + +### InSequence {#InSequence} + +`::testing::InSequence` + +An object of this type causes all expectations encountered in its scope to be +put in an anonymous sequence. + +This allows more convenient expression of multiple expectations in a single +sequence: + +```cpp +using ::testing::InSequence; +{ + InSequence seq; + + // The following are expected to occur in the order declared. + EXPECT_CALL(...); + EXPECT_CALL(...); + ... + EXPECT_CALL(...); +} +``` + +The name of the `InSequence` object does not matter. + +### Expectation {#Expectation} + +`::testing::Expectation` + +Represents a mock function call expectation as created by +[`EXPECT_CALL`](#EXPECT_CALL): + +```cpp +using ::testing::Expectation; +Expectation my_expectation = EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. + +### ExpectationSet {#ExpectationSet} + +`::testing::ExpectationSet` + +Represents a set of mock function call expectations. + +Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set: + +```cpp +using ::testing::ExpectationSet; +ExpectationSet my_expectations; +my_expectations += EXPECT_CALL(...); +``` + +Useful for specifying sequences of expectations; see the +[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`. diff --git a/thirdparty_builtin/googletest/docs/reference/testing.md b/thirdparty_builtin/googletest/docs/reference/testing.md new file mode 100644 index 000000000..877dfa322 --- /dev/null +++ b/thirdparty_builtin/googletest/docs/reference/testing.md @@ -0,0 +1,1432 @@ +# Testing Reference + + + +This page lists the facilities provided by GoogleTest for writing test programs. +To use them, include the header `gtest/gtest.h`. + +## Macros + +GoogleTest defines the following macros for writing tests. + +### TEST {#TEST} + +
+TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* in the test suite +*`TestSuiteName`*, consisting of the given statements. + +Both arguments *`TestSuiteName`* and *`TestName`* must be valid C++ identifiers +and must not contain underscores (`_`). Tests in different test suites can have +the same individual name. + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_F {#TEST_F} + +
+TEST_F(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual test named *`TestName`* that uses the test fixture class +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a test fixture class—see +[Test Fixtures](../primer.md#same-data-multiple-tests). + +The statements within the test body can be any code under test. +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +### TEST_P {#TEST_P} + +
+TEST_P(TestFixtureName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual value-parameterized test named *`TestName`* that uses the +test fixture class *`TestFixtureName`*. The test suite name is +*`TestFixtureName`*. + +Both arguments *`TestFixtureName`* and *`TestName`* must be valid C++ +identifiers and must not contain underscores (`_`). *`TestFixtureName`* must be +the name of a value-parameterized test fixture class—see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +The statements within the test body can be any code under test. Within the test +body, the test parameter can be accessed with the `GetParam()` function (see +[`WithParamInterface`](#WithParamInterface)). For example: + +```cpp +TEST_P(MyTestSuite, DoesSomething) { + ... + EXPECT_TRUE(DoSomething(GetParam())); + ... +} +``` + +[Assertions](assertions.md) used within the test body determine the outcome of +the test. + +See also [`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). + +### INSTANTIATE_TEST_SUITE_P {#INSTANTIATE_TEST_SUITE_P} + +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`)` +\ +`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`,`*`name_generator`*`)` + +Instantiates the value-parameterized test suite *`TestSuiteName`* (defined with +[`TEST_P`](#TEST_P)). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. + +The argument *`param_generator`* is one of the following GoogleTest-provided +functions that generate the test parameters, all defined in the `::testing` +namespace: + + + +| Parameter Generator | Behavior | +| ------------------- | ---------------------------------------------------- | +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. | +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. | +| `ConvertGenerator(g)` | Yields values generated by generator `g`, `static_cast` to `T`. | + +The optional last argument *`name_generator`* is a function or functor that +generates custom test name suffixes based on the test parameters. The function +must accept an argument of type +[`TestParamInfo`](#TestParamInfo) and return a `std::string`. +The test name suffix can only contain alphanumeric characters and underscores. +GoogleTest provides [`PrintToStringParamName`](#PrintToStringParamName), or a +custom function can be used for more control: + +```cpp +INSTANTIATE_TEST_SUITE_P( + MyInstantiation, MyTestSuite, + ::testing::Values(...), + [](const ::testing::TestParamInfo& info) { + // Can use info.param here to generate the test suffix + std::string name = ... + return name; + }); +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +See also +[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST). + +### TYPED_TEST_SUITE {#TYPED_TEST_SUITE} + +`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)` + +Defines a typed test suite based on the test fixture *`TestFixtureName`*. The +test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type, for example: + +```cpp +template +class MyFixture : public ::testing::Test { + public: + ... + using List = std::list; + static T shared_; + T value_; +}; +``` + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +TYPED_TEST_SUITE(MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE` +macro to parse correctly. + +See also [`TYPED_TEST`](#TYPED_TEST) and +[Typed Tests](../advanced.md#typed-tests) for more information. + +### TYPED_TEST {#TYPED_TEST} + +
+TYPED_TEST(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual typed test named *`TestName`* in the typed test suite +*`TestSuiteName`*. The test suite must be defined with +[`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See the following example: + +```cpp +TYPED_TEST(MyFixture, Example) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of MyFixture via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + + values.push_back(n); + ... +} +``` + +For more information, see [Typed Tests](../advanced.md#typed-tests). + +### TYPED_TEST_SUITE_P {#TYPED_TEST_SUITE_P} + +`TYPED_TEST_SUITE_P(`*`TestFixtureName`*`)` + +Defines a type-parameterized test suite based on the test fixture +*`TestFixtureName`*. The test suite name is *`TestFixtureName`*. + +The argument *`TestFixtureName`* is a fixture class template, parameterized by a +type. See [`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE) for an example. + +See also [`TYPED_TEST_P`](#TYPED_TEST_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### TYPED_TEST_P {#TYPED_TEST_P} + +
+TYPED_TEST_P(TestSuiteName, TestName) {
+  ... statements ...
+}
+
+ +Defines an individual type-parameterized test named *`TestName`* in the +type-parameterized test suite *`TestSuiteName`*. The test suite must be defined +with [`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P). + +Within the test body, the special name `TypeParam` refers to the type parameter, +and `TestFixture` refers to the fixture class. See [`TYPED_TEST`](#TYPED_TEST) +for an example. + +See also [`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### REGISTER_TYPED_TEST_SUITE_P {#REGISTER_TYPED_TEST_SUITE_P} + +`REGISTER_TYPED_TEST_SUITE_P(`*`TestSuiteName`*`,`*`TestNames...`*`)` + +Registers the type-parameterized tests *`TestNames...`* of the test suite +*`TestSuiteName`*. The test suite and tests must be defined with +[`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P) and [`TYPED_TEST_P`](#TYPED_TEST_P). + +For example: + +```cpp +// Define the test suite and tests. +TYPED_TEST_SUITE_P(MyFixture); +TYPED_TEST_P(MyFixture, HasPropertyA) { ... } +TYPED_TEST_P(MyFixture, HasPropertyB) { ... } + +// Register the tests in the test suite. +REGISTER_TYPED_TEST_SUITE_P(MyFixture, HasPropertyA, HasPropertyB); +``` + +See also [`INSTANTIATE_TYPED_TEST_SUITE_P`](#INSTANTIATE_TYPED_TEST_SUITE_P) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### INSTANTIATE_TYPED_TEST_SUITE_P {#INSTANTIATE_TYPED_TEST_SUITE_P} + +`INSTANTIATE_TYPED_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`Types`*`)` + +Instantiates the type-parameterized test suite *`TestSuiteName`*. The test suite +must be registered with +[`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P). + +The argument *`InstantiationName`* is a unique name for the instantiation of the +test suite, to distinguish between multiple instantiations. In test output, the +instantiation name is added as a prefix to the test suite name +*`TestSuiteName`*. + +The argument *`Types`* is a [`Types`](#Types) object representing the list of +types to run the tests on, for example: + +```cpp +using MyTypes = ::testing::Types; +INSTANTIATE_TYPED_TEST_SUITE_P(MyInstantiation, MyFixture, MyTypes); +``` + +The type alias (`using` or `typedef`) is necessary for the +`INSTANTIATE_TYPED_TEST_SUITE_P` macro to parse correctly. + +For more information, see +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +### FRIEND_TEST {#FRIEND_TEST} + +`FRIEND_TEST(`*`TestSuiteName`*`,`*`TestName`*`)` + +Within a class body, declares an individual test as a friend of the class, +enabling the test to access private class members. + +If the class is defined in a namespace, then in order to be friends of the +class, test fixtures and tests must be defined in the exact same namespace, +without inline or anonymous namespaces. + +For example, if the class definition looks like the following: + +```cpp +namespace my_namespace { + +class MyClass { + friend class MyClassTest; + FRIEND_TEST(MyClassTest, HasPropertyA); + FRIEND_TEST(MyClassTest, HasPropertyB); + ... definition of class MyClass ... +}; + +} // namespace my_namespace +``` + +Then the test code should look like: + +```cpp +namespace my_namespace { + +class MyClassTest : public ::testing::Test { + ... +}; + +TEST_F(MyClassTest, HasPropertyA) { ... } +TEST_F(MyClassTest, HasPropertyB) { ... } + +} // namespace my_namespace +``` + +See [Testing Private Code](../advanced.md#testing-private-code) for more +information. + +### SCOPED_TRACE {#SCOPED_TRACE} + +`SCOPED_TRACE(`*`message`*`)` + +Causes the current file name, line number, and the given message *`message`* to +be added to the failure message for each assertion failure that occurs in the +scope. + +For more information, see +[Adding Traces to Assertions](../advanced.md#adding-traces-to-assertions). + +See also the [`ScopedTrace` class](#ScopedTrace). + +### GTEST_SKIP {#GTEST_SKIP} + +`GTEST_SKIP()` + +Prevents further test execution at runtime. + +Can be used in individual test cases or in the `SetUp()` methods of test +environments or test fixtures (classes derived from the +[`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global +test environment `SetUp()` method, it skips all tests in the test program. If +used in a test fixture `SetUp()` method, it skips all tests in the corresponding +test suite. + +Similar to assertions, `GTEST_SKIP` allows streaming a custom message into it. + +See [Skipping Test Execution](../advanced.md#skipping-test-execution) for more +information. + +### GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST {#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST} + +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(`*`TestSuiteName`*`)` + +Allows the value-parameterized test suite *`TestSuiteName`* to be +uninstantiated. + +By default, every [`TEST_P`](#TEST_P) call without a corresponding +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P) call causes a failing +test in the test suite `GoogleTestVerification`. +`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST` suppresses this failure for the +given test suite. + +## Classes and types + +GoogleTest defines the following classes and types to help with writing tests. + +### AssertionResult {#AssertionResult} + +`::testing::AssertionResult` + +A class for indicating whether an assertion was successful. + +When the assertion wasn't successful, the `AssertionResult` object stores a +non-empty failure message that can be retrieved with the object's `message()` +method. + +To create an instance of this class, use one of the factory functions +[`AssertionSuccess()`](#AssertionSuccess) or +[`AssertionFailure()`](#AssertionFailure). + +### AssertionException {#AssertionException} + +`::testing::AssertionException` + +Exception which can be thrown from +[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult). + +### EmptyTestEventListener {#EmptyTestEventListener} + +`::testing::EmptyTestEventListener` + +Provides an empty implementation of all methods in the +[`TestEventListener`](#TestEventListener) interface, such that a subclass only +needs to override the methods it cares about. + +### Environment {#Environment} + +`::testing::Environment` + +Represents a global test environment. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down). + +#### Protected Methods {#Environment-protected} + +##### SetUp {#Environment::SetUp} + +`virtual void Environment::SetUp()` + +Override this to define how to set up the environment. + +##### TearDown {#Environment::TearDown} + +`virtual void Environment::TearDown()` + +Override this to define how to tear down the environment. + +### ScopedTrace {#ScopedTrace} + +`::testing::ScopedTrace` + +An instance of this class causes a trace to be included in every test failure +message generated by code in the scope of the lifetime of the `ScopedTrace` +instance. The effect is undone with the destruction of the instance. + +The `ScopedTrace` constructor has the following form: + +```cpp +template +ScopedTrace(const char* file, int line, const T& message) +``` + +Example usage: + +```cpp +::testing::ScopedTrace trace("file.cc", 123, "message"); +``` + +The resulting trace includes the given source file path and line number, and the +given message. The `message` argument can be anything streamable to +`std::ostream`. + +See also [`SCOPED_TRACE`](#SCOPED_TRACE). + +### Test {#Test} + +`::testing::Test` + +The abstract class that all tests inherit from. `Test` is not copyable. + +#### Public Methods {#Test-public} + +##### SetUpTestSuite {#Test::SetUpTestSuite} + +`static void Test::SetUpTestSuite()` + +Performs shared setup for all tests in the test suite. GoogleTest calls +`SetUpTestSuite()` before running the first test in the test suite. + +##### TearDownTestSuite {#Test::TearDownTestSuite} + +`static void Test::TearDownTestSuite()` + +Performs shared teardown for all tests in the test suite. GoogleTest calls +`TearDownTestSuite()` after running the last test in the test suite. + +##### HasFatalFailure {#Test::HasFatalFailure} + +`static bool Test::HasFatalFailure()` + +Returns true if and only if the current test has a fatal failure. + +##### HasNonfatalFailure {#Test::HasNonfatalFailure} + +`static bool Test::HasNonfatalFailure()` + +Returns true if and only if the current test has a nonfatal failure. + +##### HasFailure {#Test::HasFailure} + +`static bool Test::HasFailure()` + +Returns true if and only if the current test has any failure, either fatal or +nonfatal. + +##### IsSkipped {#Test::IsSkipped} + +`static bool Test::IsSkipped()` + +Returns true if and only if the current test was skipped. + +##### RecordProperty {#Test::RecordProperty} + +`static void Test::RecordProperty(const std::string& key, const std::string& +value)` \ +`static void Test::RecordProperty(const std::string& key, int value)` + +Logs a property for the current test, test suite, or entire invocation of the +test program. Only the last value for a given key is logged. + +The key must be a valid XML attribute name, and cannot conflict with the ones +already used by GoogleTest (`name`, `file`, `line`, `status`, `time`, +`classname`, `type_param`, and `value_param`). + +`RecordProperty` is `public static` so it can be called from utility functions +that are not members of the test fixture. + +Calls to `RecordProperty` made during the lifespan of the test (from the moment +its constructor starts to the moment its destructor finishes) are output in XML +as attributes of the `` element. Properties recorded from a fixture's +`SetUpTestSuite` or `TearDownTestSuite` methods are logged as attributes of the +corresponding `` element. Calls to `RecordProperty` made in the +global context (before or after invocation of `RUN_ALL_TESTS` or from the +`SetUp`/`TearDown` methods of registered `Environment` objects) are output as +attributes of the `` element. + +#### Protected Methods {#Test-protected} + +##### SetUp {#Test::SetUp} + +`virtual void Test::SetUp()` + +Override this to perform test fixture setup. GoogleTest calls `SetUp()` before +running each individual test. + +##### TearDown {#Test::TearDown} + +`virtual void Test::TearDown()` + +Override this to perform test fixture teardown. GoogleTest calls `TearDown()` +after running each individual test. + +### TestWithParam {#TestWithParam} + +`::testing::TestWithParam` + +A convenience class which inherits from both [`Test`](#Test) and +[`WithParamInterface`](#WithParamInterface). + +### TestSuite {#TestSuite} + +Represents a test suite. `TestSuite` is not copyable. + +#### Public Methods {#TestSuite-public} + +##### name {#TestSuite::name} + +`const char* TestSuite::name() const` + +Gets the name of the test suite. + +##### type_param {#TestSuite::type_param} + +`const char* TestSuite::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test suite. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### should_run {#TestSuite::should_run} + +`bool TestSuite::should_run() const` + +Returns true if any test in this test suite should run. + +##### successful_test_count {#TestSuite::successful_test_count} + +`int TestSuite::successful_test_count() const` + +Gets the number of successful tests in this test suite. + +##### skipped_test_count {#TestSuite::skipped_test_count} + +`int TestSuite::skipped_test_count() const` + +Gets the number of skipped tests in this test suite. + +##### failed_test_count {#TestSuite::failed_test_count} + +`int TestSuite::failed_test_count() const` + +Gets the number of failed tests in this test suite. + +##### reportable_disabled_test_count {#TestSuite::reportable_disabled_test_count} + +`int TestSuite::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#TestSuite::disabled_test_count} + +`int TestSuite::disabled_test_count() const` + +Gets the number of disabled tests in this test suite. + +##### reportable_test_count {#TestSuite::reportable_test_count} + +`int TestSuite::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### test_to_run_count {#TestSuite::test_to_run_count} + +`int TestSuite::test_to_run_count() const` + +Get the number of tests in this test suite that should run. + +##### total_test_count {#TestSuite::total_test_count} + +`int TestSuite::total_test_count() const` + +Gets the number of all tests in this test suite. + +##### Passed {#TestSuite::Passed} + +`bool TestSuite::Passed() const` + +Returns true if and only if the test suite passed. + +##### Failed {#TestSuite::Failed} + +`bool TestSuite::Failed() const` + +Returns true if and only if the test suite failed. + +##### elapsed_time {#TestSuite::elapsed_time} + +`TimeInMillis TestSuite::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestSuite::start_timestamp} + +`TimeInMillis TestSuite::start_timestamp() const` + +Gets the time of the test suite start, in ms from the start of the UNIX epoch. + +##### GetTestInfo {#TestSuite::GetTestInfo} + +`const TestInfo* TestSuite::GetTestInfo(int i) const` + +Returns the [`TestInfo`](#TestInfo) for the `i`-th test among all the tests. `i` +can range from 0 to `total_test_count() - 1`. If `i` is not in that range, +returns `NULL`. + +##### ad_hoc_test_result {#TestSuite::ad_hoc_test_result} + +`const TestResult& TestSuite::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) that holds test properties recorded +during execution of `SetUpTestSuite` and `TearDownTestSuite`. + +### TestInfo {#TestInfo} + +`::testing::TestInfo` + +Stores information about a test. + +#### Public Methods {#TestInfo-public} + +##### test_suite_name {#TestInfo::test_suite_name} + +`const char* TestInfo::test_suite_name() const` + +Returns the test suite name. + +##### name {#TestInfo::name} + +`const char* TestInfo::name() const` + +Returns the test name. + +##### type_param {#TestInfo::type_param} + +`const char* TestInfo::type_param() const` + +Returns the name of the parameter type, or `NULL` if this is not a typed or +type-parameterized test. See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests). + +##### value_param {#TestInfo::value_param} + +`const char* TestInfo::value_param() const` + +Returns the text representation of the value parameter, or `NULL` if this is not +a value-parameterized test. See +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +##### file {#TestInfo::file} + +`const char* TestInfo::file() const` + +Returns the file name where this test is defined. + +##### line {#TestInfo::line} + +`int TestInfo::line() const` + +Returns the line where this test is defined. + +##### is_in_another_shard {#TestInfo::is_in_another_shard} + +`bool TestInfo::is_in_another_shard() const` + +Returns true if this test should not be run because it's in another shard. + +##### should_run {#TestInfo::should_run} + +`bool TestInfo::should_run() const` + +Returns true if this test should run, that is if the test is not disabled (or it +is disabled but the `also_run_disabled_tests` flag has been specified) and its +full name matches the user-specified filter. + +GoogleTest allows the user to filter the tests by their full names. Only the +tests that match the filter will run. See +[Running a Subset of the Tests](../advanced.md#running-a-subset-of-the-tests) +for more information. + +##### is_reportable {#TestInfo::is_reportable} + +`bool TestInfo::is_reportable() const` + +Returns true if and only if this test will appear in the XML report. + +##### result {#TestInfo::result} + +`const TestResult* TestInfo::result() const` + +Returns the result of the test. See [`TestResult`](#TestResult). + +### TestParamInfo {#TestParamInfo} + +`::testing::TestParamInfo` + +Describes a parameter to a value-parameterized test. The type `T` is the type of +the parameter. + +Contains the fields `param` and `index` which hold the value of the parameter +and its integer index respectively. + +### UnitTest {#UnitTest} + +`::testing::UnitTest` + +This class contains information about the test program. + +`UnitTest` is a singleton class. The only instance is created when +`UnitTest::GetInstance()` is first called. This instance is never deleted. + +`UnitTest` is not copyable. + +#### Public Methods {#UnitTest-public} + +##### GetInstance {#UnitTest::GetInstance} + +`static UnitTest* UnitTest::GetInstance()` + +Gets the singleton `UnitTest` object. The first time this method is called, a +`UnitTest` object is constructed and returned. Consecutive calls will return the +same object. + +##### original_working_dir {#UnitTest::original_working_dir} + +`const char* UnitTest::original_working_dir() const` + +Returns the working directory when the first [`TEST()`](#TEST) or +[`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string. + +##### current_test_suite {#UnitTest::current_test_suite} + +`const TestSuite* UnitTest::current_test_suite() const` + +Returns the [`TestSuite`](#TestSuite) object for the test that's currently +running, or `NULL` if no test is running. + +##### current_test_info {#UnitTest::current_test_info} + +`const TestInfo* UnitTest::current_test_info() const` + +Returns the [`TestInfo`](#TestInfo) object for the test that's currently +running, or `NULL` if no test is running. + +##### random_seed {#UnitTest::random_seed} + +`int UnitTest::random_seed() const` + +Returns the random seed used at the start of the current test run. + +##### successful_test_suite_count {#UnitTest::successful_test_suite_count} + +`int UnitTest::successful_test_suite_count() const` + +Gets the number of successful test suites. + +##### failed_test_suite_count {#UnitTest::failed_test_suite_count} + +`int UnitTest::failed_test_suite_count() const` + +Gets the number of failed test suites. + +##### total_test_suite_count {#UnitTest::total_test_suite_count} + +`int UnitTest::total_test_suite_count() const` + +Gets the number of all test suites. + +##### test_suite_to_run_count {#UnitTest::test_suite_to_run_count} + +`int UnitTest::test_suite_to_run_count() const` + +Gets the number of all test suites that contain at least one test that should +run. + +##### successful_test_count {#UnitTest::successful_test_count} + +`int UnitTest::successful_test_count() const` + +Gets the number of successful tests. + +##### skipped_test_count {#UnitTest::skipped_test_count} + +`int UnitTest::skipped_test_count() const` + +Gets the number of skipped tests. + +##### failed_test_count {#UnitTest::failed_test_count} + +`int UnitTest::failed_test_count() const` + +Gets the number of failed tests. + +##### reportable_disabled_test_count {#UnitTest::reportable_disabled_test_count} + +`int UnitTest::reportable_disabled_test_count() const` + +Gets the number of disabled tests that will be reported in the XML report. + +##### disabled_test_count {#UnitTest::disabled_test_count} + +`int UnitTest::disabled_test_count() const` + +Gets the number of disabled tests. + +##### reportable_test_count {#UnitTest::reportable_test_count} + +`int UnitTest::reportable_test_count() const` + +Gets the number of tests to be printed in the XML report. + +##### total_test_count {#UnitTest::total_test_count} + +`int UnitTest::total_test_count() const` + +Gets the number of all tests. + +##### test_to_run_count {#UnitTest::test_to_run_count} + +`int UnitTest::test_to_run_count() const` + +Gets the number of tests that should run. + +##### start_timestamp {#UnitTest::start_timestamp} + +`TimeInMillis UnitTest::start_timestamp() const` + +Gets the time of the test program start, in ms from the start of the UNIX epoch. + +##### elapsed_time {#UnitTest::elapsed_time} + +`TimeInMillis UnitTest::elapsed_time() const` + +Gets the elapsed time, in milliseconds. + +##### Passed {#UnitTest::Passed} + +`bool UnitTest::Passed() const` + +Returns true if and only if the unit test passed (i.e. all test suites passed). + +##### Failed {#UnitTest::Failed} + +`bool UnitTest::Failed() const` + +Returns true if and only if the unit test failed (i.e. some test suite failed or +something outside of all tests failed). + +##### GetTestSuite {#UnitTest::GetTestSuite} + +`const TestSuite* UnitTest::GetTestSuite(int i) const` + +Gets the [`TestSuite`](#TestSuite) object for the `i`-th test suite among all +the test suites. `i` can range from 0 to `total_test_suite_count() - 1`. If `i` +is not in that range, returns `NULL`. + +##### ad_hoc_test_result {#UnitTest::ad_hoc_test_result} + +`const TestResult& UnitTest::ad_hoc_test_result() const` + +Returns the [`TestResult`](#TestResult) containing information on test failures +and properties logged outside of individual test suites. + +##### listeners {#UnitTest::listeners} + +`TestEventListeners& UnitTest::listeners()` + +Returns the list of event listeners that can be used to track events inside +GoogleTest. See [`TestEventListeners`](#TestEventListeners). + +### TestEventListener {#TestEventListener} + +`::testing::TestEventListener` + +The interface for tracing execution of tests. The methods below are listed in +the order the corresponding events are fired. + +#### Public Methods {#TestEventListener-public} + +##### OnTestProgramStart {#TestEventListener::OnTestProgramStart} + +`virtual void TestEventListener::OnTestProgramStart(const UnitTest& unit_test)` + +Fired before any test activity starts. + +##### OnTestIterationStart {#TestEventListener::OnTestIterationStart} + +`virtual void TestEventListener::OnTestIterationStart(const UnitTest& unit_test, +int iteration)` + +Fired before each iteration of tests starts. There may be more than one +iteration if `GTEST_FLAG(repeat)` is set. `iteration` is the iteration index, +starting from 0. + +##### OnEnvironmentsSetUpStart {#TestEventListener::OnEnvironmentsSetUpStart} + +`virtual void TestEventListener::OnEnvironmentsSetUpStart(const UnitTest& +unit_test)` + +Fired before environment set-up for each iteration of tests starts. + +##### OnEnvironmentsSetUpEnd {#TestEventListener::OnEnvironmentsSetUpEnd} + +`virtual void TestEventListener::OnEnvironmentsSetUpEnd(const UnitTest& +unit_test)` + +Fired after environment set-up for each iteration of tests ends. + +##### OnTestSuiteStart {#TestEventListener::OnTestSuiteStart} + +`virtual void TestEventListener::OnTestSuiteStart(const TestSuite& test_suite)` + +Fired before the test suite starts. + +##### OnTestStart {#TestEventListener::OnTestStart} + +`virtual void TestEventListener::OnTestStart(const TestInfo& test_info)` + +Fired before the test starts. + +##### OnTestPartResult {#TestEventListener::OnTestPartResult} + +`virtual void TestEventListener::OnTestPartResult(const TestPartResult& +test_part_result)` + +Fired after a failed assertion or a `SUCCEED()` invocation. If you want to throw +an exception from this function to skip to the next test, it must be an +[`AssertionException`](#AssertionException) or inherited from it. + +##### OnTestEnd {#TestEventListener::OnTestEnd} + +`virtual void TestEventListener::OnTestEnd(const TestInfo& test_info)` + +Fired after the test ends. + +##### OnTestSuiteEnd {#TestEventListener::OnTestSuiteEnd} + +`virtual void TestEventListener::OnTestSuiteEnd(const TestSuite& test_suite)` + +Fired after the test suite ends. + +##### OnEnvironmentsTearDownStart {#TestEventListener::OnEnvironmentsTearDownStart} + +`virtual void TestEventListener::OnEnvironmentsTearDownStart(const UnitTest& +unit_test)` + +Fired before environment tear-down for each iteration of tests starts. + +##### OnEnvironmentsTearDownEnd {#TestEventListener::OnEnvironmentsTearDownEnd} + +`virtual void TestEventListener::OnEnvironmentsTearDownEnd(const UnitTest& +unit_test)` + +Fired after environment tear-down for each iteration of tests ends. + +##### OnTestIterationEnd {#TestEventListener::OnTestIterationEnd} + +`virtual void TestEventListener::OnTestIterationEnd(const UnitTest& unit_test, +int iteration)` + +Fired after each iteration of tests finishes. + +##### OnTestProgramEnd {#TestEventListener::OnTestProgramEnd} + +`virtual void TestEventListener::OnTestProgramEnd(const UnitTest& unit_test)` + +Fired after all test activities have ended. + +### TestEventListeners {#TestEventListeners} + +`::testing::TestEventListeners` + +Lets users add listeners to track events in GoogleTest. + +#### Public Methods {#TestEventListeners-public} + +##### Append {#TestEventListeners::Append} + +`void TestEventListeners::Append(TestEventListener* listener)` + +Appends an event listener to the end of the list. GoogleTest assumes ownership +of the listener (i.e. it will delete the listener when the test program +finishes). + +##### Release {#TestEventListeners::Release} + +`TestEventListener* TestEventListeners::Release(TestEventListener* listener)` + +Removes the given event listener from the list and returns it. It then becomes +the caller's responsibility to delete the listener. Returns `NULL` if the +listener is not found in the list. + +##### default_result_printer {#TestEventListeners::default_result_printer} + +`TestEventListener* TestEventListeners::default_result_printer() const` + +Returns the standard listener responsible for the default console output. Can be +removed from the listeners list to shut down default console output. Note that +removing this object from the listener list with +[`Release()`](#TestEventListeners::Release) transfers its ownership to the +caller and makes this function return `NULL` the next time. + +##### default_xml_generator {#TestEventListeners::default_xml_generator} + +`TestEventListener* TestEventListeners::default_xml_generator() const` + +Returns the standard listener responsible for the default XML output controlled +by the `--gtest_output=xml` flag. Can be removed from the listeners list by +users who want to shut down the default XML output controlled by this flag and +substitute it with custom one. Note that removing this object from the listener +list with [`Release()`](#TestEventListeners::Release) transfers its ownership to +the caller and makes this function return `NULL` the next time. + +### TestPartResult {#TestPartResult} + +`::testing::TestPartResult` + +A copyable object representing the result of a test part (i.e. an assertion or +an explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`). + +#### Public Methods {#TestPartResult-public} + +##### type {#TestPartResult::type} + +`Type TestPartResult::type() const` + +Gets the outcome of the test part. + +The return type `Type` is an enum defined as follows: + +```cpp +enum Type { + kSuccess, // Succeeded. + kNonFatalFailure, // Failed but the test can continue. + kFatalFailure, // Failed and the test should be terminated. + kSkip // Skipped. +}; +``` + +##### file_name {#TestPartResult::file_name} + +`const char* TestPartResult::file_name() const` + +Gets the name of the source file where the test part took place, or `NULL` if +it's unknown. + +##### line_number {#TestPartResult::line_number} + +`int TestPartResult::line_number() const` + +Gets the line in the source file where the test part took place, or `-1` if it's +unknown. + +##### summary {#TestPartResult::summary} + +`const char* TestPartResult::summary() const` + +Gets the summary of the failure message. + +##### message {#TestPartResult::message} + +`const char* TestPartResult::message() const` + +Gets the message associated with the test part. + +##### skipped {#TestPartResult::skipped} + +`bool TestPartResult::skipped() const` + +Returns true if and only if the test part was skipped. + +##### passed {#TestPartResult::passed} + +`bool TestPartResult::passed() const` + +Returns true if and only if the test part passed. + +##### nonfatally_failed {#TestPartResult::nonfatally_failed} + +`bool TestPartResult::nonfatally_failed() const` + +Returns true if and only if the test part non-fatally failed. + +##### fatally_failed {#TestPartResult::fatally_failed} + +`bool TestPartResult::fatally_failed() const` + +Returns true if and only if the test part fatally failed. + +##### failed {#TestPartResult::failed} + +`bool TestPartResult::failed() const` + +Returns true if and only if the test part failed. + +### TestProperty {#TestProperty} + +`::testing::TestProperty` + +A copyable object representing a user-specified test property which can be +output as a key/value string pair. + +#### Public Methods {#TestProperty-public} + +##### key {#key} + +`const char* key() const` + +Gets the user-supplied key. + +##### value {#value} + +`const char* value() const` + +Gets the user-supplied value. + +##### SetValue {#SetValue} + +`void SetValue(const std::string& new_value)` + +Sets a new value, overriding the previous one. + +### TestResult {#TestResult} + +`::testing::TestResult` + +Contains information about the result of a single test. + +`TestResult` is not copyable. + +#### Public Methods {#TestResult-public} + +##### total_part_count {#TestResult::total_part_count} + +`int TestResult::total_part_count() const` + +Gets the number of all test parts. This is the sum of the number of successful +test parts and the number of failed test parts. + +##### test_property_count {#TestResult::test_property_count} + +`int TestResult::test_property_count() const` + +Returns the number of test properties. + +##### Passed {#TestResult::Passed} + +`bool TestResult::Passed() const` + +Returns true if and only if the test passed (i.e. no test part failed). + +##### Skipped {#TestResult::Skipped} + +`bool TestResult::Skipped() const` + +Returns true if and only if the test was skipped. + +##### Failed {#TestResult::Failed} + +`bool TestResult::Failed() const` + +Returns true if and only if the test failed. + +##### HasFatalFailure {#TestResult::HasFatalFailure} + +`bool TestResult::HasFatalFailure() const` + +Returns true if and only if the test fatally failed. + +##### HasNonfatalFailure {#TestResult::HasNonfatalFailure} + +`bool TestResult::HasNonfatalFailure() const` + +Returns true if and only if the test has a non-fatal failure. + +##### elapsed_time {#TestResult::elapsed_time} + +`TimeInMillis TestResult::elapsed_time() const` + +Returns the elapsed time, in milliseconds. + +##### start_timestamp {#TestResult::start_timestamp} + +`TimeInMillis TestResult::start_timestamp() const` + +Gets the time of the test case start, in ms from the start of the UNIX epoch. + +##### GetTestPartResult {#TestResult::GetTestPartResult} + +`const TestPartResult& TestResult::GetTestPartResult(int i) const` + +Returns the [`TestPartResult`](#TestPartResult) for the `i`-th test part result +among all the results. `i` can range from 0 to `total_part_count() - 1`. If `i` +is not in that range, aborts the program. + +##### GetTestProperty {#TestResult::GetTestProperty} + +`const TestProperty& TestResult::GetTestProperty(int i) const` + +Returns the [`TestProperty`](#TestProperty) object for the `i`-th test property. +`i` can range from 0 to `test_property_count() - 1`. If `i` is not in that +range, aborts the program. + +### TimeInMillis {#TimeInMillis} + +`::testing::TimeInMillis` + +An integer type representing time in milliseconds. + +### Types {#Types} + +`::testing::Types` + +Represents a list of types for use in typed tests and type-parameterized tests. + +The template argument `T...` can be any number of types, for example: + +``` +::testing::Types +``` + +See [Typed Tests](../advanced.md#typed-tests) and +[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more +information. + +### WithParamInterface {#WithParamInterface} + +`::testing::WithParamInterface` + +The pure interface class that all value-parameterized tests inherit from. + +A value-parameterized test fixture class must inherit from both [`Test`](#Test) +and `WithParamInterface`. In most cases that just means inheriting from +[`TestWithParam`](#TestWithParam), but more complicated test hierarchies may +need to inherit from `Test` and `WithParamInterface` at different levels. + +This interface defines the type alias `ParamType` for the parameter type `T` and +has support for accessing the test parameter value via the `GetParam()` method: + +``` +static const ParamType& GetParam() +``` + +For more information, see +[Value-Parameterized Tests](../advanced.md#value-parameterized-tests). + +## Functions + +GoogleTest defines the following functions to help with writing and running +tests. + +### InitGoogleTest {#InitGoogleTest} + +`void ::testing::InitGoogleTest(int* argc, char** argv)` \ +`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \ +`void ::testing::InitGoogleTest()` + +Initializes GoogleTest. This must be called before calling +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line +for the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it +is removed from `argv`, and `*argc` is decremented. + +No value is returned. Instead, the GoogleTest flag variables are updated. + +The `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows +programs compiled in `UNICODE` mode. + +The argument-less `InitGoogleTest()` overload can be used on Arduino/embedded +platforms where there is no `argc`/`argv`. + +### AddGlobalTestEnvironment {#AddGlobalTestEnvironment} + +`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)` + +Adds a test environment to the test program. Must be called before +[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See +[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down) for +more information. + +See also [`Environment`](#Environment). + +### RegisterTest {#RegisterTest} + +```cpp +template +TestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name, + const char* type_param, const char* value_param, + const char* file, int line, Factory factory) +``` + +Dynamically registers a test with the framework. + +The `factory` argument is a factory callable (move-constructible) object or +function pointer that creates a new instance of the `Test` object. It handles +ownership to the caller. The signature of the callable is `Fixture*()`, where +`Fixture` is the test fixture class for the test. All tests registered with the +same `test_suite_name` must return the same fixture type. This is checked at +runtime. + +The framework will infer the fixture class from the factory and will call the +`SetUpTestSuite` and `TearDownTestSuite` methods for it. + +Must be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is invoked, otherwise +behavior is undefined. + +See +[Registering tests programmatically](../advanced.md#registering-tests-programmatically) +for more information. + +### RUN_ALL_TESTS {#RUN_ALL_TESTS} + +`int RUN_ALL_TESTS()` + +Use this function in `main()` to run all tests. It returns `0` if all tests are +successful, or `1` otherwise. + +`RUN_ALL_TESTS()` should be invoked after the command line has been parsed by +[`InitGoogleTest()`](#InitGoogleTest). + +This function was formerly a macro; thus, it is in the global namespace and has +an all-caps name. + +### AssertionSuccess {#AssertionSuccess} + +`AssertionResult ::testing::AssertionSuccess()` + +Creates a successful assertion result. See +[`AssertionResult`](#AssertionResult). + +### AssertionFailure {#AssertionFailure} + +`AssertionResult ::testing::AssertionFailure()` + +Creates a failed assertion result. Use the `<<` operator to store a failure +message: + +```cpp +::testing::AssertionFailure() << "My failure message"; +``` + +See [`AssertionResult`](#AssertionResult). + +### StaticAssertTypeEq {#StaticAssertTypeEq} + +`::testing::StaticAssertTypeEq()` + +Compile-time assertion for type equality. Compiles if and only if `T1` and `T2` +are the same type. The value it returns is irrelevant. + +See [Type Assertions](../advanced.md#type-assertions) for more information. + +### PrintToString {#PrintToString} + +`std::string ::testing::PrintToString(x)` + +Prints any value `x` using GoogleTest's value printer. + +See +[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values) +for more information. + +### PrintToStringParamName {#PrintToStringParamName} + +`std::string ::testing::PrintToStringParamName(TestParamInfo& info)` + +A built-in parameterized test name generator which returns the result of +[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the +test parameter is a `std::string` or C string. See +[Specifying Names for Value-Parameterized Test Parameters](../advanced.md#specifying-names-for-value-parameterized-test-parameters) +for more information. + +See also [`TestParamInfo`](#TestParamInfo) and +[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P). diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/samples.md b/thirdparty_builtin/googletest/docs/samples.md similarity index 89% rename from thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/samples.md rename to thirdparty_builtin/googletest/docs/samples.md index aaa588383..dedc59098 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googletest/docs/samples.md +++ b/thirdparty_builtin/googletest/docs/samples.md @@ -1,7 +1,7 @@ -# Googletest Samples {#samples} +# Googletest Samples If you're like us, you'd like to look at -[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples) +[googletest samples.](https://github.com/google/googletest/blob/main/googletest/samples) The sample directory has a number of well-commented samples showing how to use a variety of googletest features. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/CMakeLists.txt b/thirdparty_builtin/googletest/googlemock/CMakeLists.txt similarity index 82% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/CMakeLists.txt rename to thirdparty_builtin/googletest/googlemock/CMakeLists.txt index dde8aec39..19198f9dc 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/CMakeLists.txt +++ b/thirdparty_builtin/googletest/googlemock/CMakeLists.txt @@ -36,13 +36,8 @@ endif() # as ${gmock_SOURCE_DIR} and to the root binary directory as # ${gmock_BINARY_DIR}. # Language "C" is required for find_package(Threads). -if (CMAKE_VERSION VERSION_LESS 3.0) - project(gmock CXX C) -else() - cmake_policy(SET CMP0048 NEW) - project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) -endif() -cmake_minimum_required(VERSION 3.0) +cmake_policy(SET CMP0048 NEW) +project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) if (COMMAND set_up_hermetic_build) set_up_hermetic_build() @@ -100,19 +95,10 @@ if (MSVC) else() cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) target_link_libraries(gmock PUBLIC gtest) + set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION}) cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) target_link_libraries(gmock_main PUBLIC gmock) -endif() -# 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") - target_include_directories(gmock INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") - target_include_directories(gmock_main INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") + set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION}) endif() ######################################################################## @@ -136,20 +122,6 @@ if (gmock_build_tests) # 'make test' or ctest. enable_testing() - if (WIN32) - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$/RunTest.ps1" - CONTENT -"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$\" -$env:Path = \"$project_bin;$env:Path\" -& $args") - elseif (MINGW OR CYGWIN) - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1" - CONTENT -"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin) -$env:Path = \"$project_bin;$env:Path\" -& $args") - endif() - if (MINGW OR CYGWIN) if (CMAKE_VERSION VERSION_LESS "2.8.12") add_compile_options("-Wa,-mbig-obj") @@ -165,11 +137,11 @@ $env:Path = \"$project_bin;$env:Path\" cxx_test(gmock-cardinalities_test gmock_main) cxx_test(gmock_ex_test gmock_main) cxx_test(gmock-function-mocker_test gmock_main) - cxx_test(gmock-generated-actions_test gmock_main) - cxx_test(gmock-generated-function-mockers_test gmock_main) - cxx_test(gmock-generated-matchers_test gmock_main) cxx_test(gmock-internal-utils_test gmock_main) - cxx_test(gmock-matchers_test gmock_main) + cxx_test(gmock-matchers-arithmetic_test gmock_main) + cxx_test(gmock-matchers-comparisons_test gmock_main) + cxx_test(gmock-matchers-containers_test gmock_main) + cxx_test(gmock-matchers-misc_test gmock_main) cxx_test(gmock-more-actions_test gmock_main) cxx_test(gmock-nice-strict_test gmock_main) cxx_test(gmock-port_test gmock_main) diff --git a/thirdparty_builtin/googletest/googlemock/README.md b/thirdparty_builtin/googletest/googlemock/README.md new file mode 100644 index 000000000..7da60655d --- /dev/null +++ b/thirdparty_builtin/googletest/googlemock/README.md @@ -0,0 +1,40 @@ +# Googletest Mocking (gMock) Framework + +### Overview + +Google's framework for writing and using C++ mock classes. It can help you +derive better designs of your system and write better tests. + +It is inspired by: + +* [jMock](http://www.jmock.org/) +* [EasyMock](http://www.easymock.org/) +* [Hamcrest](http://code.google.com/p/hamcrest/) + +It is designed with C++'s specifics in mind. + +gMock: + +- Provides a declarative syntax for defining mocks. +- Can define partial (hybrid) mocks, which are a cross of real and mock + objects. +- Handles functions of arbitrary types and overloaded functions. +- Comes with a rich set of matchers for validating function arguments. +- Uses an intuitive syntax for controlling the behavior of a mock. +- Does automatic verification of expectations (no record-and-replay needed). +- Allows arbitrary (partial) ordering constraints on function calls to be + expressed. +- Lets a user extend it by defining new matchers and actions. +- Does not use exceptions. +- Is easy to learn and use. + +Details and examples can be found here: + +* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html) +* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html) +* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html) +* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html) + +GoogleMock is a part of +[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a +subject to the same requirements. diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/cmake/gmock.pc.in b/thirdparty_builtin/googletest/googlemock/cmake/gmock.pc.in similarity index 89% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/cmake/gmock.pc.in rename to thirdparty_builtin/googletest/googlemock/cmake/gmock.pc.in index 5780fcaa5..23c67b5c8 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/cmake/gmock.pc.in +++ b/thirdparty_builtin/googletest/googlemock/cmake/gmock.pc.in @@ -5,6 +5,6 @@ Name: gmock Description: GoogleMock (without main() function) Version: @PROJECT_VERSION@ URL: https://github.com/google/googletest -Requires: gtest +Requires: gtest = @PROJECT_VERSION@ Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/cmake/gmock_main.pc.in b/thirdparty_builtin/googletest/googlemock/cmake/gmock_main.pc.in similarity index 89% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/cmake/gmock_main.pc.in rename to thirdparty_builtin/googletest/googlemock/cmake/gmock_main.pc.in index f2dfe69e0..66ffea7f4 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/cmake/gmock_main.pc.in +++ b/thirdparty_builtin/googletest/googlemock/cmake/gmock_main.pc.in @@ -5,6 +5,6 @@ Name: gmock_main Description: GoogleMock (with main() function) Version: @PROJECT_VERSION@ URL: https://github.com/google/googletest -Requires: gmock +Requires: gmock = @PROJECT_VERSION@ Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ diff --git a/thirdparty_builtin/googletest/googlemock/docs/README.md b/thirdparty_builtin/googletest/googlemock/docs/README.md new file mode 100644 index 000000000..1bc57b799 --- /dev/null +++ b/thirdparty_builtin/googletest/googlemock/docs/README.md @@ -0,0 +1,4 @@ +# Content Moved + +We are working on updates to the GoogleTest documentation, which has moved to +the top-level [docs](../../docs) directory. diff --git a/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-actions.h b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-actions.h new file mode 100644 index 000000000..c0bb8a9c6 --- /dev/null +++ b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-actions.h @@ -0,0 +1,2297 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// The ACTION* family of macros can be used in a namespace scope to +// define custom actions easily. The syntax: +// +// ACTION(name) { statements; } +// +// will define an action with the given name that executes the +// statements. The value returned by the statements will be used as +// the return value of the action. Inside the statements, you can +// refer to the K-th (0-based) argument of the mock function by +// 'argK', and refer to its type by 'argK_type'. For example: +// +// ACTION(IncrementArg1) { +// arg1_type temp = arg1; +// return ++(*temp); +// } +// +// allows you to write +// +// ...WillOnce(IncrementArg1()); +// +// You can also refer to the entire argument tuple and its type by +// 'args' and 'args_type', and refer to the mock function type and its +// return type by 'function_type' and 'return_type'. +// +// Note that you don't need to specify the types of the mock function +// arguments. However rest assured that your code is still type-safe: +// you'll get a compiler error if *arg1 doesn't support the ++ +// operator, or if the type of ++(*arg1) isn't compatible with the +// mock function's return type, for example. +// +// Sometimes you'll want to parameterize the action. For that you can use +// another macro: +// +// ACTION_P(name, param_name) { statements; } +// +// For example: +// +// ACTION_P(Add, n) { return arg0 + n; } +// +// will allow you to write: +// +// ...WillOnce(Add(5)); +// +// Note that you don't need to provide the type of the parameter +// either. If you need to reference the type of a parameter named +// 'foo', you can write 'foo_type'. For example, in the body of +// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type +// of 'n'. +// +// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support +// multi-parameter actions. +// +// For the purpose of typing, you can view +// +// ACTION_Pk(Foo, p1, ..., pk) { ... } +// +// as shorthand for +// +// template +// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } +// +// In particular, you can provide the template type arguments +// explicitly when invoking Foo(), as in Foo(5, false); +// although usually you can rely on the compiler to infer the types +// for you automatically. You can assign the result of expression +// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. +// +// You can also overload actions with different numbers of parameters: +// +// ACTION_P(Plus, a) { ... } +// ACTION_P2(Plus, a, b) { ... } +// +// While it's tempting to always use the ACTION* macros when defining +// a new action, you should also consider implementing ActionInterface +// or using MakePolymorphicAction() instead, especially if you need to +// use the action a lot. While these approaches require more work, +// they give you more control on the types of the mock function +// arguments and the action parameters, which in general leads to +// better compiler error messages that pay off in the long run. They +// also allow overloading actions based on parameter types (as opposed +// to just based on the number of parameters). +// +// CAVEAT: +// +// ACTION*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// Users can, however, define any local functors (e.g. a lambda) that +// can be used as actions. +// +// MORE INFORMATION: +// +// To learn more about using these macros, please search for 'ACTION' on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ + +#ifndef _WIN32_WCE +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" + +GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100) + +namespace testing { + +// To implement an action Foo, define: +// 1. a class FooAction that implements the ActionInterface interface, and +// 2. a factory function that creates an Action object from a +// const FooAction*. +// +// The two-level delegation design follows that of Matcher, providing +// consistency for extension developers. It also eases ownership +// management as Action objects can now be copied like plain values. + +namespace internal { + +// BuiltInDefaultValueGetter::Get() returns a +// default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. +// +// This primary template is used when kDefaultConstructible is true. +template +struct BuiltInDefaultValueGetter { + static T Get() { return T(); } +}; +template +struct BuiltInDefaultValueGetter { + static T Get() { + Assert(false, __FILE__, __LINE__, + "Default action undefined for the function return type."); + return internal::Invalid(); + // The above statement will never be reached, but is required in + // order for this function to compile. + } +}; + +// BuiltInDefaultValue::Get() returns the "built-in" default value +// for type T, which is NULL when T is a raw pointer type, 0 when T is +// a numeric type, false when T is bool, or "" when T is string or +// std::string. In addition, in C++11 and above, it turns a +// default-constructed T value if T is default constructible. For any +// other type T, the built-in default T value is undefined, and the +// function will abort the process. +template +class BuiltInDefaultValue { + public: + // This function returns true if and only if type T has a built-in default + // value. + static bool Exists() { return ::std::is_default_constructible::value; } + + static T Get() { + return BuiltInDefaultValueGetter< + T, ::std::is_default_constructible::value>::Get(); + } +}; + +// This partial specialization says that we use the same built-in +// default value for T and const T. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return BuiltInDefaultValue::Exists(); } + static T Get() { return BuiltInDefaultValue::Get(); } +}; + +// This partial specialization defines the default values for pointer +// types. +template +class BuiltInDefaultValue { + public: + static bool Exists() { return true; } + static T* Get() { return nullptr; } +}; + +// The following specializations define the default values for +// specific types we care about. +#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ + template <> \ + class BuiltInDefaultValue { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ + } + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); + +// There's no need for a default action for signed wchar_t, as that +// type is the same as wchar_t for gcc, and invalid for MSVC. +// +// There's also no need for a default action for unsigned wchar_t, as +// that type is the same as unsigned int for gcc, and invalid for +// MSVC. +#if GMOCK_WCHAR_T_IS_NATIVE_ +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT +#endif + +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); +GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); + +#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ + +// Partial implementations of metaprogramming types from the standard library +// not available in C++11. + +template +struct negation + // NOLINTNEXTLINE + : std::integral_constant {}; + +// Base case: with zero predicates the answer is always true. +template +struct conjunction : std::true_type {}; + +// With a single predicate, the answer is that predicate. +template +struct conjunction : P1 {}; + +// With multiple predicates the answer is the first predicate if that is false, +// and we recurse otherwise. +template +struct conjunction + : std::conditional, P1>::type {}; + +template +struct disjunction : std::false_type {}; + +template +struct disjunction : P1 {}; + +template +struct disjunction + // NOLINTNEXTLINE + : std::conditional, P1>::type {}; + +template +using void_t = void; + +// Detects whether an expression of type `From` can be implicitly converted to +// `To` according to [conv]. In C++17, [conv]/3 defines this as follows: +// +// An expression e can be implicitly converted to a type T if and only if +// the declaration T t=e; is well-formed, for some invented temporary +// variable t ([dcl.init]). +// +// [conv]/2 implies we can use function argument passing to detect whether this +// initialization is valid. +// +// Note that this is distinct from is_convertible, which requires this be valid: +// +// To test() { +// return declval(); +// } +// +// In particular, is_convertible doesn't give the correct answer when `To` and +// `From` are the same non-moveable type since `declval` will be an rvalue +// reference, defeating the guaranteed copy elision that would otherwise make +// this function work. +// +// REQUIRES: `From` is not cv void. +template +struct is_implicitly_convertible { + private: + // A function that accepts a parameter of type T. This can be called with type + // U successfully only if U is implicitly convertible to T. + template + static void Accept(T); + + // A function that creates a value of type T. + template + static T Make(); + + // An overload be selected when implicit conversion from T to To is possible. + template (Make()))> + static std::true_type TestImplicitConversion(int); + + // A fallback overload selected in all other cases. + template + static std::false_type TestImplicitConversion(...); + + public: + using type = decltype(TestImplicitConversion(0)); + static constexpr bool value = type::value; +}; + +// Like std::invoke_result_t from C++17, but works only for objects with call +// operators (not e.g. member function pointers, which we don't need specific +// support for in OnceAction because std::function deals with them). +template +using call_result_t = decltype(std::declval()(std::declval()...)); + +template +struct is_callable_r_impl : std::false_type {}; + +// Specialize the struct for those template arguments where call_result_t is +// well-formed. When it's not, the generic template above is chosen, resulting +// in std::false_type. +template +struct is_callable_r_impl>, R, F, Args...> + : std::conditional< + std::is_void::value, // + std::true_type, // + is_implicitly_convertible, R>>::type {}; + +// Like std::is_invocable_r from C++17, but works only for objects with call +// operators. See the note on call_result_t. +template +using is_callable_r = is_callable_r_impl; + +// Like std::as_const from C++17. +template +typename std::add_const::type& as_const(T& t) { + return t; +} + +} // namespace internal + +// Specialized for function types below. +template +class OnceAction; + +// An action that can only be used once. +// +// This is accepted by WillOnce, which doesn't require the underlying action to +// be copy-constructible (only move-constructible), and promises to invoke it as +// an rvalue reference. This allows the action to work with move-only types like +// std::move_only_function in a type-safe manner. +// +// For example: +// +// // Assume we have some API that needs to accept a unique pointer to some +// // non-copyable object Foo. +// void AcceptUniquePointer(std::unique_ptr foo); +// +// // We can define an action that provides a Foo to that API. Because It +// // has to give away its unique pointer, it must not be called more than +// // once, so its call operator is &&-qualified. +// struct ProvideFoo { +// std::unique_ptr foo; +// +// void operator()() && { +// AcceptUniquePointer(std::move(Foo)); +// } +// }; +// +// // This action can be used with WillOnce. +// EXPECT_CALL(mock, Call) +// .WillOnce(ProvideFoo{std::make_unique(...)}); +// +// // But a call to WillRepeatedly will fail to compile. This is correct, +// // since the action cannot correctly be used repeatedly. +// EXPECT_CALL(mock, Call) +// .WillRepeatedly(ProvideFoo{std::make_unique(...)}); +// +// A less-contrived example would be an action that returns an arbitrary type, +// whose &&-qualified call operator is capable of dealing with move-only types. +template +class OnceAction final { + private: + // True iff we can use the given callable type (or lvalue reference) directly + // via StdFunctionAdaptor. + template + using IsDirectlyCompatible = internal::conjunction< + // It must be possible to capture the callable in StdFunctionAdaptor. + std::is_constructible::type, Callable>, + // The callable must be compatible with our signature. + internal::is_callable_r::type, + Args...>>; + + // True iff we can use the given callable type via StdFunctionAdaptor once we + // ignore incoming arguments. + template + using IsCompatibleAfterIgnoringArguments = internal::conjunction< + // It must be possible to capture the callable in a lambda. + std::is_constructible::type, Callable>, + // The callable must be invocable with zero arguments, returning something + // convertible to Result. + internal::is_callable_r::type>>; + + public: + // Construct from a callable that is directly compatible with our mocked + // signature: it accepts our function type's arguments and returns something + // convertible to our result type. + template ::type>>, + IsDirectlyCompatible> // + ::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + : function_(StdFunctionAdaptor::type>( + {}, std::forward(callable))) {} + + // As above, but for a callable that ignores the mocked function's arguments. + template ::type>>, + // Exclude callables for which the overload above works. + // We'd rather provide the arguments if possible. + internal::negation>, + IsCompatibleAfterIgnoringArguments>::value, + int>::type = 0> + OnceAction(Callable&& callable) // NOLINT + // Call the constructor above with a callable + // that ignores the input arguments. + : OnceAction(IgnoreIncomingArguments::type>{ + std::forward(callable)}) {} + + // We are naturally copyable because we store only an std::function, but + // semantically we should not be copyable. + OnceAction(const OnceAction&) = delete; + OnceAction& operator=(const OnceAction&) = delete; + OnceAction(OnceAction&&) = default; + + // Invoke the underlying action callable with which we were constructed, + // handing it the supplied arguments. + Result Call(Args... args) && { + return function_(std::forward(args)...); + } + + private: + // An adaptor that wraps a callable that is compatible with our signature and + // being invoked as an rvalue reference so that it can be used as an + // StdFunctionAdaptor. This throws away type safety, but that's fine because + // this is only used by WillOnce, which we know calls at most once. + // + // Once we have something like std::move_only_function from C++23, we can do + // away with this. + template + class StdFunctionAdaptor final { + public: + // A tag indicating that the (otherwise universal) constructor is accepting + // the callable itself, instead of e.g. stealing calls for the move + // constructor. + struct CallableTag final {}; + + template + explicit StdFunctionAdaptor(CallableTag, F&& callable) + : callable_(std::make_shared(std::forward(callable))) {} + + // Rather than explicitly returning Result, we return whatever the wrapped + // callable returns. This allows for compatibility with existing uses like + // the following, when the mocked function returns void: + // + // EXPECT_CALL(mock_fn_, Call) + // .WillOnce([&] { + // [...] + // return 0; + // }); + // + // Such a callable can be turned into std::function. If we use an + // explicit return type of Result here then it *doesn't* work with + // std::function, because we'll get a "void function should not return a + // value" error. + // + // We need not worry about incompatible result types because the SFINAE on + // OnceAction already checks this for us. std::is_invocable_r_v itself makes + // the same allowance for void result types. + template + internal::call_result_t operator()( + ArgRefs&&... args) const { + return std::move(*callable_)(std::forward(args)...); + } + + private: + // We must put the callable on the heap so that we are copyable, which + // std::function needs. + std::shared_ptr callable_; + }; + + // An adaptor that makes a callable that accepts zero arguments callable with + // our mocked arguments. + template + struct IgnoreIncomingArguments { + internal::call_result_t operator()(Args&&...) { + return std::move(callable)(); + } + + Callable callable; + }; + + std::function function_; +}; + +// When an unexpected function call is encountered, Google Mock will +// let it return a default value if the user has specified one for its +// return type, or if the return type has a built-in default value; +// otherwise Google Mock won't know what value to return and will have +// to abort the process. +// +// The DefaultValue class allows a user to specify the +// default value for a type T that is both copyable and publicly +// destructible (i.e. anything that can be used as a function return +// type). The usage is: +// +// // Sets the default value for type T to be foo. +// DefaultValue::Set(foo); +template +class DefaultValue { + public: + // Sets the default value for type T; requires T to be + // copy-constructable and have a public destructor. + static void Set(T x) { + delete producer_; + producer_ = new FixedValueProducer(x); + } + + // Provides a factory function to be called to generate the default value. + // This method can be used even if T is only move-constructible, but it is not + // limited to that case. + typedef T (*FactoryFunction)(); + static void SetFactory(FactoryFunction factory) { + delete producer_; + producer_ = new FactoryValueProducer(factory); + } + + // Unsets the default value for type T. + static void Clear() { + delete producer_; + producer_ = nullptr; + } + + // Returns true if and only if the user has set the default value for type T. + static bool IsSet() { return producer_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T if the user has set one; + // otherwise returns the built-in default value. Requires that Exists() + // is true, which ensures that the return value is well-defined. + static T Get() { + return producer_ == nullptr ? internal::BuiltInDefaultValue::Get() + : producer_->Produce(); + } + + private: + class ValueProducer { + public: + virtual ~ValueProducer() {} + virtual T Produce() = 0; + }; + + class FixedValueProducer : public ValueProducer { + public: + explicit FixedValueProducer(T value) : value_(value) {} + T Produce() override { return value_; } + + private: + const T value_; + FixedValueProducer(const FixedValueProducer&) = delete; + FixedValueProducer& operator=(const FixedValueProducer&) = delete; + }; + + class FactoryValueProducer : public ValueProducer { + public: + explicit FactoryValueProducer(FactoryFunction factory) + : factory_(factory) {} + T Produce() override { return factory_(); } + + private: + const FactoryFunction factory_; + FactoryValueProducer(const FactoryValueProducer&) = delete; + FactoryValueProducer& operator=(const FactoryValueProducer&) = delete; + }; + + static ValueProducer* producer_; +}; + +// This partial specialization allows a user to set default values for +// reference types. +template +class DefaultValue { + public: + // Sets the default value for type T&. + static void Set(T& x) { // NOLINT + address_ = &x; + } + + // Unsets the default value for type T&. + static void Clear() { address_ = nullptr; } + + // Returns true if and only if the user has set the default value for type T&. + static bool IsSet() { return address_ != nullptr; } + + // Returns true if T has a default return value set by the user or there + // exists a built-in default value. + static bool Exists() { + return IsSet() || internal::BuiltInDefaultValue::Exists(); + } + + // Returns the default value for type T& if the user has set one; + // otherwise returns the built-in default value if there is one; + // otherwise aborts the process. + static T& Get() { + return address_ == nullptr ? internal::BuiltInDefaultValue::Get() + : *address_; + } + + private: + static T* address_; +}; + +// This specialization allows DefaultValue::Get() to +// compile. +template <> +class DefaultValue { + public: + static bool Exists() { return true; } + static void Get() {} +}; + +// Points to the user-set default value for type T. +template +typename DefaultValue::ValueProducer* DefaultValue::producer_ = nullptr; + +// Points to the user-set default value for type T&. +template +T* DefaultValue::address_ = nullptr; + +// Implement this interface to define an action for function type F. +template +class ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + ActionInterface() {} + virtual ~ActionInterface() {} + + // Performs the action. This method is not const, as in general an + // action can have side effects and be stateful. For example, a + // get-the-next-element-from-the-collection action will need to + // remember the current element. + virtual Result Perform(const ArgumentTuple& args) = 0; + + private: + ActionInterface(const ActionInterface&) = delete; + ActionInterface& operator=(const ActionInterface&) = delete; +}; + +template +class Action; + +// An Action is a copyable and IMMUTABLE (except by assignment) +// object that represents an action to be taken when a mock function of type +// R(Args...) is called. The implementation of Action is just a +// std::shared_ptr to const ActionInterface. Don't inherit from Action! You +// can view an object implementing ActionInterface as a concrete action +// (including its current state), and an Action object as a handle to it. +template +class Action { + private: + using F = R(Args...); + + // Adapter class to allow constructing Action from a legacy ActionInterface. + // New code should create Actions from functors instead. + struct ActionAdapter { + // Adapter must be copyable to satisfy std::function requirements. + ::std::shared_ptr> impl_; + + template + typename internal::Function::Result operator()(InArgs&&... args) { + return impl_->Perform( + ::std::forward_as_tuple(::std::forward(args)...)); + } + }; + + template + using IsCompatibleFunctor = std::is_constructible, G>; + + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + // Constructs a null Action. Needed for storing Action objects in + // STL containers. + Action() {} + + // Construct an Action from a specified callable. + // This cannot take std::function directly, because then Action would not be + // directly constructible from lambda (it would require two conversions). + template < + typename G, + typename = typename std::enable_if, std::is_constructible, + G>>::value>::type> + Action(G&& fun) { // NOLINT + Init(::std::forward(fun), IsCompatibleFunctor()); + } + + // Constructs an Action from its implementation. + explicit Action(ActionInterface* impl) + : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} + + // This constructor allows us to turn an Action object into an + // Action, as long as F's arguments can be implicitly converted + // to Func's and Func's return type can be implicitly converted to F's. + template + Action(const Action& action) // NOLINT + : fun_(action.fun_) {} + + // Returns true if and only if this is the DoDefault() action. + bool IsDoDefault() const { return fun_ == nullptr; } + + // Performs the action. Note that this method is const even though + // the corresponding method in ActionInterface is not. The reason + // is that a const Action means that it cannot be re-bound to + // another concrete action, not that the concrete action it binds to + // cannot change state. (Think of the difference between a const + // pointer and a pointer to const.) + Result Perform(ArgumentTuple args) const { + if (IsDoDefault()) { + internal::IllegalDoDefault(__FILE__, __LINE__); + } + return internal::Apply(fun_, ::std::move(args)); + } + + // An action can be used as a OnceAction, since it's obviously safe to call it + // once. + operator OnceAction() const { // NOLINT + // Return a OnceAction-compatible callable that calls Perform with the + // arguments it is provided. We could instead just return fun_, but then + // we'd need to handle the IsDoDefault() case separately. + struct OA { + Action action; + + R operator()(Args... args) && { + return action.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{*this}; + } + + private: + template + friend class Action; + + template + void Init(G&& g, ::std::true_type) { + fun_ = ::std::forward(g); + } + + template + void Init(G&& g, ::std::false_type) { + fun_ = IgnoreArgs::type>{::std::forward(g)}; + } + + template + struct IgnoreArgs { + template + Result operator()(const InArgs&...) const { + return function_impl(); + } + + FunctionImpl function_impl; + }; + + // fun_ is an empty function if and only if this is the DoDefault() action. + ::std::function fun_; +}; + +// The PolymorphicAction class template makes it easy to implement a +// polymorphic action (i.e. an action that can be used in mock +// functions of than one type, e.g. Return()). +// +// To define a polymorphic action, a user first provides a COPYABLE +// implementation class that has a Perform() method template: +// +// class FooAction { +// public: +// template +// Result Perform(const ArgumentTuple& args) const { +// // Processes the arguments and returns a result, using +// // std::get(args) to get the N-th (0-based) argument in the tuple. +// } +// ... +// }; +// +// Then the user creates the polymorphic action using +// MakePolymorphicAction(object) where object has type FooAction. See +// the definition of Return(void) and SetArgumentPointee(value) for +// complete examples. +template +class PolymorphicAction { + public: + explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} + + template + operator Action() const { + return Action(new MonomorphicImpl(impl_)); + } + + private: + template + class MonomorphicImpl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} + + Result Perform(const ArgumentTuple& args) override { + return impl_.template Perform(args); + } + + private: + Impl impl_; + }; + + Impl impl_; +}; + +// Creates an Action from its implementation and returns it. The +// created Action object owns the implementation. +template +Action MakeAction(ActionInterface* impl) { + return Action(impl); +} + +// Creates a polymorphic action from its implementation. This is +// easier to use than the PolymorphicAction constructor as it +// doesn't require you to explicitly write the template argument, e.g. +// +// MakePolymorphicAction(foo); +// vs +// PolymorphicAction(foo); +template +inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { + return PolymorphicAction(impl); +} + +namespace internal { + +// Helper struct to specialize ReturnAction to execute a move instead of a copy +// on return. Useful for move-only types, but could be used on any type. +template +struct ByMoveWrapper { + explicit ByMoveWrapper(T value) : payload(std::move(value)) {} + T payload; +}; + +// The general implementation of Return(R). Specializations follow below. +template +class ReturnAction final { + public: + explicit ReturnAction(R value) : value_(std::move(value)) {} + + template >, // + negation>, // + std::is_convertible, // + std::is_move_constructible>::value>::type> + operator OnceAction() && { // NOLINT + return Impl(std::move(value_)); + } + + template >, // + negation>, // + std::is_convertible, // + std::is_copy_constructible>::value>::type> + operator Action() const { // NOLINT + return Impl(value_); + } + + private: + // Implements the Return(x) action for a mock function that returns type U. + template + class Impl final { + public: + // The constructor used when the return value is allowed to move from the + // input value (i.e. we are converting to OnceAction). + explicit Impl(R&& input_value) + : state_(new State(std::move(input_value))) {} + + // The constructor used when the return value is not allowed to move from + // the input value (i.e. we are converting to Action). + explicit Impl(const R& input_value) : state_(new State(input_value)) {} + + U operator()() && { return std::move(state_->value); } + U operator()() const& { return state_->value; } + + private: + // We put our state on the heap so that the compiler-generated copy/move + // constructors work correctly even when U is a reference-like type. This is + // necessary only because we eagerly create State::value (see the note on + // that symbol for details). If we instead had only the input value as a + // member then the default constructors would work fine. + // + // For example, when R is std::string and U is std::string_view, value is a + // reference to the string backed by input_value. The copy constructor would + // copy both, so that we wind up with a new input_value object (with the + // same contents) and a reference to the *old* input_value object rather + // than the new one. + struct State { + explicit State(const R& input_value_in) + : input_value(input_value_in), + // Make an implicit conversion to Result before initializing the U + // object we store, avoiding calling any explicit constructor of U + // from R. + // + // This simulates the language rules: a function with return type U + // that does `return R()` requires R to be implicitly convertible to + // U, and uses that path for the conversion, even U Result has an + // explicit constructor from R. + value(ImplicitCast_(internal::as_const(input_value))) {} + + // As above, but for the case where we're moving from the ReturnAction + // object because it's being used as a OnceAction. + explicit State(R&& input_value_in) + : input_value(std::move(input_value_in)), + // For the same reason as above we make an implicit conversion to U + // before initializing the value. + // + // Unlike above we provide the input value as an rvalue to the + // implicit conversion because this is a OnceAction: it's fine if it + // wants to consume the input value. + value(ImplicitCast_(std::move(input_value))) {} + + // A copy of the value originally provided by the user. We retain this in + // addition to the value of the mock function's result type below in case + // the latter is a reference-like type. See the std::string_view example + // in the documentation on Return. + R input_value; + + // The value we actually return, as the type returned by the mock function + // itself. + // + // We eagerly initialize this here, rather than lazily doing the implicit + // conversion automatically each time Perform is called, for historical + // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126) + // made the Action conversion operator eagerly convert the R value to + // U, but without keeping the R alive. This broke the use case discussed + // in the documentation for Return, making reference-like types such as + // std::string_view not safe to use as U where the input type R is a + // value-like type such as std::string. + // + // The example the commit gave was not very clear, nor was the issue + // thread (https://github.com/google/googlemock/issues/86), but it seems + // the worry was about reference-like input types R that flatten to a + // value-like type U when being implicitly converted. An example of this + // is std::vector::reference, which is often a proxy type with an + // reference to the underlying vector: + // + // // Helper method: have the mock function return bools according + // // to the supplied script. + // void SetActions(MockFunction& mock, + // const std::vector& script) { + // for (size_t i = 0; i < script.size(); ++i) { + // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i])); + // } + // } + // + // TEST(Foo, Bar) { + // // Set actions using a temporary vector, whose operator[] + // // returns proxy objects that references that will be + // // dangling once the call to SetActions finishes and the + // // vector is destroyed. + // MockFunction mock; + // SetActions(mock, {false, true}); + // + // EXPECT_FALSE(mock.AsStdFunction()(0)); + // EXPECT_TRUE(mock.AsStdFunction()(1)); + // } + // + // This eager conversion helps with a simple case like this, but doesn't + // fully make these types work in general. For example the following still + // uses a dangling reference: + // + // TEST(Foo, Baz) { + // MockFunction()> mock; + // + // // Return the same vector twice, and then the empty vector + // // thereafter. + // auto action = Return(std::initializer_list{ + // "taco", "burrito", + // }); + // + // EXPECT_CALL(mock, Call) + // .WillOnce(action) + // .WillOnce(action) + // .WillRepeatedly(Return(std::vector{})); + // + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), + // ElementsAre("taco", "burrito")); + // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty()); + // } + // + U value; + }; + + const std::shared_ptr state_; + }; + + R value_; +}; + +// A specialization of ReturnAction when R is ByMoveWrapper for some T. +// +// This version applies the type system-defeating hack of moving from T even in +// the const call operator, checking at runtime that it isn't called more than +// once, since the user has declared their intent to do so by using ByMove. +template +class ReturnAction> final { + public: + explicit ReturnAction(ByMoveWrapper wrapper) + : state_(new State(std::move(wrapper.payload))) {} + + T operator()() const { + GTEST_CHECK_(!state_->called) + << "A ByMove() action must be performed at most once."; + + state_->called = true; + return std::move(state_->value); + } + + private: + // We store our state on the heap so that we are copyable as required by + // Action, despite the fact that we are stateful and T may not be copyable. + struct State { + explicit State(T&& value_in) : value(std::move(value_in)) {} + + T value; + bool called = false; + }; + + const std::shared_ptr state_; +}; + +// Implements the ReturnNull() action. +class ReturnNullAction { + public: + // Allows ReturnNull() to be used in any pointer-returning function. In C++11 + // this is enforced by returning nullptr, and in non-C++11 by asserting a + // pointer type on compile time. + template + static Result Perform(const ArgumentTuple&) { + return nullptr; + } +}; + +// Implements the Return() action. +class ReturnVoidAction { + public: + // Allows Return() to be used in any void-returning function. + template + static void Perform(const ArgumentTuple&) { + static_assert(std::is_void::value, "Result should be void."); + } +}; + +// Implements the polymorphic ReturnRef(x) action, which can be used +// in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefAction { + public: + // Constructs a ReturnRefAction object from the reference to be returned. + explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT + + // This template type conversion operator allows ReturnRef(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRef(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRef to return a value"); + return Action(new Impl(ref_)); + } + + private: + // Implements the ReturnRef(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(T& ref) : ref_(ref) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return ref_; } + + private: + T& ref_; + }; + + T& ref_; +}; + +// Implements the polymorphic ReturnRefOfCopy(x) action, which can be +// used in any function that returns a reference to the type of x, +// regardless of the argument types. +template +class ReturnRefOfCopyAction { + public: + // Constructs a ReturnRefOfCopyAction object from the reference to + // be returned. + explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT + + // This template type conversion operator allows ReturnRefOfCopy(x) to be + // used in ANY function that returns a reference to x's type. + template + operator Action() const { + typedef typename Function::Result Result; + // Asserts that the function return type is a reference. This + // catches the user error of using ReturnRefOfCopy(x) when Return(x) + // should be used, and generates some helpful error message. + static_assert(std::is_reference::value, + "use Return instead of ReturnRefOfCopy to return a value"); + return Action(new Impl(value_)); + } + + private: + // Implements the ReturnRefOfCopy(x) action for a particular function type F. + template + class Impl : public ActionInterface { + public: + typedef typename Function::Result Result; + typedef typename Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const T& value) : value_(value) {} // NOLINT + + Result Perform(const ArgumentTuple&) override { return value_; } + + private: + T value_; + }; + + const T value_; +}; + +// Implements the polymorphic ReturnRoundRobin(v) action, which can be +// used in any function that returns the element_type of v. +template +class ReturnRoundRobinAction { + public: + explicit ReturnRoundRobinAction(std::vector values) { + GTEST_CHECK_(!values.empty()) + << "ReturnRoundRobin requires at least one element."; + state_->values = std::move(values); + } + + template + T operator()(Args&&...) const { + return state_->Next(); + } + + private: + struct State { + T Next() { + T ret_val = values[i++]; + if (i == values.size()) i = 0; + return ret_val; + } + + std::vector values; + size_t i = 0; + }; + std::shared_ptr state_ = std::make_shared(); +}; + +// Implements the polymorphic DoDefault() action. +class DoDefaultAction { + public: + // This template type conversion operator allows DoDefault() to be + // used in any function. + template + operator Action() const { + return Action(); + } // NOLINT +}; + +// Implements the Assign action to set a given pointer referent to a +// particular value. +template +class AssignAction { + public: + AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} + + template + void Perform(const ArgumentTuple& /* args */) const { + *ptr_ = value_; + } + + private: + T1* const ptr_; + const T2 value_; +}; + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Implements the SetErrnoAndReturn action to simulate return from +// various system calls and libc functions. +template +class SetErrnoAndReturnAction { + public: + SetErrnoAndReturnAction(int errno_value, T result) + : errno_(errno_value), result_(result) {} + template + Result Perform(const ArgumentTuple& /* args */) const { + errno = errno_; + return result_; + } + + private: + const int errno_; + const T result_; +}; + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Implements the SetArgumentPointee(x) action for any function +// whose N-th argument (0-based) is a pointer to x's type. +template +struct SetArgumentPointeeAction { + A value; + + template + void operator()(const Args&... args) const { + *::std::get(std::tie(args...)) = value; + } +}; + +// Implements the Invoke(object_ptr, &Class::Method) action. +template +struct InvokeMethodAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + template + auto operator()(Args&&... args) const + -> decltype((obj_ptr->*method_ptr)(std::forward(args)...)) { + return (obj_ptr->*method_ptr)(std::forward(args)...); + } +}; + +// Implements the InvokeWithoutArgs(f) action. The template argument +// FunctionImpl is the implementation type of f, which can be either a +// function pointer or a functor. InvokeWithoutArgs(f) can be used as an +// Action as long as f's type is compatible with F. +template +struct InvokeWithoutArgsAction { + FunctionImpl function_impl; + + // Allows InvokeWithoutArgs(f) to be used as any action whose type is + // compatible with f. + template + auto operator()(const Args&...) -> decltype(function_impl()) { + return function_impl(); + } +}; + +// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. +template +struct InvokeMethodWithoutArgsAction { + Class* const obj_ptr; + const MethodPtr method_ptr; + + using ReturnType = + decltype((std::declval()->*std::declval())()); + + template + ReturnType operator()(const Args&...) const { + return (obj_ptr->*method_ptr)(); + } +}; + +// Implements the IgnoreResult(action) action. +template +class IgnoreResultAction { + public: + explicit IgnoreResultAction(const A& action) : action_(action) {} + + template + operator Action() const { + // Assert statement belongs here because this is the best place to verify + // conditions on F. It produces the clearest error messages + // in most compilers. + // Impl really belongs in this scope as a local class but can't + // because MSVC produces duplicate symbols in different translation units + // in this case. Until MS fixes that bug we put Impl into the class scope + // and put the typedef both here (for use in assert statement) and + // in the Impl class. But both definitions must be the same. + typedef typename internal::Function::Result Result; + + // Asserts at compile time that F returns void. + static_assert(std::is_void::value, "Result type should be void."); + + return Action(new Impl(action_)); + } + + private: + template + class Impl : public ActionInterface { + public: + typedef typename internal::Function::Result Result; + typedef typename internal::Function::ArgumentTuple ArgumentTuple; + + explicit Impl(const A& action) : action_(action) {} + + void Perform(const ArgumentTuple& args) override { + // Performs the action and ignores its result. + action_.Perform(args); + } + + private: + // Type OriginalFunction is the same as F except that its return + // type is IgnoredValue. + typedef + typename internal::Function::MakeResultIgnoredValue OriginalFunction; + + const Action action_; + }; + + const A action_; +}; + +template +struct WithArgsAction { + InnerAction inner_action; + + // The signature of the function as seen by the inner action, given an out + // action with the given result and argument types. + template + using InnerSignature = + R(typename std::tuple_element>::type...); + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + struct OA { + OnceAction> inner_action; + + R operator()(Args&&... args) && { + return std::move(inner_action) + .Call(std::get( + std::forward_as_tuple(std::forward(args)...))...); + } + }; + + return OA{std::move(inner_action)}; + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>...)>>::value, + int>::type = 0> + operator Action() const { // NOLINT + Action> converted(inner_action); + + return [converted](Args&&... args) -> R { + return converted.Perform(std::forward_as_tuple( + std::get(std::forward_as_tuple(std::forward(args)...))...)); + }; + } +}; + +template +class DoAllAction; + +// Base case: only a single action. +template +class DoAllAction { + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& action) + : final_action_(std::forward(action)) {} + + // Rather than a call operator, we must define conversion operators to + // particular action types. This is necessary for embedded actions like + // DoDefault(), which rely on an action conversion operators rather than + // providing a call operator because even with a particular set of arguments + // they don't have a fixed return type. + + template >::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + return std::move(final_action_); + } + + template < + typename R, typename... Args, + typename std::enable_if< + std::is_convertible>::value, + int>::type = 0> + operator Action() const { // NOLINT + return final_action_; + } + + private: + FinalAction final_action_; +}; + +// Recursive case: support N actions by calling the initial action and then +// calling through to the base class containing N-1 actions. +template +class DoAllAction + : private DoAllAction { + private: + using Base = DoAllAction; + + // The type of reference that should be provided to an initial action for a + // mocked function parameter of type T. + // + // There are two quirks here: + // + // * Unlike most forwarding functions, we pass scalars through by value. + // This isn't strictly necessary because an lvalue reference would work + // fine too and be consistent with other non-reference types, but it's + // perhaps less surprising. + // + // For example if the mocked function has signature void(int), then it + // might seem surprising for the user's initial action to need to be + // convertible to Action. This is perhaps less + // surprising for a non-scalar type where there may be a performance + // impact, or it might even be impossible, to pass by value. + // + // * More surprisingly, `const T&` is often not a const reference type. + // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to + // U& or U&& for some non-scalar type U, then InitialActionArgType is + // U&. In other words, we may hand over a non-const reference. + // + // So for example, given some non-scalar type Obj we have the following + // mappings: + // + // T InitialActionArgType + // ------- ----------------------- + // Obj const Obj& + // Obj& Obj& + // Obj&& Obj& + // const Obj const Obj& + // const Obj& const Obj& + // const Obj&& const Obj& + // + // In other words, the initial actions get a mutable view of an non-scalar + // argument if and only if the mock function itself accepts a non-const + // reference type. They are never given an rvalue reference to an + // non-scalar type. + // + // This situation makes sense if you imagine use with a matcher that is + // designed to write through a reference. For example, if the caller wants + // to fill in a reference argument and then return a canned value: + // + // EXPECT_CALL(mock, Call) + // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19))); + // + template + using InitialActionArgType = + typename std::conditional::value, T, const T&>::type; + + public: + struct UserConstructorTag {}; + + template + explicit DoAllAction(UserConstructorTag, T&& initial_action, + U&&... other_actions) + : Base({}, std::forward(other_actions)...), + initial_action_(std::forward(initial_action)) {} + + template ...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator OnceAction() && { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + OnceAction...)> initial_action; + OnceAction remaining_actions; + + R operator()(Args... args) && { + std::move(initial_action) + .Call(static_cast>(args)...); + + return std::move(remaining_actions).Call(std::forward(args)...); + } + }; + + return OA{ + std::move(initial_action_), + std::move(static_cast(*this)), + }; + } + + template < + typename R, typename... Args, + typename std::enable_if< + conjunction< + // Both the initial action and the rest must support conversion to + // Action. + std::is_convertible...)>>, + std::is_convertible>>::value, + int>::type = 0> + operator Action() const { // NOLINT + // Return an action that first calls the initial action with arguments + // filtered through InitialActionArgType, then forwards arguments directly + // to the base class to deal with the remaining actions. + struct OA { + Action...)> initial_action; + Action remaining_actions; + + R operator()(Args... args) const { + initial_action.Perform(std::forward_as_tuple( + static_cast>(args)...)); + + return remaining_actions.Perform( + std::forward_as_tuple(std::forward(args)...)); + } + }; + + return OA{ + initial_action_, + static_cast(*this), + }; + } + + private: + InitialAction initial_action_; +}; + +template +struct ReturnNewAction { + T* operator()() const { + return internal::Apply( + [](const Params&... unpacked_params) { + return new T(unpacked_params...); + }, + params); + } + std::tuple params; +}; + +template +struct ReturnArgAction { + template ::type> + auto operator()(Args&&... args) const -> decltype(std::get( + std::forward_as_tuple(std::forward(args)...))) { + return std::get(std::forward_as_tuple(std::forward(args)...)); + } +}; + +template +struct SaveArgAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = std::get(std::tie(args...)); + } +}; + +template +struct SaveArgPointeeAction { + Ptr pointer; + + template + void operator()(const Args&... args) const { + *pointer = *std::get(std::tie(args...)); + } +}; + +template +struct SetArgRefereeAction { + T value; + + template + void operator()(Args&&... args) const { + using argk_type = + typename ::std::tuple_element>::type; + static_assert(std::is_lvalue_reference::value, + "Argument must be a reference type."); + std::get(std::tie(args...)) = value; + } +}; + +template +struct SetArrayArgumentAction { + I1 first; + I2 last; + + template + void operator()(const Args&... args) const { + auto value = std::get(std::tie(args...)); + for (auto it = first; it != last; ++it, (void)++value) { + *value = *it; + } + } +}; + +template +struct DeleteArgAction { + template + void operator()(const Args&... args) const { + delete std::get(std::tie(args...)); + } +}; + +template +struct ReturnPointeeAction { + Ptr pointer; + template + auto operator()(const Args&...) const -> decltype(*pointer) { + return *pointer; + } +}; + +#if GTEST_HAS_EXCEPTIONS +template +struct ThrowAction { + T exception; + // We use a conversion operator to adapt to any return type. + template + operator Action() const { // NOLINT + T copy = exception; + return [copy](Args...) -> R { throw copy; }; + } +}; +#endif // GTEST_HAS_EXCEPTIONS + +} // namespace internal + +// An Unused object can be implicitly constructed from ANY value. +// This is handy when defining actions that ignore some or all of the +// mock function arguments. For example, given +// +// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); +// MOCK_METHOD3(Bar, double(int index, double x, double y)); +// +// instead of +// +// double DistanceToOriginWithLabel(const string& label, double x, double y) { +// return sqrt(x*x + y*y); +// } +// double DistanceToOriginWithIndex(int index, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)) +// .WillOnce(Invoke(DistanceToOriginWithLabel)); +// EXPECT_CALL(mock, Bar(5, _, _)) +// .WillOnce(Invoke(DistanceToOriginWithIndex)); +// +// you could write +// +// // We can declare any uninteresting argument as Unused. +// double DistanceToOrigin(Unused, double x, double y) { +// return sqrt(x*x + y*y); +// } +// ... +// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +typedef internal::IgnoredValue Unused; + +// Creates an action that does actions a1, a2, ..., sequentially in +// each invocation. All but the last action will have a readonly view of the +// arguments. +template +internal::DoAllAction::type...> DoAll( + Action&&... action) { + return internal::DoAllAction::type...>( + {}, std::forward(action)...); +} + +// WithArg(an_action) creates an action that passes the k-th +// (0-based) argument of the mock function to an_action and performs +// it. It adapts an action accepting one argument to one that accepts +// multiple arguments. For convenience, we also provide +// WithArgs(an_action) (defined below) as a synonym. +template +internal::WithArgsAction::type, k> WithArg( + InnerAction&& action) { + return {std::forward(action)}; +} + +// WithArgs(an_action) creates an action that passes +// the selected arguments of the mock function to an_action and +// performs it. It serves as an adaptor between actions with +// different argument lists. +template +internal::WithArgsAction::type, k, ks...> +WithArgs(InnerAction&& action) { + return {std::forward(action)}; +} + +// WithoutArgs(inner_action) can be used in a mock function with a +// non-empty argument list to perform inner_action, which takes no +// argument. In other words, it adapts an action accepting no +// argument to one that accepts (and ignores) arguments. +template +internal::WithArgsAction::type> WithoutArgs( + InnerAction&& action) { + return {std::forward(action)}; +} + +// Creates an action that returns a value. +// +// The returned type can be used with a mock function returning a non-void, +// non-reference type U as follows: +// +// * If R is convertible to U and U is move-constructible, then the action can +// be used with WillOnce. +// +// * If const R& is convertible to U and U is copy-constructible, then the +// action can be used with both WillOnce and WillRepeatedly. +// +// The mock expectation contains the R value from which the U return value is +// constructed (a move/copy of the argument to Return). This means that the R +// value will survive at least until the mock object's expectations are cleared +// or the mock object is destroyed, meaning that U can safely be a +// reference-like type such as std::string_view: +// +// // The mock function returns a view of a copy of the string fed to +// // Return. The view is valid even after the action is performed. +// MockFunction mock; +// EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco"))); +// const std::string_view result = mock.AsStdFunction()(); +// EXPECT_EQ("taco", result); +// +template +internal::ReturnAction Return(R value) { + return internal::ReturnAction(std::move(value)); +} + +// Creates an action that returns NULL. +inline PolymorphicAction ReturnNull() { + return MakePolymorphicAction(internal::ReturnNullAction()); +} + +// Creates an action that returns from a void function. +inline PolymorphicAction Return() { + return MakePolymorphicAction(internal::ReturnVoidAction()); +} + +// Creates an action that returns the reference to a variable. +template +inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT + return internal::ReturnRefAction(x); +} + +// Prevent using ReturnRef on reference to temporary. +template +internal::ReturnRefAction ReturnRef(R&&) = delete; + +// Creates an action that returns the reference to a copy of the +// argument. The copy is created when the action is constructed and +// lives as long as the action. +template +inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { + return internal::ReturnRefOfCopyAction(x); +} + +// DEPRECATED: use Return(x) directly with WillOnce. +// +// Modifies the parent action (a Return() action) to perform a move of the +// argument instead of a copy. +// Return(ByMove()) actions can only be executed once and will assert this +// invariant. +template +internal::ByMoveWrapper ByMove(R x) { + return internal::ByMoveWrapper(std::move(x)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin(std::vector vals) { + return internal::ReturnRoundRobinAction(std::move(vals)); +} + +// Creates an action that returns an element of `vals`. Calling this action will +// repeatedly return the next value from `vals` until it reaches the end and +// will restart from the beginning. +template +internal::ReturnRoundRobinAction ReturnRoundRobin( + std::initializer_list vals) { + return internal::ReturnRoundRobinAction(std::vector(vals)); +} + +// Creates an action that does the default action for the give mock function. +inline internal::DoDefaultAction DoDefault() { + return internal::DoDefaultAction(); +} + +// Creates an action that sets the variable pointed by the N-th +// (0-based) function argument to 'value'. +template +internal::SetArgumentPointeeAction SetArgPointee(T value) { + return {std::move(value)}; +} + +// The following version is DEPRECATED. +template +internal::SetArgumentPointeeAction SetArgumentPointee(T value) { + return {std::move(value)}; +} + +// Creates an action that sets a pointer referent to a given value. +template +PolymorphicAction> Assign(T1* ptr, T2 val) { + return MakePolymorphicAction(internal::AssignAction(ptr, val)); +} + +#ifndef GTEST_OS_WINDOWS_MOBILE + +// Creates an action that sets errno and returns the appropriate error. +template +PolymorphicAction> SetErrnoAndReturn( + int errval, T result) { + return MakePolymorphicAction( + internal::SetErrnoAndReturnAction(errval, result)); +} + +#endif // !GTEST_OS_WINDOWS_MOBILE + +// Various overloads for Invoke(). + +// Legacy function. +// Actions can now be implicitly constructed from callables. No need to create +// wrapper objects. +// This function exists for backwards compatibility. +template +typename std::decay::type Invoke(FunctionImpl&& function_impl) { + return std::forward(function_impl); +} + +// Creates an action that invokes the given method on the given object +// with the mock function's arguments. +template +internal::InvokeMethodAction Invoke(Class* obj_ptr, + MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that invokes 'function_impl' with no argument. +template +internal::InvokeWithoutArgsAction::type> +InvokeWithoutArgs(FunctionImpl function_impl) { + return {std::move(function_impl)}; +} + +// Creates an action that invokes the given method on the given object +// with no argument. +template +internal::InvokeMethodWithoutArgsAction InvokeWithoutArgs( + Class* obj_ptr, MethodPtr method_ptr) { + return {obj_ptr, method_ptr}; +} + +// Creates an action that performs an_action and throws away its +// result. In other words, it changes the return type of an_action to +// void. an_action MUST NOT return void, or the code won't compile. +template +inline internal::IgnoreResultAction IgnoreResult(const A& an_action) { + return internal::IgnoreResultAction(an_action); +} + +// Creates a reference wrapper for the given L-value. If necessary, +// you can explicitly specify the type of the reference. For example, +// suppose 'derived' is an object of type Derived, ByRef(derived) +// would wrap a Derived&. If you want to wrap a const Base& instead, +// where Base is a base class of Derived, just write: +// +// ByRef(derived) +// +// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. +// However, it may still be used for consistency with ByMove(). +template +inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT + return ::std::reference_wrapper(l_value); +} + +// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new +// instance of type T, constructed on the heap with constructor arguments +// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. +template +internal::ReturnNewAction::type...> ReturnNew( + Params&&... params) { + return {std::forward_as_tuple(std::forward(params)...)}; +} + +// Action ReturnArg() returns the k-th argument of the mock function. +template +internal::ReturnArgAction ReturnArg() { + return {}; +} + +// Action SaveArg(pointer) saves the k-th (0-based) argument of the +// mock function to *pointer. +template +internal::SaveArgAction SaveArg(Ptr pointer) { + return {pointer}; +} + +// Action SaveArgPointee(pointer) saves the value pointed to +// by the k-th (0-based) argument of the mock function to *pointer. +template +internal::SaveArgPointeeAction SaveArgPointee(Ptr pointer) { + return {pointer}; +} + +// Action SetArgReferee(value) assigns 'value' to the variable +// referenced by the k-th (0-based) argument of the mock function. +template +internal::SetArgRefereeAction::type> SetArgReferee( + T&& value) { + return {std::forward(value)}; +} + +// Action SetArrayArgument(first, last) copies the elements in +// source range [first, last) to the array pointed to by the k-th +// (0-based) argument, which can be either a pointer or an +// iterator. The action does not take ownership of the elements in the +// source range. +template +internal::SetArrayArgumentAction SetArrayArgument(I1 first, + I2 last) { + return {first, last}; +} + +// Action DeleteArg() deletes the k-th (0-based) argument of the mock +// function. +template +internal::DeleteArgAction DeleteArg() { + return {}; +} + +// This action returns the value pointed to by 'pointer'. +template +internal::ReturnPointeeAction ReturnPointee(Ptr pointer) { + return {pointer}; +} + +// Action Throw(exception) can be used in a mock function of any type +// to throw the given exception. Any copyable value can be thrown. +#if GTEST_HAS_EXCEPTIONS +template +internal::ThrowAction::type> Throw(T&& exception) { + return {std::forward(exception)}; +} +#endif // GTEST_HAS_EXCEPTIONS + +namespace internal { + +// A macro from the ACTION* family (defined later in gmock-generated-actions.h) +// defines an action that can be used in a mock function. Typically, +// these actions only care about a subset of the arguments of the mock +// function. For example, if such an action only uses the second +// argument, it can be used in any mock function that takes >= 2 +// arguments where the type of the second argument is compatible. +// +// Therefore, the action implementation must be prepared to take more +// arguments than it needs. The ExcessiveArg type is used to +// represent those excessive arguments. In order to keep the compiler +// error messages tractable, we define it in the testing namespace +// instead of testing::internal. However, this is an INTERNAL TYPE +// and subject to change without notice, so a user MUST NOT USE THIS +// TYPE DIRECTLY. +struct ExcessiveArg {}; + +// Builds an implementation of an Action<> for some particular signature, using +// a class defined by an ACTION* macro. +template +struct ActionImpl; + +template +struct ImplBase { + struct Holder { + // Allows each copy of the Action<> to get to the Impl. + explicit operator const Impl&() const { return *ptr; } + std::shared_ptr ptr; + }; + using type = typename std::conditional::value, + Impl, Holder>::type; +}; + +template +struct ActionImpl : ImplBase::type { + using Base = typename ImplBase::type; + using function_type = R(Args...); + using args_type = std::tuple; + + ActionImpl() = default; // Only defined if appropriate for Base. + explicit ActionImpl(std::shared_ptr impl) : Base{std::move(impl)} {} + + R operator()(Args&&... arg) const { + static constexpr size_t kMaxArgs = + sizeof...(Args) <= 10 ? sizeof...(Args) : 10; + return Apply(MakeIndexSequence{}, + MakeIndexSequence<10 - kMaxArgs>{}, + args_type{std::forward(arg)...}); + } + + template + R Apply(IndexSequence, IndexSequence, + const args_type& args) const { + // Impl need not be specific to the signature of action being implemented; + // only the implementing function body needs to have all of the specific + // types instantiated. Up to 10 of the args that are provided by the + // args_type get passed, followed by a dummy of unspecified type for the + // remainder up to 10 explicit args. + static constexpr ExcessiveArg kExcessArg{}; + return static_cast(*this) + .template gmock_PerformImpl< + /*function_type=*/function_type, /*return_type=*/R, + /*args_type=*/args_type, + /*argN_type=*/ + typename std::tuple_element::type...>( + /*args=*/args, std::get(args)..., + ((void)excess_id, kExcessArg)...); + } +}; + +// Stores a default-constructed Impl as part of the Action<>'s +// std::function<>. The Impl should be trivial to copy. +template +::testing::Action MakeAction() { + return ::testing::Action(ActionImpl()); +} + +// Stores just the one given instance of Impl. +template +::testing::Action MakeAction(std::shared_ptr impl) { + return ::testing::Action(ActionImpl(std::move(impl))); +} + +#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \ + , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_ +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ + const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_ARG_UNUSED, , 10) + +#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \ + const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10) + +#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type +#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \ + GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10)) + +#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type +#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type +#define GMOCK_ACTION_TYPE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params)) + +#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \ + , param##_type gmock_p##i +#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \ + , std::forward(gmock_p##i) +#define GMOCK_ACTION_GVALUE_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params)) + +#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \ + , param(::std::forward(gmock_p##i)) +#define GMOCK_ACTION_INIT_PARAMS_(params) \ + GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params)) + +#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param; +#define GMOCK_ACTION_FIELD_PARAMS_(params) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params) + +#define GMOCK_INTERNAL_ACTION(name, full_name, params) \ + template \ + class full_name { \ + public: \ + explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : impl_(std::make_shared( \ + GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \ + full_name(const full_name&) = default; \ + full_name(full_name&&) noexcept = default; \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(impl_); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \ + : GMOCK_ACTION_INIT_PARAMS_(params) {} \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + GMOCK_ACTION_FIELD_PARAMS_(params) \ + }; \ + std::shared_ptr impl_; \ + }; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \ + template \ + inline full_name name( \ + GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \ + return full_name( \ + GMOCK_ACTION_GVALUE_PARAMS_(params)); \ + } \ + template \ + template \ + return_type \ + full_name::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +} // namespace internal + +// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored. +#define ACTION(name) \ + class name##Action { \ + public: \ + explicit name##Action() noexcept {} \ + name##Action(const name##Action&) noexcept {} \ + template \ + operator ::testing::Action() const { \ + return ::testing::internal::MakeAction(); \ + } \ + \ + private: \ + class gmock_Impl { \ + public: \ + template \ + return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \ + }; \ + }; \ + inline name##Action name() GTEST_MUST_USE_RESULT_; \ + inline name##Action name() { return name##Action(); } \ + template \ + return_type name##Action::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__)) + +#define ACTION_P2(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__)) + +#define ACTION_P3(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__)) + +#define ACTION_P4(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__)) + +#define ACTION_P5(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__)) + +#define ACTION_P6(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__)) + +#define ACTION_P7(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__)) + +#define ACTION_P8(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__)) + +#define ACTION_P9(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__)) + +#define ACTION_P10(name, ...) \ + GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__)) + +} // namespace testing + +GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100 + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-cardinalities.h b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-cardinalities.h similarity index 94% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-cardinalities.h rename to thirdparty_builtin/googletest/googlemock/include/gmock/gmock-cardinalities.h index 46e01e102..b6ab648e5 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-cardinalities.h +++ b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-cardinalities.h @@ -27,21 +27,23 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used cardinalities. More // cardinalities can be defined by the user implementing the // CardinalityInterface interface if necessary. -// GOOGLETEST_CM0002 DO NOT DELETE +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #include + #include #include // NOLINT + #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" @@ -116,7 +118,7 @@ class GTEST_API_ Cardinality { // cardinality, i.e. exceed the maximum number of allowed calls. bool IsOverSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count) && - !impl_->IsSatisfiedByCallCount(call_count); + !impl_->IsSatisfiedByCallCount(call_count); } // Describes self to an ostream @@ -154,4 +156,4 @@ inline Cardinality MakeCardinality(const CardinalityInterface* c) { GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-function-mocker.h b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-function-mocker.h new file mode 100644 index 000000000..1a1f126e4 --- /dev/null +++ b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-function-mocker.h @@ -0,0 +1,518 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Google Mock - a framework for writing C++ mock classes. +// +// This file implements MOCK_METHOD. + +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* + +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ + +#include // IWYU pragma: keep +#include // IWYU pragma: keep + +#include "gmock/gmock-spec-builders.h" +#include "gmock/internal/gmock-internal-utils.h" +#include "gmock/internal/gmock-pp.h" + +namespace testing { +namespace internal { +template +using identity_t = T; + +template +struct ThisRefAdjuster { + template + using AdjustT = typename std::conditional< + std::is_const::type>::value, + typename std::conditional::value, + const T&, const T&&>::type, + typename std::conditional::value, T&, + T&&>::type>::type; + + template + static AdjustT Adjust(const MockType& mock) { + return static_cast>(const_cast(mock)); + } +}; + +constexpr bool PrefixOf(const char* a, const char* b) { + return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1)); +} + +template +constexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(prefix, str); +} + +template +constexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) { + return N <= M && internal::PrefixOf(suffix, str + M - N); +} + +template +constexpr bool Equals(const char (&a)[N], const char (&b)[M]) { + return N == M && internal::PrefixOf(a, b); +} + +template +constexpr bool ValidateSpec(const char (&spec)[N]) { + return internal::Equals("const", spec) || + internal::Equals("override", spec) || + internal::Equals("final", spec) || + internal::Equals("noexcept", spec) || + (internal::StartsWith("noexcept(", spec) && + internal::EndsWith(")", spec)) || + internal::Equals("ref(&)", spec) || + internal::Equals("ref(&&)", spec) || + (internal::StartsWith("Calltype(", spec) && + internal::EndsWith(")", spec)); +} + +} // namespace internal + +// The style guide prohibits "using" statements in a namespace scope +// inside a header file. However, the FunctionMocker class template +// is meant to be defined in the ::testing namespace. The following +// line is just a trick for working around a bug in MSVC 8.0, which +// cannot handle it if we define FunctionMocker in ::testing. +using internal::FunctionMocker; +} // namespace testing + +#define MOCK_METHOD(...) \ + GMOCK_INTERNAL_WARNING_PUSH() \ + GMOCK_INTERNAL_WARNING_CLANG(ignored, "-Wunused-member-function") \ + GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) \ + GMOCK_INTERNAL_WARNING_POP() + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ + GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ + GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ + GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ + GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ + GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec), \ + GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \ + (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ + GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) + +#define GMOCK_INTERNAL_WRONG_ARITY(...) \ + static_assert( \ + false, \ + "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ + "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ + "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ + "it must also be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ + static_assert( \ + GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ + GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ + static_assert( \ + std::is_function<__VA_ARGS__>::value, \ + "Signature must be a function type, maybe return type contains " \ + "unprotected comma."); \ + static_assert( \ + ::testing::tuple_size::ArgumentTuple>::value == _N, \ + "This method does not take " GMOCK_PP_STRINGIZE( \ + _N) " arguments. Parenthesize all types with unprotected commas.") + +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) + +#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ + _Override, _Final, _NoexceptSpec, \ + _CallType, _RefSpec, _Signature) \ + typename ::testing::internal::Function::Result \ + GMOCK_INTERNAL_EXPAND(_CallType) \ + _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) \ + _RefSpec _NoexceptSpec GMOCK_PP_IF(_Override, override, ) \ + GMOCK_PP_IF(_Final, final, ) { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .SetOwnerAndName(this, #_MethodName); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ + GMOCK_PP_IF(_Constness, const, ) _RefSpec { \ + GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ + return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ + .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ + } \ + ::testing::MockSpec gmock_##_MethodName( \ + const ::testing::internal::WithoutMatchers&, \ + GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ + GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \ + return ::testing::internal::ThisRefAdjuster::Adjust(*this) \ + .gmock_##_MethodName(GMOCK_PP_REPEAT( \ + GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ + } \ + mutable ::testing::FunctionMocker \ + GMOCK_MOCKER_(_N, _Constness, _MethodName) + +#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ + +// Valid modifiers. +#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ + GMOCK_PP_HAS_COMMA( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) + +#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ + GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) + +#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple) + +#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \ + _elem, ) + +#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple) + +#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_IF( \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple) + +#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \ + GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \ + GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), ) + +#ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)), \ + "Token \'" GMOCK_PP_STRINGIZE( \ + _elem) "\' cannot be recognized as a valid specification " \ + "modifier. Is a ',' missing?"); +#else +#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ + static_assert( \ + (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \ + GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \ + GMOCK_PP_STRINGIZE( \ + _elem) " cannot be recognized as a valid specification modifier."); +#endif // GMOCK_INTERNAL_STRICT_SPEC_ASSERT + +// Modifiers implementation. +#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CONST_I_const , + +#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , + +#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_FINAL_I_final , + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , + +#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_REF_I_ref , + +#define GMOCK_INTERNAL_UNPACK_ref(x) x + +#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \ + GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem) + +#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype , + +#define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__ + +// Note: The use of `identity_t` here allows _Ret to represent return types that +// would normally need to be specified in a different way. For example, a method +// returning a function pointer must be written as +// +// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...) +// +// But we only support placing the return type at the beginning. To handle this, +// we wrap all calls in identity_t, so that a declaration will be expanded to +// +// identity_t method(method_args_t...) +// +// This allows us to work around the syntactic oddities of function/method +// types. +#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ + ::testing::internal::identity_t( \ + GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) + +#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ + GMOCK_PP_IDENTITY) \ + (_elem) + +#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::std::forward(gmock_a##_i) + +#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \ + gmock_a##_i + +#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ + GMOCK_PP_COMMA_IF(_i) \ + gmock_a##_i + +#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ + GMOCK_PP_COMMA_IF(_i) \ + ::testing::A() + +#define GMOCK_INTERNAL_ARG_O(_i, ...) \ + typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type + +#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \ + const ::testing::Matcher::template Arg<_i>::type>& + +#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__) +#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__) +#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__) +#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__) +#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__) +#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__) +#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__) +#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__) +#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__) +#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__) +#define MOCK_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10(m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__) +#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__) +#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__) +#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__) +#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__) +#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__) +#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__) +#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__) +#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__) +#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__) +#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__) + +#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__) +#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__) +#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__) +#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__) +#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__) +#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__) +#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__) +#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__) +#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__) +#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__) +#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__) +#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__) +#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__) +#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__) +#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__) +#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__) +#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__) +#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__) +#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__) +#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__) +#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ + GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__) + +#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ + MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__) + +#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \ + GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ + args_num, ::testing::internal::identity_t<__VA_ARGS__>); \ + GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ + args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \ + (::testing::internal::identity_t<__VA_ARGS__>)) + +#define GMOCK_MOCKER_(arity, constness, Method) \ + GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) + +#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_FUNCTION_MOCKER_H_ diff --git a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-matchers.h b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-matchers.h similarity index 70% rename from thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-matchers.h rename to thirdparty_builtin/googletest/googlemock/include/gmock/gmock-matchers.h index 67bd7e271..7c5d65cf1 100644 --- a/thirdparty_builtin/googletest-master-2020-01-07/googlemock/include/gmock/gmock-matchers.h +++ b/thirdparty_builtin/googletest/googlemock/include/gmock/gmock-matchers.h @@ -27,24 +27,239 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // Google Mock - a framework for writing C++ mock classes. // -// This file implements some commonly used argument matchers. More +// The MATCHER* family of macros can be used in a namespace scope to +// define custom matchers easily. +// +// Basic Usage +// =========== +// +// The syntax +// +// MATCHER(name, description_string) { statements; } +// +// defines a matcher with the given name that executes the statements, +// which must return a bool to indicate if the match succeeds. Inside +// the statements, you can refer to the value being matched by 'arg', +// and refer to its type by 'arg_type'. +// +// The description string documents what the matcher does, and is used +// to generate the failure message when the match fails. Since a +// MATCHER() is usually defined in a header file shared by multiple +// C++ source files, we require the description to be a C-string +// literal to avoid possible side effects. It can be empty, in which +// case we'll use the sequence of words in the matcher name as the +// description. +// +// For example: +// +// MATCHER(IsEven, "") { return (arg % 2) == 0; } +// +// allows you to write +// +// // Expects mock_foo.Bar(n) to be called where n is even. +// EXPECT_CALL(mock_foo, Bar(IsEven())); +// +// or, +// +// // Verifies that the value of some_expression is even. +// EXPECT_THAT(some_expression, IsEven()); +// +// If the above assertion fails, it will print something like: +// +// Value of: some_expression +// Expected: is even +// Actual: 7 +// +// where the description "is even" is automatically calculated from the +// matcher name IsEven. +// +// Argument Type +// ============= +// +// Note that the type of the value being matched (arg_type) is +// determined by the context in which you use the matcher and is +// supplied to you by the compiler, so you don't need to worry about +// declaring it (nor can you). This allows the matcher to be +// polymorphic. For example, IsEven() can be used to match any type +// where the value of "(arg % 2) == 0" can be implicitly converted to +// a bool. In the "Bar(IsEven())" example above, if method Bar() +// takes an int, 'arg_type' will be int; if it takes an unsigned long, +// 'arg_type' will be unsigned long; and so on. +// +// Parameterizing Matchers +// ======================= +// +// Sometimes you'll want to parameterize the matcher. For that you +// can use another macro: +// +// MATCHER_P(name, param_name, description_string) { statements; } +// +// For example: +// +// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } +// +// will allow you to write: +// +// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); +// +// which may lead to this message (assuming n is 10): +// +// Value of: Blah("a") +// Expected: has absolute value 10 +// Actual: -9 +// +// Note that both the matcher description and its parameter are +// printed, making the message human-friendly. +// +// In the matcher definition body, you can write 'foo_type' to +// reference the type of a parameter named 'foo'. For example, in the +// body of MATCHER_P(HasAbsoluteValue, value) above, you can write +// 'value_type' to refer to the type of 'value'. +// +// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to +// support multi-parameter matchers. +// +// Describing Parameterized Matchers +// ================================= +// +// The last argument to MATCHER*() is a string-typed expression. The +// expression can reference all of the matcher's parameters and a +// special bool-typed variable named 'negation'. When 'negation' is +// false, the expression should evaluate to the matcher's description; +// otherwise it should evaluate to the description of the negation of +// the matcher. For example, +// +// using testing::PrintToString; +// +// MATCHER_P2(InClosedRange, low, hi, +// std::string(negation ? "is not" : "is") + " in range [" + +// PrintToString(low) + ", " + PrintToString(hi) + "]") { +// return low <= arg && arg <= hi; +// } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: is in range [4, 6] +// ... +// Expected: is not in range [2, 4] +// +// If you specify "" as the description, the failure message will +// contain the sequence of words in the matcher name followed by the +// parameter values printed as a tuple. For example, +// +// MATCHER_P2(InClosedRange, low, hi, "") { ... } +// ... +// EXPECT_THAT(3, InClosedRange(4, 6)); +// EXPECT_THAT(3, Not(InClosedRange(2, 4))); +// +// would generate two failures that contain the text: +// +// Expected: in closed range (4, 6) +// ... +// Expected: not (in closed range (2, 4)) +// +// Types of Matcher Parameters +// =========================== +// +// For the purpose of typing, you can view +// +// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } +// +// as shorthand for +// +// template +// FooMatcherPk +// Foo(p1_type p1, ..., pk_type pk) { ... } +// +// When you write Foo(v1, ..., vk), the compiler infers the types of +// the parameters v1, ..., and vk for you. If you are not happy with +// the result of the type inference, you can specify the types by +// explicitly instantiating the template, as in Foo(5, +// false). As said earlier, you don't get to (or need to) specify +// 'arg_type' as that's determined by the context in which the matcher +// is used. You can assign the result of expression Foo(p1, ..., pk) +// to a variable of type FooMatcherPk. This +// can be useful when composing matchers. +// +// While you can instantiate a matcher template with reference types, +// passing the parameters by pointer usually makes your code more +// readable. If, however, you still want to pass a parameter by +// reference, be aware that in the failure message generated by the +// matcher you will see the value of the referenced object but not its +// address. +// +// Explaining Match Results +// ======================== +// +// Sometimes the matcher description alone isn't enough to explain why +// the match has failed or succeeded. For example, when expecting a +// long string, it can be very helpful to also print the diff between +// the expected string and the actual one. To achieve that, you can +// optionally stream additional information to a special variable +// named result_listener, whose type is a pointer to class +// MatchResultListener: +// +// MATCHER_P(EqualsLongString, str, "") { +// if (arg == str) return true; +// +// *result_listener << "the difference: " +/// << DiffStrings(str, arg); +// return false; +// } +// +// Overloading Matchers +// ==================== +// +// You can overload matchers with different numbers of parameters: +// +// MATCHER_P(Blah, a, description_string1) { ... } +// MATCHER_P2(Blah, a, b, description_string2) { ... } +// +// Caveats +// ======= +// +// When defining a new matcher, you should also consider implementing +// MatcherInterface or using MakePolymorphicMatcher(). These +// approaches require more work than the MATCHER* macros, but also +// give you more control on the types of the value being matched and +// the matcher parameters, which may leads to better compiler error +// messages when the matcher is used wrong. They also allow +// overloading matchers based on parameter types (as opposed to just +// based on the number of parameters). +// +// MATCHER*() can only be used in a namespace scope as templates cannot be +// declared inside of a local class. +// +// More Information +// ================ +// +// To learn more about using these macros, please search for 'MATCHER' +// on +// https://github.com/google/googletest/blob/main/docs/gmock_cook_book.md +// +// This file also implements some commonly used argument matchers. More // matchers can be defined by the user implementing the // MatcherInterface interface if necessary. // // See googletest/include/gtest/gtest-matchers.h for the definition of class // Matcher, class MatcherInterface, and others. -// GOOGLETEST_CM0002 DO NOT DELETE +// IWYU pragma: private, include "gmock/gmock.h" +// IWYU pragma: friend gmock/.* -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ +#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #include #include +#include #include +#include #include #include #include @@ -57,6 +272,7 @@ #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" +#include "gmock/internal/gmock-pp.h" #include "gtest/gtest.h" // MSVC warning C5046 is new as of VS2017 version 15.8. @@ -99,7 +315,9 @@ class StringMatchResultListener : public MatchResultListener { private: ::std::stringstream ss_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); + StringMatchResultListener(const StringMatchResultListener&) = delete; + StringMatchResultListener& operator=(const StringMatchResultListener&) = + delete; }; // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION @@ -129,7 +347,7 @@ class MatcherCastImpl { // constructor from M (this usually happens when T has an implicit // constructor from any type). // - // It won't work to unconditionally implict_cast + // It won't work to unconditionally implicit_cast // polymorphic_matcher_or_value to Matcher because it won't trigger // a user-defined conversion from M to T if one exists (assuming M is // a value). @@ -182,7 +400,7 @@ class MatcherCastImpl { // is already a Matcher. This only compiles when type T can be // statically converted to type U. template -class MatcherCastImpl > { +class MatcherCastImpl> { public: static Matcher Cast(const Matcher& source_matcher) { return Matcher(new Impl(source_matcher)); @@ -210,7 +428,14 @@ class MatcherCastImpl > { !std::is_base_of::value, "Can't implicitly convert from to "); - return source_matcher_.MatchAndExplain(static_cast(x), listener); + // Do the cast to `U` explicitly if necessary. + // Otherwise, let implicit conversions do the trick. + using CastType = + typename std::conditional::value, + T&, U>::type; + + return source_matcher_.MatchAndExplain(static_cast(x), + listener); } void DescribeTo(::std::ostream* os) const override { @@ -223,19 +448,61 @@ class MatcherCastImpl > { private: const Matcher source_matcher_; - - GTEST_DISALLOW_ASSIGN_(Impl); }; }; // This even more specialized version is used for efficiently casting // a matcher to its own type. template -class MatcherCastImpl > { +class MatcherCastImpl> { public: static Matcher Cast(const Matcher& matcher) { return matcher; } }; +// Template specialization for parameterless Matcher. +template +class MatcherBaseImpl { + public: + MatcherBaseImpl() = default; + + template + operator ::testing::Matcher() const { // NOLINT(runtime/explicit) + return ::testing::Matcher(new + typename Derived::template gmock_Impl()); + } +}; + +// Template specialization for Matcher with parameters. +template