mirror of
https://github.com/TorqueGameEngines/Torque3D.git
synced 2026-07-13 23:54:35 +00:00
Update Assimp from 5.2.3 to 5.2.5
This commit is contained in:
parent
ea7ca63301
commit
16f3710058
379 changed files with 14469 additions and 47175 deletions
|
|
@ -86,6 +86,13 @@ class Int128
|
|||
|
||||
Int128(const Int128 &val): hi(val.hi), lo(val.lo){}
|
||||
|
||||
Int128 operator = (const Int128 &val)
|
||||
{
|
||||
lo = val.lo;
|
||||
hi = val.hi;
|
||||
return val;
|
||||
}
|
||||
|
||||
long64 operator = (const long64 &val)
|
||||
{
|
||||
lo = val;
|
||||
|
|
|
|||
1
Engine/lib/assimp/contrib/draco/.gitignore
vendored
Normal file
1
Engine/lib/assimp/contrib/draco/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
docs/_site
|
||||
|
|
@ -10,7 +10,7 @@ endif()
|
|||
|
||||
set(draco_root "${CMAKE_CURRENT_SOURCE_DIR}")
|
||||
set(draco_src_root "${draco_root}/src/draco")
|
||||
set(draco_build "${CMAKE_BINARY_DIR}")
|
||||
set(draco_build "${Assimp_BINARY_DIR}")
|
||||
|
||||
if("${draco_root}" STREQUAL "${draco_build}")
|
||||
message(
|
||||
|
|
|
|||
2
Engine/lib/assimp/contrib/gtest/.gitignore
vendored
Normal file
2
Engine/lib/assimp/contrib/gtest/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
# python
|
||||
*.pyc
|
||||
|
|
@ -1,14 +1,13 @@
|
|||
########################################################################
|
||||
# Note: CMake support is community-based. The maintainers do not use CMake
|
||||
# internally.
|
||||
#
|
||||
# CMake build script for Google Test.
|
||||
#
|
||||
# To run the tests for Google Test itself on Linux, use 'make test' or
|
||||
# ctest. You can select which tests to run using 'ctest -R regex'.
|
||||
# For more options, run 'ctest --help'.
|
||||
|
||||
# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
|
||||
# make it prominent in the GUI.
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
|
||||
|
||||
# When other libraries are using a shared version of runtime libraries,
|
||||
# Google Test also has to use one.
|
||||
option(
|
||||
|
|
@ -44,13 +43,40 @@ endif()
|
|||
# as ${gtest_SOURCE_DIR} and to the root binary directory as
|
||||
# ${gtest_BINARY_DIR}.
|
||||
# Language "C" is required for find_package(Threads).
|
||||
project(gtest CXX C)
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
# Project version:
|
||||
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
cmake_policy(SET CMP0048 NEW)
|
||||
project(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
|
||||
|
||||
if (POLICY CMP0063) # Visibility
|
||||
cmake_policy(SET CMP0063 NEW)
|
||||
endif (POLICY CMP0063)
|
||||
|
||||
if (COMMAND set_up_hermetic_build)
|
||||
set_up_hermetic_build()
|
||||
endif()
|
||||
|
||||
# These commands only run if this is the main project
|
||||
if(CMAKE_PROJECT_NAME STREQUAL "gtest" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution")
|
||||
|
||||
# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
|
||||
# make it prominent in the GUI.
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
|
||||
|
||||
else()
|
||||
|
||||
mark_as_advanced(
|
||||
gtest_force_shared_crt
|
||||
gtest_build_tests
|
||||
gtest_build_samples
|
||||
gtest_disable_pthreads
|
||||
gtest_hide_internal_symbols)
|
||||
|
||||
endif()
|
||||
|
||||
|
||||
if (gtest_hide_internal_symbols)
|
||||
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
|
||||
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
|
||||
|
|
@ -61,24 +87,34 @@ include(cmake/internal_utils.cmake)
|
|||
|
||||
config_compiler_and_linker() # Defined in internal_utils.cmake.
|
||||
|
||||
# Where Google Test's .h files can be found.
|
||||
include_directories(
|
||||
${gtest_SOURCE_DIR}/include
|
||||
${gtest_SOURCE_DIR})
|
||||
# Needed to set the namespace for both the export targets and the
|
||||
# alias libraries
|
||||
set(cmake_package_name GTest CACHE INTERNAL "")
|
||||
|
||||
# Where Google Test's libraries can be found.
|
||||
link_directories(${gtest_BINARY_DIR}/src)
|
||||
|
||||
# Summary of tuple support for Microsoft Visual Studio:
|
||||
# Compiler version(MS) version(cmake) Support
|
||||
# ---------- ----------- -------------- -----------------------------
|
||||
# <= VS 2010 <= 10 <= 1600 Use Google Tests's own tuple.
|
||||
# VS 2012 11 1700 std::tr1::tuple + _VARIADIC_MAX=10
|
||||
# VS 2013 12 1800 std::tr1::tuple
|
||||
if (MSVC AND MSVC_VERSION EQUAL 1700)
|
||||
add_definitions(/D _VARIADIC_MAX=10)
|
||||
# Create the CMake package file descriptors.
|
||||
if (INSTALL_GTEST)
|
||||
include(CMakePackageConfigHelpers)
|
||||
set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL "")
|
||||
set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated" CACHE INTERNAL "")
|
||||
set(cmake_files_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}")
|
||||
set(version_file "${generated_dir}/${cmake_package_name}ConfigVersion.cmake")
|
||||
write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion)
|
||||
install(EXPORT ${targets_export_name}
|
||||
NAMESPACE ${cmake_package_name}::
|
||||
DESTINATION ${cmake_files_install_dir})
|
||||
set(config_file "${generated_dir}/${cmake_package_name}Config.cmake")
|
||||
configure_package_config_file("${gtest_SOURCE_DIR}/cmake/Config.cmake.in"
|
||||
"${config_file}" INSTALL_DESTINATION ${cmake_files_install_dir})
|
||||
install(FILES ${version_file} ${config_file}
|
||||
DESTINATION ${cmake_files_install_dir})
|
||||
endif()
|
||||
|
||||
# Where Google Test's .h files can be found.
|
||||
set(gtest_build_include_dirs
|
||||
"${gtest_SOURCE_DIR}/include"
|
||||
"${gtest_SOURCE_DIR}")
|
||||
include_directories(${gtest_build_include_dirs})
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Defines the gtest & gtest_main libraries. User tests should link
|
||||
|
|
@ -88,24 +124,30 @@ endif()
|
|||
# are used for other targets, to ensure that gtest can be compiled by a user
|
||||
# aggressive about warnings.
|
||||
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
|
||||
set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
|
||||
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
|
||||
target_link_libraries(gtest_main gtest)
|
||||
|
||||
set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
|
||||
# If the CMake version supports it, attach header directory information
|
||||
# to the targets for when we are part of a parent build (ie being pulled
|
||||
# in via add_subdirectory() rather than being a standalone build).
|
||||
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
|
||||
target_include_directories(gtest INTERFACE "${gtest_SOURCE_DIR}/include")
|
||||
target_include_directories(gtest_main INTERFACE "${gtest_SOURCE_DIR}/include")
|
||||
string(REPLACE ";" "$<SEMICOLON>" dirs "${gtest_build_include_dirs}")
|
||||
target_include_directories(gtest SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_include_directories(gtest_main SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
endif()
|
||||
if(CMAKE_SYSTEM_NAME MATCHES "QNX")
|
||||
target_link_libraries(gtest PUBLIC regex)
|
||||
endif()
|
||||
target_link_libraries(gtest_main PUBLIC gtest)
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Install rules
|
||||
install(TARGETS gtest gtest_main
|
||||
DESTINATION lib)
|
||||
install(DIRECTORY ${gtest_SOURCE_DIR}/include/gtest
|
||||
DESTINATION include)
|
||||
install_project(gtest gtest_main)
|
||||
|
||||
########################################################################
|
||||
#
|
||||
|
|
@ -147,33 +189,34 @@ if (gtest_build_tests)
|
|||
############################################################
|
||||
# C++ tests built with standard compiler flags.
|
||||
|
||||
cxx_test(gtest-death-test_test gtest_main)
|
||||
cxx_test(googletest-death-test-test gtest_main)
|
||||
cxx_test(gtest_environment_test gtest)
|
||||
cxx_test(gtest-filepath_test gtest_main)
|
||||
cxx_test(gtest-linked_ptr_test gtest_main)
|
||||
cxx_test(gtest-listener_test gtest_main)
|
||||
cxx_test(googletest-filepath-test gtest_main)
|
||||
cxx_test(googletest-listener-test gtest_main)
|
||||
cxx_test(gtest_main_unittest gtest_main)
|
||||
cxx_test(gtest-message_test gtest_main)
|
||||
cxx_test(googletest-message-test gtest_main)
|
||||
cxx_test(gtest_no_test_unittest gtest)
|
||||
cxx_test(gtest-options_test gtest_main)
|
||||
cxx_test(gtest-param-test_test gtest
|
||||
test/gtest-param-test2_test.cc)
|
||||
cxx_test(gtest-port_test gtest_main)
|
||||
cxx_test(googletest-options-test gtest_main)
|
||||
cxx_test(googletest-param-test-test gtest
|
||||
test/googletest-param-test2-test.cc)
|
||||
cxx_test(googletest-port-test gtest_main)
|
||||
cxx_test(gtest_pred_impl_unittest gtest_main)
|
||||
cxx_test(gtest_premature_exit_test gtest
|
||||
test/gtest_premature_exit_test.cc)
|
||||
cxx_test(gtest-printers_test gtest_main)
|
||||
cxx_test(googletest-printers-test gtest_main)
|
||||
cxx_test(gtest_prod_test gtest_main
|
||||
test/production.cc)
|
||||
cxx_test(gtest_repeat_test gtest)
|
||||
cxx_test(gtest_sole_header_test gtest_main)
|
||||
cxx_test(gtest_stress_test gtest)
|
||||
cxx_test(gtest-test-part_test gtest_main)
|
||||
cxx_test(googletest-test-part-test gtest_main)
|
||||
cxx_test(gtest_throw_on_failure_ex_test gtest)
|
||||
cxx_test(gtest-typed-test_test gtest_main
|
||||
test/gtest-typed-test2_test.cc)
|
||||
cxx_test(gtest_unittest gtest_main)
|
||||
cxx_test(gtest-unittest-api_test gtest)
|
||||
cxx_test(gtest_skip_in_environment_setup_test gtest_main)
|
||||
cxx_test(gtest_skip_test gtest_main)
|
||||
|
||||
############################################################
|
||||
# C++ tests built with non-standard compiler flags.
|
||||
|
|
@ -190,10 +233,10 @@ if (gtest_build_tests)
|
|||
|
||||
cxx_test_with_flags(gtest-death-test_ex_nocatch_test
|
||||
"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0"
|
||||
gtest test/gtest-death-test_ex_test.cc)
|
||||
gtest test/googletest-death-test_ex_test.cc)
|
||||
cxx_test_with_flags(gtest-death-test_ex_catch_test
|
||||
"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1"
|
||||
gtest test/gtest-death-test_ex_test.cc)
|
||||
gtest test/googletest-death-test_ex_test.cc)
|
||||
|
||||
cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}"
|
||||
gtest_main_no_rtti test/gtest_unittest.cc)
|
||||
|
|
@ -207,80 +250,73 @@ if (gtest_build_tests)
|
|||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
|
||||
|
||||
if (NOT MSVC OR MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010.
|
||||
# Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that
|
||||
# conflict with our own definitions. Therefore using our own tuple does not
|
||||
# work on those compilers.
|
||||
cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}"
|
||||
src/gtest-all.cc src/gtest_main.cc)
|
||||
|
||||
cxx_test_with_flags(gtest-tuple_test "${cxx_use_own_tuple}"
|
||||
gtest_main_use_own_tuple test/gtest-tuple_test.cc)
|
||||
|
||||
cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}"
|
||||
gtest_main_use_own_tuple
|
||||
test/gtest-param-test_test.cc test/gtest-param-test2_test.cc)
|
||||
endif()
|
||||
|
||||
############################################################
|
||||
# Python tests.
|
||||
|
||||
cxx_executable(gtest_break_on_failure_unittest_ test gtest)
|
||||
py_test(gtest_break_on_failure_unittest)
|
||||
cxx_executable(googletest-break-on-failure-unittest_ test gtest)
|
||||
py_test(googletest-break-on-failure-unittest)
|
||||
|
||||
py_test(gtest_skip_check_output_test)
|
||||
py_test(gtest_skip_environment_check_output_test)
|
||||
|
||||
# Visual Studio .NET 2003 does not support STL with exceptions disabled.
|
||||
if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003
|
||||
cxx_executable_with_flags(
|
||||
gtest_catch_exceptions_no_ex_test_
|
||||
googletest-catch-exceptions-no-ex-test_
|
||||
"${cxx_no_exception}"
|
||||
gtest_main_no_exception
|
||||
test/gtest_catch_exceptions_test_.cc)
|
||||
test/googletest-catch-exceptions-test_.cc)
|
||||
endif()
|
||||
|
||||
cxx_executable_with_flags(
|
||||
gtest_catch_exceptions_ex_test_
|
||||
googletest-catch-exceptions-ex-test_
|
||||
"${cxx_exception}"
|
||||
gtest_main
|
||||
test/gtest_catch_exceptions_test_.cc)
|
||||
py_test(gtest_catch_exceptions_test)
|
||||
test/googletest-catch-exceptions-test_.cc)
|
||||
py_test(googletest-catch-exceptions-test)
|
||||
|
||||
cxx_executable(gtest_color_test_ test gtest)
|
||||
py_test(gtest_color_test)
|
||||
cxx_executable(googletest-color-test_ test gtest)
|
||||
py_test(googletest-color-test)
|
||||
|
||||
cxx_executable(gtest_env_var_test_ test gtest)
|
||||
py_test(gtest_env_var_test)
|
||||
cxx_executable(googletest-env-var-test_ test gtest)
|
||||
py_test(googletest-env-var-test)
|
||||
|
||||
cxx_executable(gtest_filter_unittest_ test gtest)
|
||||
py_test(gtest_filter_unittest)
|
||||
cxx_executable(googletest-filter-unittest_ test gtest)
|
||||
py_test(googletest-filter-unittest)
|
||||
|
||||
cxx_executable(gtest_help_test_ test gtest_main)
|
||||
py_test(gtest_help_test)
|
||||
|
||||
cxx_executable(gtest_list_tests_unittest_ test gtest)
|
||||
py_test(gtest_list_tests_unittest)
|
||||
cxx_executable(googletest-list-tests-unittest_ test gtest)
|
||||
py_test(googletest-list-tests-unittest)
|
||||
|
||||
cxx_executable(gtest_output_test_ test gtest)
|
||||
py_test(gtest_output_test)
|
||||
cxx_executable(googletest-output-test_ test gtest)
|
||||
py_test(googletest-output-test --no_stacktrace_support)
|
||||
|
||||
cxx_executable(gtest_shuffle_test_ test gtest)
|
||||
py_test(gtest_shuffle_test)
|
||||
cxx_executable(googletest-shuffle-test_ test gtest)
|
||||
py_test(googletest-shuffle-test)
|
||||
|
||||
# MSVC 7.1 does not support STL with exceptions disabled.
|
||||
if (NOT MSVC OR MSVC_VERSION GREATER 1310)
|
||||
cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception)
|
||||
set_target_properties(gtest_throw_on_failure_test_
|
||||
cxx_executable(googletest-throw-on-failure-test_ test gtest_no_exception)
|
||||
set_target_properties(googletest-throw-on-failure-test_
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS "${cxx_no_exception}")
|
||||
py_test(gtest_throw_on_failure_test)
|
||||
py_test(googletest-throw-on-failure-test)
|
||||
endif()
|
||||
|
||||
cxx_executable(gtest_uninitialized_test_ test gtest)
|
||||
py_test(gtest_uninitialized_test)
|
||||
cxx_executable(googletest-uninitialized-test_ test gtest)
|
||||
py_test(googletest-uninitialized-test)
|
||||
|
||||
cxx_executable(gtest_list_output_unittest_ test gtest)
|
||||
py_test(gtest_list_output_unittest)
|
||||
|
||||
cxx_executable(gtest_xml_outfile1_test_ test gtest_main)
|
||||
cxx_executable(gtest_xml_outfile2_test_ test gtest_main)
|
||||
py_test(gtest_xml_outfiles_test)
|
||||
py_test(googletest-json-outfiles-test)
|
||||
|
||||
cxx_executable(gtest_xml_output_unittest_ test gtest)
|
||||
py_test(gtest_xml_output_unittest)
|
||||
py_test(gtest_xml_output_unittest --no_stacktrace_support)
|
||||
py_test(googletest-json-output-unittest --no_stacktrace_support)
|
||||
endif()
|
||||
|
|
|
|||
|
|
@ -1,181 +1,156 @@
|
|||
### Generic Build Instructions
|
||||
|
||||
### Generic Build Instructions ###
|
||||
#### Setup
|
||||
|
||||
#### Setup ####
|
||||
To build GoogleTest 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.
|
||||
|
||||
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
|
||||
|
||||
#### Build ####
|
||||
GoogleTest 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
|
||||
<http://www.cmake.org/>.
|
||||
|
||||
Suppose you put Google Test in directory `${GTEST_DIR}`. To build it,
|
||||
create a library build target (or a project as called by Visual Studio
|
||||
and Xcode) to compile
|
||||
CMake works by generating native makefiles or build projects that can be used in
|
||||
the compiler environment of your choice. You can either build GoogleTest as a
|
||||
standalone project or it can be incorporated into an existing CMake build for
|
||||
another project.
|
||||
|
||||
${GTEST_DIR}/src/gtest-all.cc
|
||||
#### Standalone CMake Project
|
||||
|
||||
with `${GTEST_DIR}/include` in the system header search path and `${GTEST_DIR}`
|
||||
in the normal header search path. Assuming a Linux-like system and gcc,
|
||||
something like the following will do:
|
||||
When building GoogleTest as a standalone project, the typical workflow starts
|
||||
with
|
||||
|
||||
g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
|
||||
-pthread -c ${GTEST_DIR}/src/gtest-all.cc
|
||||
ar -rv libgtest.a gtest-all.o
|
||||
```
|
||||
git clone https://github.com/google/googletest.git -b release-1.11.0
|
||||
cd googletest # Main directory of the cloned repository.
|
||||
mkdir build # Create a directory to hold the build output.
|
||||
cd build
|
||||
cmake .. # Generate native build scripts for GoogleTest.
|
||||
```
|
||||
|
||||
(We need `-pthread` as Google Test uses threads.)
|
||||
The above command also includes GoogleMock by default. And so, if you want to
|
||||
build only GoogleTest, you should replace the last command with
|
||||
|
||||
Next, you should compile your test source file with
|
||||
`${GTEST_DIR}/include` in the system header search path, and link it
|
||||
with gtest and any other necessary libraries:
|
||||
```
|
||||
cmake .. -DBUILD_GMOCK=OFF
|
||||
```
|
||||
|
||||
g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \
|
||||
-o your_test
|
||||
If you are on a \*nix system, you should now see a Makefile in the current
|
||||
directory. Just type `make` to build GoogleTest. And then you can simply install
|
||||
GoogleTest if you are a system administrator.
|
||||
|
||||
As an example, the make/ directory contains a Makefile that you can
|
||||
use to build Google Test on systems where GNU make is available
|
||||
(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google
|
||||
Test's own tests. Instead, it just builds the Google Test library and
|
||||
a sample test. You can use it as a starting point for your own build
|
||||
script.
|
||||
```
|
||||
make
|
||||
sudo make install # Install in /usr/local/ by default
|
||||
```
|
||||
|
||||
If the default settings are correct for your environment, the
|
||||
following commands should succeed:
|
||||
|
||||
cd ${GTEST_DIR}/make
|
||||
make
|
||||
./sample1_unittest
|
||||
|
||||
If you see errors, try to tweak the contents of `make/Makefile` to make
|
||||
them go away. There are instructions in `make/Makefile` on how to do
|
||||
it.
|
||||
|
||||
### Using CMake ###
|
||||
|
||||
Google Test comes with a CMake build script (
|
||||
[CMakeLists.txt](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 <http://www.cmake.org/>.
|
||||
|
||||
CMake works by generating native makefiles or build projects that can
|
||||
be used in the compiler environment of your choice. 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.
|
||||
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.
|
||||
|
||||
### Legacy Build Scripts ###
|
||||
#### Incorporating Into An Existing CMake Project
|
||||
|
||||
Before settling on CMake, we have been providing hand-maintained build
|
||||
projects/scripts for Visual Studio, Xcode, and Autotools. While we
|
||||
continue to provide them for convenience, they are not actively
|
||||
maintained any more. We highly recommend that you follow the
|
||||
instructions in the previous two sections to integrate Google Test
|
||||
with your existing build system.
|
||||
If you want to use GoogleTest in a project which already uses CMake, the easiest
|
||||
way is to get installed libraries and headers.
|
||||
|
||||
If you still need to use the legacy build scripts, here's how:
|
||||
* Import GoogleTest by using `find_package` (or `pkg_check_modules`). For
|
||||
example, if `find_package(GTest CONFIG REQUIRED)` succeeds, you can use the
|
||||
libraries as `GTest::gtest`, `GTest::gmock`.
|
||||
|
||||
The msvc\ folder contains two solutions with Visual C++ projects.
|
||||
Open the `gtest.sln` or `gtest-md.sln` file using Visual Studio, and you
|
||||
are ready to build Google Test the same way you build any Visual
|
||||
Studio project. Files that have names ending with -md use DLL
|
||||
versions of Microsoft runtime libraries (the /MD or the /MDd compiler
|
||||
option). Files without that suffix use static versions of the runtime
|
||||
libraries (the /MT or the /MTd option). Please note that one must use
|
||||
the same option to compile both gtest and the test code. If you use
|
||||
Visual Studio 2005 or above, we recommend the -md version as /MD is
|
||||
the default for new projects in these versions of Visual Studio.
|
||||
And a more robust and flexible approach is to build GoogleTest 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 GoogleTest 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:
|
||||
|
||||
On Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using
|
||||
Xcode. Build the "gtest" target. The universal binary framework will
|
||||
end up in your selected build directory (selected in the Xcode
|
||||
"Preferences..." -> "Building" pane and defaults to xcode/build).
|
||||
Alternatively, at the command line, enter:
|
||||
* 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
|
||||
approach doesn't have the limitations of the other methods.
|
||||
|
||||
xcodebuild
|
||||
The last of the above methods is implemented with a small piece of CMake code
|
||||
that downloads and pulls the GoogleTest code into the main build.
|
||||
|
||||
This will build the "Release" configuration of gtest.framework in your
|
||||
default build location. See the "xcodebuild" man page for more
|
||||
information about building different configurations and building in
|
||||
different locations.
|
||||
Just add to your `CMakeLists.txt`:
|
||||
|
||||
If you wish to use the Google Test Xcode project with Xcode 4.x and
|
||||
above, you need to either:
|
||||
```cmake
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(
|
||||
googletest
|
||||
# Specify the commit you depend on and update it regularly.
|
||||
URL https://github.com/google/googletest/archive/e2239ee6043f73722e7aa812a459f54a28552929.zip
|
||||
)
|
||||
# For Windows: Prevent overriding the parent project's compiler/linker settings
|
||||
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||
FetchContent_MakeAvailable(googletest)
|
||||
|
||||
* update the SDK configuration options in xcode/Config/General.xconfig.
|
||||
Comment options `SDKROOT`, `MACOS_DEPLOYMENT_TARGET`, and `GCC_VERSION`. If
|
||||
you choose this route you lose the ability to target earlier versions
|
||||
of MacOS X.
|
||||
* Install an SDK for an earlier version. This doesn't appear to be
|
||||
supported by Apple, but has been reported to work
|
||||
(http://stackoverflow.com/questions/5378518).
|
||||
# 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)
|
||||
```
|
||||
|
||||
### Tweaking Google Test ###
|
||||
Note that this approach requires CMake 3.14 or later due to its use of the
|
||||
`FetchContent_MakeAvailable()` command.
|
||||
|
||||
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.
|
||||
##### Visual Studio Dynamic vs Static Runtimes
|
||||
|
||||
We list the most frequently used macros below. For a complete list,
|
||||
see file [include/gtest/internal/gtest-port.h](include/gtest/internal/gtest-port.h).
|
||||
By default, new Visual Studio projects link the C runtimes dynamically but
|
||||
GoogleTest 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
|
||||
|
||||
### Choosing a TR1 Tuple Library ###
|
||||
GoogleTest already has a CMake option for this: `gtest_force_shared_crt`
|
||||
|
||||
Some Google Test features require the C++ Technical Report 1 (TR1)
|
||||
tuple library, which is not yet available with all compilers. The
|
||||
good news is that Google Test implements a subset of TR1 tuple that's
|
||||
enough for its own need, and will automatically use this when the
|
||||
compiler doesn't provide TR1 tuple.
|
||||
Enabling this option will make gtest link the runtimes dynamically too, and
|
||||
match the project in which it is included.
|
||||
|
||||
Usually you don't need to care about which tuple library Google Test
|
||||
uses. However, if your project already uses TR1 tuple, you need to
|
||||
tell Google Test to use the same TR1 tuple library the rest of your
|
||||
project uses, or the two tuple implementations will clash. To do
|
||||
that, add
|
||||
#### C++ Standard Version
|
||||
|
||||
-DGTEST_USE_OWN_TR1_TUPLE=0
|
||||
An environment that supports C++11 is required in order to successfully build
|
||||
GoogleTest. 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 GoogleTest for validation,
|
||||
then it can be specified by adding it to the options for cmake via the
|
||||
`DCMAKE_CXX_FLAGS` option.
|
||||
|
||||
to the compiler flags while compiling Google Test and your tests. If
|
||||
you want to force Google Test to use its own tuple library, just add
|
||||
### Tweaking GoogleTest
|
||||
|
||||
-DGTEST_USE_OWN_TR1_TUPLE=1
|
||||
GoogleTest 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 GoogleTest 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.
|
||||
|
||||
to the compiler flags instead.
|
||||
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).
|
||||
|
||||
If you don't want Google Test to use tuple at all, add
|
||||
### Multi-threaded Tests
|
||||
|
||||
-DGTEST_HAS_TR1_TUPLE=0
|
||||
GoogleTest 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.).
|
||||
|
||||
and all features using tuple will be disabled.
|
||||
|
||||
### 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
|
||||
If GoogleTest doesn't correctly detect whether pthread is available in your
|
||||
environment, you can force it with
|
||||
|
||||
-DGTEST_HAS_PTHREAD=1
|
||||
|
||||
|
|
@ -183,26 +158,24 @@ 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.
|
||||
When GoogleTest 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, 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) ###
|
||||
### 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.
|
||||
GoogleTest is compact, so most users can build and link it as a static library
|
||||
for the simplicity. You can choose to use GoogleTest 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 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
|
||||
|
||||
|
|
@ -210,31 +183,30 @@ To compile your *tests* that use the gtest shared library, add
|
|||
|
||||
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
|
||||
<http://gcc.gnu.org/wiki/Visibility> 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.
|
||||
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
|
||||
<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended
|
||||
to always add the above flags when using GoogleTest as a shared library.
|
||||
Otherwise a future release of GoogleTest may break your build script.
|
||||
|
||||
### Avoiding Macro Name Clashes ###
|
||||
### 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.
|
||||
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
|
||||
GoogleTest macro clashes with another library, you can force GoogleTest to
|
||||
rename its macro to avoid the conflict.
|
||||
|
||||
Specifically, if both Google Test and some other code define macro
|
||||
FOO, you can add
|
||||
Specifically, if both GoogleTest 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
|
||||
to the compiler flags to tell GoogleTest to change the macro's name from `FOO`
|
||||
to `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,
|
||||
`ASSERT_GT`, `ASSERT_LE`, `ASSERT_LT`, `ASSERT_NE`, `ASSERT_TRUE`,
|
||||
`EXPECT_FALSE`, `EXPECT_TRUE`, `FAIL`, `SUCCEED`, `TEST`, or `TEST_F`. For
|
||||
example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write
|
||||
|
||||
GTEST_TEST(SomeTest, DoesThis) { ... }
|
||||
|
||||
|
|
@ -243,38 +215,3 @@ instead of
|
|||
TEST(SomeTest, DoesThis) { ... }
|
||||
|
||||
in order to define a test.
|
||||
|
||||
## Developing Google Test ##
|
||||
|
||||
This section discusses how to make your own changes to Google Test.
|
||||
|
||||
### Testing Google Test Itself ###
|
||||
|
||||
To make sure your changes work as intended and don't break existing
|
||||
functionality, you'll want to compile and run Google Test's own tests.
|
||||
For that you can use CMake:
|
||||
|
||||
mkdir mybuild
|
||||
cd mybuild
|
||||
cmake -Dgtest_build_tests=ON ${GTEST_DIR}
|
||||
|
||||
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 -Dgtest_build_tests=ON ${GTEST_DIR}
|
||||
|
||||
Next, you can build Google Test and all of its own tests. On \*nix,
|
||||
this is usually done by 'make'. To run the tests, do
|
||||
|
||||
make test
|
||||
|
||||
All tests should pass.
|
||||
|
||||
Normally you don't need to worry about regenerating the source files,
|
||||
unless you need to modify them. In that case, you should modify the
|
||||
corresponding .pump files instead and run the pump.py Python script to
|
||||
regenerate them. You can find pump.py in the [scripts/](scripts/) directory.
|
||||
Read the [Pump manual](docs/PumpManual.md) for how to use it.
|
||||
|
|
|
|||
9
Engine/lib/assimp/contrib/gtest/cmake/Config.cmake.in
Normal file
9
Engine/lib/assimp/contrib/gtest/cmake/Config.cmake.in
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
@PACKAGE_INIT@
|
||||
include(CMakeFindDependencyMacro)
|
||||
if (@GTEST_HAS_PTHREAD@)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG @THREADS_PREFER_PTHREAD_FLAG@)
|
||||
find_dependency(Threads)
|
||||
endif()
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake")
|
||||
check_required_components("@project_name@")
|
||||
9
Engine/lib/assimp/contrib/gtest/cmake/gtest.pc.in
Normal file
9
Engine/lib/assimp/contrib/gtest/cmake/gtest.pc.in
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gtest
|
||||
Description: GoogleTest (without main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
|
||||
10
Engine/lib/assimp/contrib/gtest/cmake/gtest_main.pc.in
Normal file
10
Engine/lib/assimp/contrib/gtest/cmake/gtest_main.pc.in
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gtest_main
|
||||
Description: GoogleTest (with main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gtest = @PROJECT_VERSION@
|
||||
Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
|
||||
|
|
@ -12,6 +12,10 @@
|
|||
# Test and Google Mock's option() definitions, and thus must be
|
||||
# called *after* the options have been defined.
|
||||
|
||||
if (POLICY CMP0054)
|
||||
cmake_policy(SET CMP0054 NEW)
|
||||
endif (POLICY CMP0054)
|
||||
|
||||
# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.
|
||||
#
|
||||
# This must be a macro(), as inside a function string() can only
|
||||
|
|
@ -20,8 +24,10 @@ macro(fix_default_compiler_settings_)
|
|||
if (MSVC)
|
||||
# For MSVC, CMake sets certain flags to defaults we want to override.
|
||||
# This replacement code is taken from sample in the CMake Wiki at
|
||||
# http://www.cmake.org/Wiki/CMake_FAQ#Dynamic_Replace.
|
||||
# https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.
|
||||
foreach (flag_var
|
||||
CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
|
||||
CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
|
||||
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
|
||||
if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt)
|
||||
|
|
@ -38,6 +44,11 @@ macro(fix_default_compiler_settings_)
|
|||
# We prefer more strict warning checking for building Google Test.
|
||||
# Replaces /W3 with /W4 in defaults.
|
||||
string(REPLACE "/W3" "/W4" ${flag_var} "${${flag_var}}")
|
||||
|
||||
# Prevent D9025 warning for targets that have exception handling
|
||||
# turned off (/EHs-c- flag). Where required, exceptions are explicitly
|
||||
# re-enabled using the cxx_exception_flags variable.
|
||||
string(REPLACE "/EHsc" "" ${flag_var} "${${flag_var}}")
|
||||
endforeach()
|
||||
endif()
|
||||
endmacro()
|
||||
|
|
@ -46,52 +57,43 @@ endmacro()
|
|||
# Google Mock. You can tweak these definitions to suit your need. A
|
||||
# variable's value is empty before it's explicitly assigned to.
|
||||
macro(config_compiler_and_linker)
|
||||
if (NOT gtest_disable_pthreads)
|
||||
# Note: pthreads on MinGW is not supported, even if available
|
||||
# instead, we use windows threading primitives
|
||||
unset(GTEST_HAS_PTHREAD)
|
||||
if (NOT gtest_disable_pthreads AND NOT MINGW)
|
||||
# Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT.
|
||||
find_package(Threads)
|
||||
if (CMAKE_USE_PTHREADS_INIT)
|
||||
set(GTEST_HAS_PTHREAD ON)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
fix_default_compiler_settings_()
|
||||
if (MSVC)
|
||||
# Newlines inside flags variables break CMake's NMake generator.
|
||||
# TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.
|
||||
set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi")
|
||||
if (MSVC_VERSION LESS 1400) # 1400 is Visual Studio 2005
|
||||
# Suppress spurious warnings MSVC 7.1 sometimes issues.
|
||||
# Forcing value to bool.
|
||||
set(cxx_base_flags "${cxx_base_flags} -wd4800")
|
||||
# Copy constructor and assignment operator could not be generated.
|
||||
set(cxx_base_flags "${cxx_base_flags} -wd4511 -wd4512")
|
||||
# Compatibility warnings not applicable to Google Test.
|
||||
# Resolved overload was found by argument-dependent lookup.
|
||||
set(cxx_base_flags "${cxx_base_flags} -wd4675")
|
||||
endif()
|
||||
if (MSVC_VERSION LESS 1500) # 1500 is Visual Studio 2008
|
||||
# Conditional expression is constant.
|
||||
# When compiling with /W4, we get several instances of C4127
|
||||
# (Conditional expression is constant). In our code, we disable that
|
||||
# warning on a case-by-case basis. However, on Visual Studio 2005,
|
||||
# the warning fires on std::list. Therefore on that compiler and earlier,
|
||||
# we disable the warning project-wide.
|
||||
set(cxx_base_flags "${cxx_base_flags} -wd4127")
|
||||
endif()
|
||||
if (NOT (MSVC_VERSION LESS 1700)) # 1700 is Visual Studio 2012.
|
||||
# Suppress "unreachable code" warning on VS 2012 and later.
|
||||
# http://stackoverflow.com/questions/3232669 explains the issue.
|
||||
set(cxx_base_flags "${cxx_base_flags} -wd4702")
|
||||
endif()
|
||||
if (NOT (MSVC_VERSION GREATER 1900)) # 1900 is Visual Studio 2015
|
||||
# BigObj required for tests.
|
||||
set(cxx_base_flags "${cxx_base_flags} -bigobj")
|
||||
endif()
|
||||
|
||||
set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J")
|
||||
set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32")
|
||||
set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN")
|
||||
set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1")
|
||||
set(cxx_no_exception_flags "-D_HAS_EXCEPTIONS=0")
|
||||
set(cxx_no_exception_flags "-EHs-c- -D_HAS_EXCEPTIONS=0")
|
||||
set(cxx_no_rtti_flags "-GR-")
|
||||
# Suppress "unreachable code" warning
|
||||
# http://stackoverflow.com/questions/3232669 explains the issue.
|
||||
set(cxx_base_flags "${cxx_base_flags} -wd4702")
|
||||
# Ensure MSVC treats source files as UTF-8 encoded.
|
||||
set(cxx_base_flags "${cxx_base_flags} -utf-8")
|
||||
elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
set(cxx_base_flags "-Wall -Wshadow -Wconversion")
|
||||
set(cxx_exception_flags "-fexceptions")
|
||||
set(cxx_no_exception_flags "-fno-exceptions")
|
||||
set(cxx_strict_flags "-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls")
|
||||
set(cxx_no_rtti_flags "-fno-rtti")
|
||||
elseif (CMAKE_COMPILER_IS_GNUCXX)
|
||||
set(cxx_base_flags "-Wall -Wshadow")
|
||||
if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)
|
||||
set(cxx_base_flags "${cxx_base_flags} -Wno-error=dangling-else")
|
||||
endif()
|
||||
set(cxx_exception_flags "-fexceptions")
|
||||
set(cxx_no_exception_flags "-fno-exceptions")
|
||||
# Until version 4.3.2, GCC doesn't define a macro to indicate
|
||||
|
|
@ -123,19 +125,20 @@ macro(config_compiler_and_linker)
|
|||
set(cxx_no_rtti_flags "")
|
||||
endif()
|
||||
|
||||
if (CMAKE_USE_PTHREADS_INIT) # The pthreads library is available and allowed.
|
||||
set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=1")
|
||||
# The pthreads library is available and allowed?
|
||||
if (DEFINED GTEST_HAS_PTHREAD)
|
||||
set(GTEST_HAS_PTHREAD_MACRO "-DGTEST_HAS_PTHREAD=1")
|
||||
else()
|
||||
set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=0")
|
||||
set(GTEST_HAS_PTHREAD_MACRO "-DGTEST_HAS_PTHREAD=0")
|
||||
endif()
|
||||
set(cxx_base_flags "${cxx_base_flags} ${GTEST_HAS_PTHREAD_MACRO}")
|
||||
|
||||
# For building gtest's own tests and samples.
|
||||
set(cxx_exception "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_exception_flags}")
|
||||
set(cxx_exception "${cxx_base_flags} ${cxx_exception_flags}")
|
||||
set(cxx_no_exception
|
||||
"${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_no_exception_flags}")
|
||||
set(cxx_default "${cxx_exception}")
|
||||
set(cxx_no_rtti "${cxx_default} ${cxx_no_rtti_flags}")
|
||||
set(cxx_use_own_tuple "${cxx_default} -DGTEST_USE_OWN_TR1_TUPLE=1")
|
||||
|
||||
# For building the gtest libraries.
|
||||
set(cxx_strict "${cxx_default} ${cxx_strict_flags}")
|
||||
|
|
@ -147,16 +150,46 @@ function(cxx_library_with_type name type cxx_flags)
|
|||
# type can be either STATIC or SHARED to denote a static or shared library.
|
||||
# ARGN refers to additional arguments after 'cxx_flags'.
|
||||
add_library(${name} ${type} ${ARGN})
|
||||
add_library(${cmake_package_name}::${name} ALIAS ${name})
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS "${cxx_flags}")
|
||||
# Set the output directory for build artifacts
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
|
||||
PDB_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
# make PDBs match library name
|
||||
get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX)
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
PDB_NAME "${name}"
|
||||
PDB_NAME_DEBUG "${name}${pdb_debug_postfix}"
|
||||
COMPILE_PDB_NAME "${name}"
|
||||
COMPILE_PDB_NAME_DEBUG "${name}${pdb_debug_postfix}")
|
||||
|
||||
if (BUILD_SHARED_LIBS OR type STREQUAL "SHARED")
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1")
|
||||
if (NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
|
||||
target_compile_definitions(${name} INTERFACE
|
||||
$<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)
|
||||
endif()
|
||||
endif()
|
||||
if (CMAKE_USE_PTHREADS_INIT)
|
||||
target_link_libraries(${name} ${CMAKE_THREAD_LIBS_INIT})
|
||||
if (DEFINED GTEST_HAS_PTHREAD)
|
||||
if ("${CMAKE_VERSION}" VERSION_LESS "3.1.0")
|
||||
set(threads_spec ${CMAKE_THREAD_LIBS_INIT})
|
||||
else()
|
||||
set(threads_spec Threads::Threads)
|
||||
endif()
|
||||
target_link_libraries(${name} PUBLIC ${threads_spec})
|
||||
endif()
|
||||
|
||||
if (NOT "${CMAKE_VERSION}" VERSION_LESS "3.8")
|
||||
target_compile_features(${name} PUBLIC cxx_std_11)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
|
|
@ -178,6 +211,10 @@ endfunction()
|
|||
# is built from the given source files with the given compiler flags.
|
||||
function(cxx_executable_with_flags name cxx_flags libs)
|
||||
add_executable(${name} ${ARGN})
|
||||
if (MSVC)
|
||||
# BigObj required for tests.
|
||||
set(cxx_flags "${cxx_flags} -bigobj")
|
||||
endif()
|
||||
if (cxx_flags)
|
||||
set_target_properties(${name}
|
||||
PROPERTIES
|
||||
|
|
@ -206,7 +243,13 @@ function(cxx_executable name dir libs)
|
|||
endfunction()
|
||||
|
||||
# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.
|
||||
find_package(PythonInterp)
|
||||
if ("${CMAKE_VERSION}" VERSION_LESS "3.12.0")
|
||||
find_package(PythonInterp)
|
||||
else()
|
||||
find_package(Python COMPONENTS Interpreter)
|
||||
set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND})
|
||||
set(PYTHON_EXECUTABLE ${Python_EXECUTABLE})
|
||||
endif()
|
||||
|
||||
# cxx_test_with_flags(name cxx_flags libs srcs...)
|
||||
#
|
||||
|
|
@ -214,7 +257,7 @@ find_package(PythonInterp)
|
|||
# from the given source files with the given compiler flags.
|
||||
function(cxx_test_with_flags name cxx_flags libs)
|
||||
cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN})
|
||||
add_test(${name} ${name})
|
||||
add_test(NAME ${name} COMMAND "$<TARGET_FILE:${name}>")
|
||||
endfunction()
|
||||
|
||||
# cxx_test(name libs srcs...)
|
||||
|
|
@ -232,23 +275,68 @@ endfunction()
|
|||
# creates a Python test with the given name whose main module is in
|
||||
# test/name.py. It does nothing if Python is not installed.
|
||||
function(py_test name)
|
||||
# We are not supporting Python tests on Linux yet as they consider
|
||||
# all Linux environments to be google3 and try to use google3 features.
|
||||
if (PYTHONINTERP_FOUND)
|
||||
# ${CMAKE_BINARY_DIR} is known at configuration time, so we can
|
||||
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
|
||||
# only at ctest runtime (by calling ctest -c <Configuration>), so
|
||||
# we have to escape $ to delay variable substitution here.
|
||||
if (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1)
|
||||
add_test(
|
||||
NAME ${name}
|
||||
if ("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 3.1)
|
||||
if (CMAKE_CONFIGURATION_TYPES)
|
||||
# Multi-configuration build generators as for Visual Studio save
|
||||
# output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,
|
||||
# Release etc.), so we have to provide it here.
|
||||
add_test(NAME ${name}
|
||||
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})
|
||||
else (CMAKE_CONFIGURATION_TYPES)
|
||||
# Single-configuration build generators like Makefile generators
|
||||
# don't have subdirs below CMAKE_CURRENT_BINARY_DIR.
|
||||
add_test(NAME ${name}
|
||||
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})
|
||||
endif (CMAKE_CONFIGURATION_TYPES)
|
||||
else()
|
||||
# ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can
|
||||
# directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known
|
||||
# only at ctest runtime (by calling ctest -c <Configuration>), so
|
||||
# we have to escape $ to delay variable substitution here.
|
||||
add_test(NAME ${name}
|
||||
COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>)
|
||||
else (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1)
|
||||
add_test(
|
||||
${name}
|
||||
${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE})
|
||||
endif (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1)
|
||||
--build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN})
|
||||
endif()
|
||||
# Make the Python import path consistent between Bazel and CMake.
|
||||
set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})
|
||||
endif(PYTHONINTERP_FOUND)
|
||||
endfunction()
|
||||
|
||||
# install_project(targets...)
|
||||
#
|
||||
# Installs the specified targets and configures the associated pkgconfig files.
|
||||
function(install_project)
|
||||
if(INSTALL_GTEST)
|
||||
install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/"
|
||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
|
||||
# Install the project targets.
|
||||
install(TARGETS ${ARGN}
|
||||
EXPORT ${targets_export_name}
|
||||
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
|
||||
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
|
||||
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
# Install PDBs
|
||||
foreach(t ${ARGN})
|
||||
get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME)
|
||||
get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG)
|
||||
get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY)
|
||||
install(FILES
|
||||
"${t_pdb_output_directory}/\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb"
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
OPTIONAL)
|
||||
endforeach()
|
||||
endif()
|
||||
# Configure and install pkgconfig files.
|
||||
foreach(t ${ARGN})
|
||||
set(configured_pc "${generated_dir}/${t}.pc")
|
||||
configure_file("${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in"
|
||||
"${configured_pc}" @ONLY)
|
||||
install(FILES "${configured_pc}"
|
||||
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
|
||||
endforeach()
|
||||
endif()
|
||||
endfunction()
|
||||
|
|
|
|||
21
Engine/lib/assimp/contrib/gtest/cmake/libgtest.la.in
Normal file
21
Engine/lib/assimp/contrib/gtest/cmake/libgtest.la.in
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
# libgtest.la - a libtool library file
|
||||
# Generated by libtool (GNU libtool) 2.4.6
|
||||
|
||||
# Please DO NOT delete this file!
|
||||
# It is necessary for linking the library.
|
||||
|
||||
# Names of this library.
|
||||
library_names='libgtest.so'
|
||||
|
||||
# Is this an already installed library?
|
||||
installed=yes
|
||||
|
||||
# Should we warn about portability when linking against -modules?
|
||||
shouldnotlink=no
|
||||
|
||||
# Files to dlopen/dlpreopen
|
||||
dlopen=''
|
||||
dlpreopen=''
|
||||
|
||||
# Directory that this library needs to be installed in:
|
||||
libdir='@CMAKE_INSTALL_FULL_LIBDIR@'
|
||||
4
Engine/lib/assimp/contrib/gtest/docs/README.md
Normal file
4
Engine/lib/assimp/contrib/gtest/docs/README.md
Normal file
|
|
@ -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.
|
||||
|
|
@ -0,0 +1,237 @@
|
|||
// Copyright 2005, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This file implements the AssertionResult type.
|
||||
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_
|
||||
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#include "gtest/gtest-message.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
namespace testing {
|
||||
|
||||
// A class for indicating whether an assertion was successful. When
|
||||
// the assertion wasn't successful, the AssertionResult object
|
||||
// remembers a non-empty message that describes how it failed.
|
||||
//
|
||||
// To create an instance of this class, use one of the factory functions
|
||||
// (AssertionSuccess() and AssertionFailure()).
|
||||
//
|
||||
// This class is useful for two purposes:
|
||||
// 1. Defining predicate functions to be used with Boolean test assertions
|
||||
// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
|
||||
// 2. Defining predicate-format functions to be
|
||||
// used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
|
||||
//
|
||||
// For example, if you define IsEven predicate:
|
||||
//
|
||||
// testing::AssertionResult IsEven(int n) {
|
||||
// if ((n % 2) == 0)
|
||||
// return testing::AssertionSuccess();
|
||||
// else
|
||||
// return testing::AssertionFailure() << n << " is odd";
|
||||
// }
|
||||
//
|
||||
// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
|
||||
// will print the message
|
||||
//
|
||||
// Value of: IsEven(Fib(5))
|
||||
// Actual: false (5 is odd)
|
||||
// Expected: true
|
||||
//
|
||||
// instead of a more opaque
|
||||
//
|
||||
// Value of: IsEven(Fib(5))
|
||||
// Actual: false
|
||||
// Expected: true
|
||||
//
|
||||
// in case IsEven is a simple Boolean predicate.
|
||||
//
|
||||
// If you expect your predicate to be reused and want to support informative
|
||||
// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
|
||||
// about half as often as positive ones in our tests), supply messages for
|
||||
// both success and failure cases:
|
||||
//
|
||||
// testing::AssertionResult IsEven(int n) {
|
||||
// if ((n % 2) == 0)
|
||||
// return testing::AssertionSuccess() << n << " is even";
|
||||
// else
|
||||
// return testing::AssertionFailure() << n << " is odd";
|
||||
// }
|
||||
//
|
||||
// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
|
||||
//
|
||||
// Value of: IsEven(Fib(6))
|
||||
// Actual: true (8 is even)
|
||||
// Expected: false
|
||||
//
|
||||
// NB: Predicates that support negative Boolean assertions have reduced
|
||||
// performance in positive ones so be careful not to use them in tests
|
||||
// that have lots (tens of thousands) of positive Boolean assertions.
|
||||
//
|
||||
// To use this class with EXPECT_PRED_FORMAT assertions such as:
|
||||
//
|
||||
// // Verifies that Foo() returns an even number.
|
||||
// EXPECT_PRED_FORMAT1(IsEven, Foo());
|
||||
//
|
||||
// you need to define:
|
||||
//
|
||||
// testing::AssertionResult IsEven(const char* expr, int n) {
|
||||
// if ((n % 2) == 0)
|
||||
// return testing::AssertionSuccess();
|
||||
// else
|
||||
// return testing::AssertionFailure()
|
||||
// << "Expected: " << expr << " is even\n Actual: it's " << n;
|
||||
// }
|
||||
//
|
||||
// If Foo() returns 5, you will see the following message:
|
||||
//
|
||||
// Expected: Foo() is even
|
||||
// Actual: it's 5
|
||||
//
|
||||
class GTEST_API_ AssertionResult {
|
||||
public:
|
||||
// Copy constructor.
|
||||
// Used in EXPECT_TRUE/FALSE(assertion_result).
|
||||
AssertionResult(const AssertionResult& other);
|
||||
|
||||
// C4800 is a level 3 warning in Visual Studio 2015 and earlier.
|
||||
// This warning is not emitted in Visual Studio 2017.
|
||||
// This warning is off by default starting in Visual Studio 2019 but can be
|
||||
// enabled with command-line options.
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)
|
||||
#endif
|
||||
|
||||
// Used in the EXPECT_TRUE/FALSE(bool_expression).
|
||||
//
|
||||
// T must be contextually convertible to bool.
|
||||
//
|
||||
// The second parameter prevents this overload from being considered if
|
||||
// the argument is implicitly convertible to AssertionResult. In that case
|
||||
// we want AssertionResult's copy constructor to be used.
|
||||
template <typename T>
|
||||
explicit AssertionResult(
|
||||
const T& success,
|
||||
typename std::enable_if<
|
||||
!std::is_convertible<T, AssertionResult>::value>::type*
|
||||
/*enabler*/
|
||||
= nullptr)
|
||||
: success_(success) {}
|
||||
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_()
|
||||
#endif
|
||||
|
||||
// Assignment operator.
|
||||
AssertionResult& operator=(AssertionResult other) {
|
||||
swap(other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Returns true if and only if the assertion succeeded.
|
||||
operator bool() const { return success_; } // NOLINT
|
||||
|
||||
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
|
||||
AssertionResult operator!() const;
|
||||
|
||||
// Returns the text streamed into this AssertionResult. Test assertions
|
||||
// use it when they fail (i.e., the predicate's outcome doesn't match the
|
||||
// assertion's expectation). When nothing has been streamed into the
|
||||
// object, returns an empty string.
|
||||
const char* message() const {
|
||||
return message_.get() != nullptr ? message_->c_str() : "";
|
||||
}
|
||||
// Deprecated; please use message() instead.
|
||||
const char* failure_message() const { return message(); }
|
||||
|
||||
// Streams a custom failure message into this object.
|
||||
template <typename T>
|
||||
AssertionResult& operator<<(const T& value) {
|
||||
AppendMessage(Message() << value);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Allows streaming basic output manipulators such as endl or flush into
|
||||
// this object.
|
||||
AssertionResult& operator<<(
|
||||
::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
|
||||
AppendMessage(Message() << basic_manipulator);
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
// Appends the contents of message to message_.
|
||||
void AppendMessage(const Message& a_message) {
|
||||
if (message_.get() == nullptr) message_.reset(new ::std::string);
|
||||
message_->append(a_message.GetString().c_str());
|
||||
}
|
||||
|
||||
// Swap the contents of this AssertionResult with other.
|
||||
void swap(AssertionResult& other);
|
||||
|
||||
// Stores result of the assertion predicate.
|
||||
bool success_;
|
||||
// Stores the message describing the condition in case the expectation
|
||||
// construct is not satisfied with the predicate's outcome.
|
||||
// Referenced via a pointer to avoid taking too much stack frame space
|
||||
// with test assertions.
|
||||
std::unique_ptr< ::std::string> message_;
|
||||
};
|
||||
|
||||
// Makes a successful assertion result.
|
||||
GTEST_API_ AssertionResult AssertionSuccess();
|
||||
|
||||
// Makes a failed assertion result.
|
||||
GTEST_API_ AssertionResult AssertionFailure();
|
||||
|
||||
// Makes a failed assertion result with the given failure message.
|
||||
// Deprecated; use AssertionFailure() << msg.
|
||||
GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
|
||||
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_
|
||||
|
|
@ -26,22 +26,22 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines the public API for death tests. It is
|
||||
// #included by gtest.h so a user doesn't need to include this
|
||||
// directly.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
|
||||
#include "gtest/internal/gtest-death-test-internal.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This flag controls the style of death tests. Valid values are "threadsafe",
|
||||
// meaning that the death test child process will re-execute the test binary
|
||||
// from the start, running only a single death test, or "fast",
|
||||
|
|
@ -49,6 +49,8 @@ namespace testing {
|
|||
// after forking.
|
||||
GTEST_DECLARE_string_(death_test_style);
|
||||
|
||||
namespace testing {
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
namespace internal {
|
||||
|
|
@ -97,12 +99,16 @@ GTEST_API_ bool InDeathTestChild();
|
|||
//
|
||||
// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!");
|
||||
//
|
||||
// The final parameter to each of these macros is a matcher applied to any data
|
||||
// the sub-process wrote to stderr. For compatibility with existing tests, a
|
||||
// bare string is interpreted as a regular expression matcher.
|
||||
//
|
||||
// On the regular expressions used in death tests:
|
||||
//
|
||||
// On POSIX-compliant systems (*nix), we use the <regex.h> library,
|
||||
// which uses the POSIX extended regex syntax.
|
||||
//
|
||||
// On other platforms (e.g. Windows), we only support a simple regex
|
||||
// On other platforms (e.g. Windows or Mac), we only support a simple regex
|
||||
// syntax implemented as part of Google Test. This limited
|
||||
// implementation should be enough most of the time when writing
|
||||
// death tests; though it lacks many features you can find in PCRE
|
||||
|
|
@ -160,29 +166,28 @@ GTEST_API_ bool InDeathTestChild();
|
|||
// is rarely a problem as people usually don't put the test binary
|
||||
// directory in PATH.
|
||||
//
|
||||
// TODO(wan@google.com): make thread-safe death tests search the PATH.
|
||||
|
||||
// Asserts that a given statement causes the program to exit, with an
|
||||
// integer exit status that satisfies predicate, and emitting error output
|
||||
// that matches regex.
|
||||
# define ASSERT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_)
|
||||
// Asserts that a given `statement` causes the program to exit, with an
|
||||
// integer exit status that satisfies `predicate`, and emitting error output
|
||||
// that matches `matcher`.
|
||||
#define ASSERT_EXIT(statement, predicate, matcher) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)
|
||||
|
||||
// Like ASSERT_EXIT, but continues on to successive tests in the
|
||||
// test case, if any:
|
||||
# define EXPECT_EXIT(statement, predicate, regex) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_)
|
||||
// Like `ASSERT_EXIT`, but continues on to successive tests in the
|
||||
// test suite, if any:
|
||||
#define EXPECT_EXIT(statement, predicate, matcher) \
|
||||
GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)
|
||||
|
||||
// Asserts that a given statement causes the program to exit, either by
|
||||
// Asserts that a given `statement` causes the program to exit, either by
|
||||
// explicitly exiting with a nonzero exit code or being killed by a
|
||||
// signal, and emitting error output that matches regex.
|
||||
# define ASSERT_DEATH(statement, regex) \
|
||||
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
// signal, and emitting error output that matches `matcher`.
|
||||
#define ASSERT_DEATH(statement, matcher) \
|
||||
ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
|
||||
|
||||
// Like ASSERT_DEATH, but continues on to successive tests in the
|
||||
// test case, if any:
|
||||
# define EXPECT_DEATH(statement, regex) \
|
||||
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex)
|
||||
// Like `ASSERT_DEATH`, but continues on to successive tests in the
|
||||
// test suite, if any:
|
||||
#define EXPECT_DEATH(statement, matcher) \
|
||||
EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)
|
||||
|
||||
// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:
|
||||
|
||||
|
|
@ -190,25 +195,26 @@ GTEST_API_ bool InDeathTestChild();
|
|||
class GTEST_API_ ExitedWithCode {
|
||||
public:
|
||||
explicit ExitedWithCode(int exit_code);
|
||||
ExitedWithCode(const ExitedWithCode&) = default;
|
||||
void operator=(const ExitedWithCode& other) = delete;
|
||||
bool operator()(int exit_status) const;
|
||||
private:
|
||||
// No implementation - assignment is unsupported.
|
||||
void operator=(const ExitedWithCode& other);
|
||||
|
||||
private:
|
||||
const int exit_code_;
|
||||
};
|
||||
|
||||
# if !GTEST_OS_WINDOWS
|
||||
#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA
|
||||
// Tests that an exit code describes an exit due to termination by a
|
||||
// given signal.
|
||||
class GTEST_API_ KilledBySignal {
|
||||
public:
|
||||
explicit KilledBySignal(int signum);
|
||||
bool operator()(int exit_status) const;
|
||||
|
||||
private:
|
||||
const int signum_;
|
||||
};
|
||||
# endif // !GTEST_OS_WINDOWS
|
||||
#endif // !GTEST_OS_WINDOWS
|
||||
|
||||
// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.
|
||||
// The death testing framework causes this to have interesting semantics,
|
||||
|
|
@ -226,7 +232,7 @@ class GTEST_API_ KilledBySignal {
|
|||
// return 12;
|
||||
// }
|
||||
//
|
||||
// TEST(TestCase, TestDieOr12WorksInDgbAndOpt) {
|
||||
// TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {
|
||||
// int sideeffect = 0;
|
||||
// // Only asserts in dbg.
|
||||
// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death");
|
||||
|
|
@ -253,42 +259,87 @@ class GTEST_API_ KilledBySignal {
|
|||
// EXPECT_EQ(12, DieInDebugOr12(&sideeffect));
|
||||
// }, "death");
|
||||
//
|
||||
# ifdef NDEBUG
|
||||
#ifdef NDEBUG
|
||||
|
||||
# define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
#define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
GTEST_EXECUTE_STATEMENT_(statement, regex)
|
||||
|
||||
# define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
#define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
GTEST_EXECUTE_STATEMENT_(statement, regex)
|
||||
|
||||
# else
|
||||
#else
|
||||
|
||||
# define EXPECT_DEBUG_DEATH(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
#define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex)
|
||||
|
||||
# define ASSERT_DEBUG_DEATH(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
#define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex)
|
||||
|
||||
# endif // NDEBUG for EXPECT_DEBUG_DEATH
|
||||
#endif // NDEBUG for EXPECT_DEBUG_DEATH
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// This macro is used for implementing macros such as
|
||||
// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
|
||||
// death tests are not supported. Those macros must compile on such systems
|
||||
// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters
|
||||
// on systems that support death tests. This allows one to write such a macro on
|
||||
// a system that does not support death tests and be sure that it will compile
|
||||
// on a death-test supporting system. It is exposed publicly so that systems
|
||||
// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST
|
||||
// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and
|
||||
// ASSERT_DEATH_IF_SUPPORTED.
|
||||
//
|
||||
// Parameters:
|
||||
// statement - A statement that a macro such as EXPECT_DEATH would test
|
||||
// for program termination. This macro has to make sure this
|
||||
// statement is compiled but not executed, to ensure that
|
||||
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
|
||||
// parameter if and only if EXPECT_DEATH compiles with it.
|
||||
// regex - A regex that a macro such as EXPECT_DEATH would use to test
|
||||
// the output of statement. This parameter has to be
|
||||
// compiled but not evaluated by this macro, to ensure that
|
||||
// this macro only accepts expressions that a macro such as
|
||||
// EXPECT_DEATH would accept.
|
||||
// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
|
||||
// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
|
||||
// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
|
||||
// compile inside functions where ASSERT_DEATH doesn't
|
||||
// compile.
|
||||
//
|
||||
// The branch that has an always false condition is used to ensure that
|
||||
// statement and regex are compiled (and thus syntactically correct) but
|
||||
// never executed. The unreachable code macro protects the terminator
|
||||
// statement from generating an 'unreachable code' warning in case
|
||||
// statement unconditionally returns or throws. The Message constructor at
|
||||
// the end allows the syntax of streaming additional messages into the
|
||||
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
|
||||
#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \
|
||||
<< "Statement '" #statement "' cannot be verified."; \
|
||||
} else if (::testing::internal::AlwaysFalse()) { \
|
||||
::testing::internal::RE::PartialMatch(".*", (regex)); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
terminator; \
|
||||
} else \
|
||||
::testing::Message()
|
||||
|
||||
// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and
|
||||
// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if
|
||||
// death tests are supported; otherwise they just issue a warning. This is
|
||||
// useful when you are combining death test assertions with normal test
|
||||
// assertions in one test.
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
EXPECT_DEATH(statement, regex)
|
||||
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
ASSERT_DEATH(statement, regex)
|
||||
#else
|
||||
# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, )
|
||||
# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return)
|
||||
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )
|
||||
#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
|
||||
GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)
|
||||
#endif
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
|
||||
|
|
|
|||
956
Engine/lib/assimp/contrib/gtest/include/gtest/gtest-matchers.h
Normal file
956
Engine/lib/assimp/contrib/gtest/include/gtest/gtest-matchers.h
Normal file
|
|
@ -0,0 +1,956 @@
|
|||
// 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.
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This file implements just enough of the matcher interface to allow
|
||||
// EXPECT_DEATH and friends to accept a matcher argument.
|
||||
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#include "gtest/gtest-printers.h"
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
// MSVC warning C5046 is new as of VS2017 version 15.8.
|
||||
#if defined(_MSC_VER) && _MSC_VER >= 1915
|
||||
#define GTEST_MAYBE_5046_ 5046
|
||||
#else
|
||||
#define GTEST_MAYBE_5046_
|
||||
#endif
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(
|
||||
4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
|
||||
clients of class B */
|
||||
/* Symbol involving type with internal linkage not defined */)
|
||||
|
||||
namespace testing {
|
||||
|
||||
// To implement a matcher Foo for type T, define:
|
||||
// 1. a class FooMatcherMatcher that implements the matcher interface:
|
||||
// using is_gtest_matcher = void;
|
||||
// bool MatchAndExplain(const T&, std::ostream*);
|
||||
// (MatchResultListener* can also be used instead of std::ostream*)
|
||||
// void DescribeTo(std::ostream*);
|
||||
// void DescribeNegationTo(std::ostream*);
|
||||
//
|
||||
// 2. a factory function that creates a Matcher<T> object from a
|
||||
// FooMatcherMatcher.
|
||||
|
||||
class MatchResultListener {
|
||||
public:
|
||||
// Creates a listener object with the given underlying ostream. The
|
||||
// listener does not own the ostream, and does not dereference it
|
||||
// in the constructor or destructor.
|
||||
explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
|
||||
virtual ~MatchResultListener() = 0; // Makes this class abstract.
|
||||
|
||||
// Streams x to the underlying ostream; does nothing if the ostream
|
||||
// is NULL.
|
||||
template <typename T>
|
||||
MatchResultListener& operator<<(const T& x) {
|
||||
if (stream_ != nullptr) *stream_ << x;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Returns the underlying ostream.
|
||||
::std::ostream* stream() { return stream_; }
|
||||
|
||||
// Returns true if and only if the listener is interested in an explanation
|
||||
// of the match result. A matcher's MatchAndExplain() method can use
|
||||
// this information to avoid generating the explanation when no one
|
||||
// intends to hear it.
|
||||
bool IsInterested() const { return stream_ != nullptr; }
|
||||
|
||||
private:
|
||||
::std::ostream* const stream_;
|
||||
|
||||
MatchResultListener(const MatchResultListener&) = delete;
|
||||
MatchResultListener& operator=(const MatchResultListener&) = delete;
|
||||
};
|
||||
|
||||
inline MatchResultListener::~MatchResultListener() {}
|
||||
|
||||
// An instance of a subclass of this knows how to describe itself as a
|
||||
// matcher.
|
||||
class GTEST_API_ MatcherDescriberInterface {
|
||||
public:
|
||||
virtual ~MatcherDescriberInterface() {}
|
||||
|
||||
// Describes this matcher to an ostream. The function should print
|
||||
// a verb phrase that describes the property a value matching this
|
||||
// matcher should have. The subject of the verb phrase is the value
|
||||
// being matched. For example, the DescribeTo() method of the Gt(7)
|
||||
// matcher prints "is greater than 7".
|
||||
virtual void DescribeTo(::std::ostream* os) const = 0;
|
||||
|
||||
// Describes the negation of this matcher to an ostream. For
|
||||
// example, if the description of this matcher is "is greater than
|
||||
// 7", the negated description could be "is not greater than 7".
|
||||
// You are not required to override this when implementing
|
||||
// MatcherInterface, but it is highly advised so that your matcher
|
||||
// can produce good error messages.
|
||||
virtual void DescribeNegationTo(::std::ostream* os) const {
|
||||
*os << "not (";
|
||||
DescribeTo(os);
|
||||
*os << ")";
|
||||
}
|
||||
};
|
||||
|
||||
// The implementation of a matcher.
|
||||
template <typename T>
|
||||
class MatcherInterface : public MatcherDescriberInterface {
|
||||
public:
|
||||
// Returns true if and only if the matcher matches x; also explains the
|
||||
// match result to 'listener' if necessary (see the next paragraph), in
|
||||
// the form of a non-restrictive relative clause ("which ...",
|
||||
// "whose ...", etc) that describes x. For example, the
|
||||
// MatchAndExplain() method of the Pointee(...) matcher should
|
||||
// generate an explanation like "which points to ...".
|
||||
//
|
||||
// Implementations of MatchAndExplain() should add an explanation of
|
||||
// the match result *if and only if* they can provide additional
|
||||
// information that's not already present (or not obvious) in the
|
||||
// print-out of x and the matcher's description. Whether the match
|
||||
// succeeds is not a factor in deciding whether an explanation is
|
||||
// needed, as sometimes the caller needs to print a failure message
|
||||
// when the match succeeds (e.g. when the matcher is used inside
|
||||
// Not()).
|
||||
//
|
||||
// For example, a "has at least 10 elements" matcher should explain
|
||||
// what the actual element count is, regardless of the match result,
|
||||
// as it is useful information to the reader; on the other hand, an
|
||||
// "is empty" matcher probably only needs to explain what the actual
|
||||
// size is when the match fails, as it's redundant to say that the
|
||||
// size is 0 when the value is already known to be empty.
|
||||
//
|
||||
// You should override this method when defining a new matcher.
|
||||
//
|
||||
// It's the responsibility of the caller (Google Test) to guarantee
|
||||
// that 'listener' is not NULL. This helps to simplify a matcher's
|
||||
// implementation when it doesn't care about the performance, as it
|
||||
// can talk to 'listener' without checking its validity first.
|
||||
// However, in order to implement dummy listeners efficiently,
|
||||
// listener->stream() may be NULL.
|
||||
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
|
||||
|
||||
// Inherits these methods from MatcherDescriberInterface:
|
||||
// virtual void DescribeTo(::std::ostream* os) const = 0;
|
||||
// virtual void DescribeNegationTo(::std::ostream* os) const;
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
||||
struct AnyEq {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const {
|
||||
return a == b;
|
||||
}
|
||||
};
|
||||
struct AnyNe {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const {
|
||||
return a != b;
|
||||
}
|
||||
};
|
||||
struct AnyLt {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const {
|
||||
return a < b;
|
||||
}
|
||||
};
|
||||
struct AnyGt {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const {
|
||||
return a > b;
|
||||
}
|
||||
};
|
||||
struct AnyLe {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const {
|
||||
return a <= b;
|
||||
}
|
||||
};
|
||||
struct AnyGe {
|
||||
template <typename A, typename B>
|
||||
bool operator()(const A& a, const B& b) const {
|
||||
return a >= b;
|
||||
}
|
||||
};
|
||||
|
||||
// A match result listener that ignores the explanation.
|
||||
class DummyMatchResultListener : public MatchResultListener {
|
||||
public:
|
||||
DummyMatchResultListener() : MatchResultListener(nullptr) {}
|
||||
|
||||
private:
|
||||
DummyMatchResultListener(const DummyMatchResultListener&) = delete;
|
||||
DummyMatchResultListener& operator=(const DummyMatchResultListener&) = delete;
|
||||
};
|
||||
|
||||
// A match result listener that forwards the explanation to a given
|
||||
// ostream. The difference between this and MatchResultListener is
|
||||
// that the former is concrete.
|
||||
class StreamMatchResultListener : public MatchResultListener {
|
||||
public:
|
||||
explicit StreamMatchResultListener(::std::ostream* os)
|
||||
: MatchResultListener(os) {}
|
||||
|
||||
private:
|
||||
StreamMatchResultListener(const StreamMatchResultListener&) = delete;
|
||||
StreamMatchResultListener& operator=(const StreamMatchResultListener&) =
|
||||
delete;
|
||||
};
|
||||
|
||||
struct SharedPayloadBase {
|
||||
std::atomic<int> ref{1};
|
||||
void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
|
||||
bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct SharedPayload : SharedPayloadBase {
|
||||
explicit SharedPayload(const T& v) : value(v) {}
|
||||
explicit SharedPayload(T&& v) : value(std::move(v)) {}
|
||||
|
||||
static void Destroy(SharedPayloadBase* shared) {
|
||||
delete static_cast<SharedPayload*>(shared);
|
||||
}
|
||||
|
||||
T value;
|
||||
};
|
||||
|
||||
// An internal class for implementing Matcher<T>, which will derive
|
||||
// from it. We put functionalities common to all Matcher<T>
|
||||
// specializations here to avoid code duplication.
|
||||
template <typename T>
|
||||
class MatcherBase : private MatcherDescriberInterface {
|
||||
public:
|
||||
// Returns true if and only if the matcher matches x; also explains the
|
||||
// match result to 'listener'.
|
||||
bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
|
||||
GTEST_CHECK_(vtable_ != nullptr);
|
||||
return vtable_->match_and_explain(*this, x, listener);
|
||||
}
|
||||
|
||||
// Returns true if and only if this matcher matches x.
|
||||
bool Matches(const T& x) const {
|
||||
DummyMatchResultListener dummy;
|
||||
return MatchAndExplain(x, &dummy);
|
||||
}
|
||||
|
||||
// Describes this matcher to an ostream.
|
||||
void DescribeTo(::std::ostream* os) const final {
|
||||
GTEST_CHECK_(vtable_ != nullptr);
|
||||
vtable_->describe(*this, os, false);
|
||||
}
|
||||
|
||||
// Describes the negation of this matcher to an ostream.
|
||||
void DescribeNegationTo(::std::ostream* os) const final {
|
||||
GTEST_CHECK_(vtable_ != nullptr);
|
||||
vtable_->describe(*this, os, true);
|
||||
}
|
||||
|
||||
// Explains why x matches, or doesn't match, the matcher.
|
||||
void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
|
||||
StreamMatchResultListener listener(os);
|
||||
MatchAndExplain(x, &listener);
|
||||
}
|
||||
|
||||
// Returns the describer for this matcher object; retains ownership
|
||||
// of the describer, which is only guaranteed to be alive when
|
||||
// this matcher object is alive.
|
||||
const MatcherDescriberInterface* GetDescriber() const {
|
||||
if (vtable_ == nullptr) return nullptr;
|
||||
return vtable_->get_describer(*this);
|
||||
}
|
||||
|
||||
protected:
|
||||
MatcherBase() : vtable_(nullptr), buffer_() {}
|
||||
|
||||
// Constructs a matcher from its implementation.
|
||||
template <typename U>
|
||||
explicit MatcherBase(const MatcherInterface<U>* impl)
|
||||
: vtable_(nullptr), buffer_() {
|
||||
Init(impl);
|
||||
}
|
||||
|
||||
template <typename M, typename = typename std::remove_reference<
|
||||
M>::type::is_gtest_matcher>
|
||||
MatcherBase(M&& m) : vtable_(nullptr), buffer_() { // NOLINT
|
||||
Init(std::forward<M>(m));
|
||||
}
|
||||
|
||||
MatcherBase(const MatcherBase& other)
|
||||
: vtable_(other.vtable_), buffer_(other.buffer_) {
|
||||
if (IsShared()) buffer_.shared->Ref();
|
||||
}
|
||||
|
||||
MatcherBase& operator=(const MatcherBase& other) {
|
||||
if (this == &other) return *this;
|
||||
Destroy();
|
||||
vtable_ = other.vtable_;
|
||||
buffer_ = other.buffer_;
|
||||
if (IsShared()) buffer_.shared->Ref();
|
||||
return *this;
|
||||
}
|
||||
|
||||
MatcherBase(MatcherBase&& other)
|
||||
: vtable_(other.vtable_), buffer_(other.buffer_) {
|
||||
other.vtable_ = nullptr;
|
||||
}
|
||||
|
||||
MatcherBase& operator=(MatcherBase&& other) {
|
||||
if (this == &other) return *this;
|
||||
Destroy();
|
||||
vtable_ = other.vtable_;
|
||||
buffer_ = other.buffer_;
|
||||
other.vtable_ = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
~MatcherBase() override { Destroy(); }
|
||||
|
||||
private:
|
||||
struct VTable {
|
||||
bool (*match_and_explain)(const MatcherBase&, const T&,
|
||||
MatchResultListener*);
|
||||
void (*describe)(const MatcherBase&, std::ostream*, bool negation);
|
||||
// Returns the captured object if it implements the interface, otherwise
|
||||
// returns the MatcherBase itself.
|
||||
const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
|
||||
// Called on shared instances when the reference count reaches 0.
|
||||
void (*shared_destroy)(SharedPayloadBase*);
|
||||
};
|
||||
|
||||
bool IsShared() const {
|
||||
return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
|
||||
}
|
||||
|
||||
// If the implementation uses a listener, call that.
|
||||
template <typename P>
|
||||
static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
|
||||
MatchResultListener* listener)
|
||||
-> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
|
||||
return P::Get(m).MatchAndExplain(value, listener->stream());
|
||||
}
|
||||
|
||||
template <typename P>
|
||||
static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
|
||||
MatchResultListener* listener)
|
||||
-> decltype(P::Get(m).MatchAndExplain(value, listener)) {
|
||||
return P::Get(m).MatchAndExplain(value, listener);
|
||||
}
|
||||
|
||||
template <typename P>
|
||||
static void DescribeImpl(const MatcherBase& m, std::ostream* os,
|
||||
bool negation) {
|
||||
if (negation) {
|
||||
P::Get(m).DescribeNegationTo(os);
|
||||
} else {
|
||||
P::Get(m).DescribeTo(os);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename P>
|
||||
static const MatcherDescriberInterface* GetDescriberImpl(
|
||||
const MatcherBase& m) {
|
||||
// If the impl is a MatcherDescriberInterface, then return it.
|
||||
// Otherwise use MatcherBase itself.
|
||||
// This allows us to implement the GetDescriber() function without support
|
||||
// from the impl, but some users really want to get their impl back when
|
||||
// they call GetDescriber().
|
||||
// We use std::get on a tuple as a workaround of not having `if constexpr`.
|
||||
return std::get<(
|
||||
std::is_convertible<decltype(&P::Get(m)),
|
||||
const MatcherDescriberInterface*>::value
|
||||
? 1
|
||||
: 0)>(std::make_tuple(&m, &P::Get(m)));
|
||||
}
|
||||
|
||||
template <typename P>
|
||||
const VTable* GetVTable() {
|
||||
static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
|
||||
&DescribeImpl<P>, &GetDescriberImpl<P>,
|
||||
P::shared_destroy};
|
||||
return &kVTable;
|
||||
}
|
||||
|
||||
union Buffer {
|
||||
// Add some types to give Buffer some common alignment/size use cases.
|
||||
void* ptr;
|
||||
double d;
|
||||
int64_t i;
|
||||
// And add one for the out-of-line cases.
|
||||
SharedPayloadBase* shared;
|
||||
};
|
||||
|
||||
void Destroy() {
|
||||
if (IsShared() && buffer_.shared->Unref()) {
|
||||
vtable_->shared_destroy(buffer_.shared);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename M>
|
||||
static constexpr bool IsInlined() {
|
||||
return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
|
||||
std::is_trivially_copy_constructible<M>::value &&
|
||||
std::is_trivially_destructible<M>::value;
|
||||
}
|
||||
|
||||
template <typename M, bool = MatcherBase::IsInlined<M>()>
|
||||
struct ValuePolicy {
|
||||
static const M& Get(const MatcherBase& m) {
|
||||
// When inlined along with Init, need to be explicit to avoid violating
|
||||
// strict aliasing rules.
|
||||
const M* ptr =
|
||||
static_cast<const M*>(static_cast<const void*>(&m.buffer_));
|
||||
return *ptr;
|
||||
}
|
||||
static void Init(MatcherBase& m, M impl) {
|
||||
::new (static_cast<void*>(&m.buffer_)) M(impl);
|
||||
}
|
||||
static constexpr auto shared_destroy = nullptr;
|
||||
};
|
||||
|
||||
template <typename M>
|
||||
struct ValuePolicy<M, false> {
|
||||
using Shared = SharedPayload<M>;
|
||||
static const M& Get(const MatcherBase& m) {
|
||||
return static_cast<Shared*>(m.buffer_.shared)->value;
|
||||
}
|
||||
template <typename Arg>
|
||||
static void Init(MatcherBase& m, Arg&& arg) {
|
||||
m.buffer_.shared = new Shared(std::forward<Arg>(arg));
|
||||
}
|
||||
static constexpr auto shared_destroy = &Shared::Destroy;
|
||||
};
|
||||
|
||||
template <typename U, bool B>
|
||||
struct ValuePolicy<const MatcherInterface<U>*, B> {
|
||||
using M = const MatcherInterface<U>;
|
||||
using Shared = SharedPayload<std::unique_ptr<M>>;
|
||||
static const M& Get(const MatcherBase& m) {
|
||||
return *static_cast<Shared*>(m.buffer_.shared)->value;
|
||||
}
|
||||
static void Init(MatcherBase& m, M* impl) {
|
||||
m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
|
||||
}
|
||||
|
||||
static constexpr auto shared_destroy = &Shared::Destroy;
|
||||
};
|
||||
|
||||
template <typename M>
|
||||
void Init(M&& m) {
|
||||
using MM = typename std::decay<M>::type;
|
||||
using Policy = ValuePolicy<MM>;
|
||||
vtable_ = GetVTable<Policy>();
|
||||
Policy::Init(*this, std::forward<M>(m));
|
||||
}
|
||||
|
||||
const VTable* vtable_;
|
||||
Buffer buffer_;
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
|
||||
// object that can check whether a value of type T matches. The
|
||||
// implementation of Matcher<T> is just a std::shared_ptr to const
|
||||
// MatcherInterface<T>. Don't inherit from Matcher!
|
||||
template <typename T>
|
||||
class Matcher : public internal::MatcherBase<T> {
|
||||
public:
|
||||
// Constructs a null matcher. Needed for storing Matcher objects in STL
|
||||
// containers. A default-constructed matcher is not yet initialized. You
|
||||
// cannot use it until a valid value has been assigned to it.
|
||||
explicit Matcher() {} // NOLINT
|
||||
|
||||
// Constructs a matcher from its implementation.
|
||||
explicit Matcher(const MatcherInterface<const T&>* impl)
|
||||
: internal::MatcherBase<T>(impl) {}
|
||||
|
||||
template <typename U>
|
||||
explicit Matcher(
|
||||
const MatcherInterface<U>* impl,
|
||||
typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
|
||||
nullptr)
|
||||
: internal::MatcherBase<T>(impl) {}
|
||||
|
||||
template <typename M, typename = typename std::remove_reference<
|
||||
M>::type::is_gtest_matcher>
|
||||
Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
|
||||
|
||||
// Implicit constructor here allows people to write
|
||||
// EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
|
||||
Matcher(T value); // NOLINT
|
||||
};
|
||||
|
||||
// The following two specializations allow the user to write str
|
||||
// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
|
||||
// matcher is expected.
|
||||
template <>
|
||||
class GTEST_API_ Matcher<const std::string&>
|
||||
: public internal::MatcherBase<const std::string&> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const std::string&>* impl)
|
||||
: internal::MatcherBase<const std::string&>(impl) {}
|
||||
|
||||
template <typename M, typename = typename std::remove_reference<
|
||||
M>::type::is_gtest_matcher>
|
||||
Matcher(M&& m) // NOLINT
|
||||
: internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a std::string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
};
|
||||
|
||||
template <>
|
||||
class GTEST_API_ Matcher<std::string>
|
||||
: public internal::MatcherBase<std::string> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const std::string&>* impl)
|
||||
: internal::MatcherBase<std::string>(impl) {}
|
||||
explicit Matcher(const MatcherInterface<std::string>* impl)
|
||||
: internal::MatcherBase<std::string>(impl) {}
|
||||
|
||||
template <typename M, typename = typename std::remove_reference<
|
||||
M>::type::is_gtest_matcher>
|
||||
Matcher(M&& m) // NOLINT
|
||||
: internal::MatcherBase<std::string>(std::forward<M>(m)) {}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
};
|
||||
|
||||
#if GTEST_INTERNAL_HAS_STRING_VIEW
|
||||
// The following two specializations allow the user to write str
|
||||
// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
|
||||
// matcher is expected.
|
||||
template <>
|
||||
class GTEST_API_ Matcher<const internal::StringView&>
|
||||
: public internal::MatcherBase<const internal::StringView&> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
|
||||
: internal::MatcherBase<const internal::StringView&>(impl) {}
|
||||
|
||||
template <typename M, typename = typename std::remove_reference<
|
||||
M>::type::is_gtest_matcher>
|
||||
Matcher(M&& m) // NOLINT
|
||||
: internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
|
||||
}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a std::string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
|
||||
// Allows the user to pass absl::string_views or std::string_views directly.
|
||||
Matcher(internal::StringView s); // NOLINT
|
||||
};
|
||||
|
||||
template <>
|
||||
class GTEST_API_ Matcher<internal::StringView>
|
||||
: public internal::MatcherBase<internal::StringView> {
|
||||
public:
|
||||
Matcher() {}
|
||||
|
||||
explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
|
||||
: internal::MatcherBase<internal::StringView>(impl) {}
|
||||
explicit Matcher(const MatcherInterface<internal::StringView>* impl)
|
||||
: internal::MatcherBase<internal::StringView>(impl) {}
|
||||
|
||||
template <typename M, typename = typename std::remove_reference<
|
||||
M>::type::is_gtest_matcher>
|
||||
Matcher(M&& m) // NOLINT
|
||||
: internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
|
||||
|
||||
// Allows the user to write str instead of Eq(str) sometimes, where
|
||||
// str is a std::string object.
|
||||
Matcher(const std::string& s); // NOLINT
|
||||
|
||||
// Allows the user to write "foo" instead of Eq("foo") sometimes.
|
||||
Matcher(const char* s); // NOLINT
|
||||
|
||||
// Allows the user to pass absl::string_views or std::string_views directly.
|
||||
Matcher(internal::StringView s); // NOLINT
|
||||
};
|
||||
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
|
||||
|
||||
// Prints a matcher in a human-readable format.
|
||||
template <typename T>
|
||||
std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
|
||||
matcher.DescribeTo(&os);
|
||||
return os;
|
||||
}
|
||||
|
||||
// The PolymorphicMatcher class template makes it easy to implement a
|
||||
// polymorphic matcher (i.e. a matcher that can match values of more
|
||||
// than one type, e.g. Eq(n) and NotNull()).
|
||||
//
|
||||
// To define a polymorphic matcher, a user should provide an Impl
|
||||
// class that has a DescribeTo() method and a DescribeNegationTo()
|
||||
// method, and define a member function (or member function template)
|
||||
//
|
||||
// bool MatchAndExplain(const Value& value,
|
||||
// MatchResultListener* listener) const;
|
||||
//
|
||||
// See the definition of NotNull() for a complete example.
|
||||
template <class Impl>
|
||||
class PolymorphicMatcher {
|
||||
public:
|
||||
explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
|
||||
|
||||
// Returns a mutable reference to the underlying matcher
|
||||
// implementation object.
|
||||
Impl& mutable_impl() { return impl_; }
|
||||
|
||||
// Returns an immutable reference to the underlying matcher
|
||||
// implementation object.
|
||||
const Impl& impl() const { return impl_; }
|
||||
|
||||
template <typename T>
|
||||
operator Matcher<T>() const {
|
||||
return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename T>
|
||||
class MonomorphicImpl : public MatcherInterface<T> {
|
||||
public:
|
||||
explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
|
||||
|
||||
void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
|
||||
|
||||
void DescribeNegationTo(::std::ostream* os) const override {
|
||||
impl_.DescribeNegationTo(os);
|
||||
}
|
||||
|
||||
bool MatchAndExplain(T x, MatchResultListener* listener) const override {
|
||||
return impl_.MatchAndExplain(x, listener);
|
||||
}
|
||||
|
||||
private:
|
||||
const Impl impl_;
|
||||
};
|
||||
|
||||
Impl impl_;
|
||||
};
|
||||
|
||||
// Creates a matcher from its implementation.
|
||||
// DEPRECATED: Especially in the generic code, prefer:
|
||||
// Matcher<T>(new MyMatcherImpl<const T&>(...));
|
||||
//
|
||||
// MakeMatcher may create a Matcher that accepts its argument by value, which
|
||||
// leads to unnecessary copies & lack of support for non-copyable types.
|
||||
template <typename T>
|
||||
inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
|
||||
return Matcher<T>(impl);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher from its implementation. This is
|
||||
// easier to use than the PolymorphicMatcher<Impl> constructor as it
|
||||
// doesn't require you to explicitly write the template argument, e.g.
|
||||
//
|
||||
// MakePolymorphicMatcher(foo);
|
||||
// vs
|
||||
// PolymorphicMatcher<TypeOfFoo>(foo);
|
||||
template <class Impl>
|
||||
inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
|
||||
return PolymorphicMatcher<Impl>(impl);
|
||||
}
|
||||
|
||||
namespace internal {
|
||||
// Implements a matcher that compares a given value with a
|
||||
// pre-supplied value using one of the ==, <=, <, etc, operators. The
|
||||
// two values being compared don't have to have the same type.
|
||||
//
|
||||
// The matcher defined here is polymorphic (for example, Eq(5) can be
|
||||
// used to match an int, a short, a double, etc). Therefore we use
|
||||
// a template type conversion operator in the implementation.
|
||||
//
|
||||
// The following template definition assumes that the Rhs parameter is
|
||||
// a "bare" type (i.e. neither 'const T' nor 'T&').
|
||||
template <typename D, typename Rhs, typename Op>
|
||||
class ComparisonBase {
|
||||
public:
|
||||
explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
|
||||
|
||||
using is_gtest_matcher = void;
|
||||
|
||||
template <typename Lhs>
|
||||
bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
|
||||
return Op()(lhs, Unwrap(rhs_));
|
||||
}
|
||||
void DescribeTo(std::ostream* os) const {
|
||||
*os << D::Desc() << " ";
|
||||
UniversalPrint(Unwrap(rhs_), os);
|
||||
}
|
||||
void DescribeNegationTo(std::ostream* os) const {
|
||||
*os << D::NegatedDesc() << " ";
|
||||
UniversalPrint(Unwrap(rhs_), os);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename T>
|
||||
static const T& Unwrap(const T& v) {
|
||||
return v;
|
||||
}
|
||||
template <typename T>
|
||||
static const T& Unwrap(std::reference_wrapper<T> v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
Rhs rhs_;
|
||||
};
|
||||
|
||||
template <typename Rhs>
|
||||
class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
|
||||
public:
|
||||
explicit EqMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {}
|
||||
static const char* Desc() { return "is equal to"; }
|
||||
static const char* NegatedDesc() { return "isn't equal to"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
|
||||
public:
|
||||
explicit NeMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {}
|
||||
static const char* Desc() { return "isn't equal to"; }
|
||||
static const char* NegatedDesc() { return "is equal to"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
|
||||
public:
|
||||
explicit LtMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {}
|
||||
static const char* Desc() { return "is <"; }
|
||||
static const char* NegatedDesc() { return "isn't <"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
|
||||
public:
|
||||
explicit GtMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {}
|
||||
static const char* Desc() { return "is >"; }
|
||||
static const char* NegatedDesc() { return "isn't >"; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
|
||||
public:
|
||||
explicit LeMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {}
|
||||
static const char* Desc() { return "is <="; }
|
||||
static const char* NegatedDesc() { return "isn't <="; }
|
||||
};
|
||||
template <typename Rhs>
|
||||
class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
|
||||
public:
|
||||
explicit GeMatcher(const Rhs& rhs)
|
||||
: ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {}
|
||||
static const char* Desc() { return "is >="; }
|
||||
static const char* NegatedDesc() { return "isn't >="; }
|
||||
};
|
||||
|
||||
template <typename T, typename = typename std::enable_if<
|
||||
std::is_constructible<std::string, T>::value>::type>
|
||||
using StringLike = T;
|
||||
|
||||
// Implements polymorphic matchers MatchesRegex(regex) and
|
||||
// ContainsRegex(regex), which can be used as a Matcher<T> as long as
|
||||
// T can be converted to a string.
|
||||
class MatchesRegexMatcher {
|
||||
public:
|
||||
MatchesRegexMatcher(const RE* regex, bool full_match)
|
||||
: regex_(regex), full_match_(full_match) {}
|
||||
|
||||
#if GTEST_INTERNAL_HAS_STRING_VIEW
|
||||
bool MatchAndExplain(const internal::StringView& s,
|
||||
MatchResultListener* listener) const {
|
||||
return MatchAndExplain(std::string(s), listener);
|
||||
}
|
||||
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
|
||||
|
||||
// Accepts pointer types, particularly:
|
||||
// const char*
|
||||
// char*
|
||||
// const wchar_t*
|
||||
// wchar_t*
|
||||
template <typename CharType>
|
||||
bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
|
||||
return s != nullptr && MatchAndExplain(std::string(s), listener);
|
||||
}
|
||||
|
||||
// Matches anything that can convert to std::string.
|
||||
//
|
||||
// This is a template, not just a plain function with const std::string&,
|
||||
// because absl::string_view has some interfering non-explicit constructors.
|
||||
template <class MatcheeStringType>
|
||||
bool MatchAndExplain(const MatcheeStringType& s,
|
||||
MatchResultListener* /* listener */) const {
|
||||
const std::string& s2(s);
|
||||
return full_match_ ? RE::FullMatch(s2, *regex_)
|
||||
: RE::PartialMatch(s2, *regex_);
|
||||
}
|
||||
|
||||
void DescribeTo(::std::ostream* os) const {
|
||||
*os << (full_match_ ? "matches" : "contains") << " regular expression ";
|
||||
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
|
||||
}
|
||||
|
||||
void DescribeNegationTo(::std::ostream* os) const {
|
||||
*os << "doesn't " << (full_match_ ? "match" : "contain")
|
||||
<< " regular expression ";
|
||||
UniversalPrinter<std::string>::Print(regex_->pattern(), os);
|
||||
}
|
||||
|
||||
private:
|
||||
const std::shared_ptr<const RE> regex_;
|
||||
const bool full_match_;
|
||||
};
|
||||
} // namespace internal
|
||||
|
||||
// Matches a string that fully matches regular expression 'regex'.
|
||||
// The matcher takes ownership of 'regex'.
|
||||
inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
|
||||
const internal::RE* regex) {
|
||||
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
|
||||
}
|
||||
template <typename T = std::string>
|
||||
PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
|
||||
const internal::StringLike<T>& regex) {
|
||||
return MatchesRegex(new internal::RE(std::string(regex)));
|
||||
}
|
||||
|
||||
// Matches a string that contains regular expression 'regex'.
|
||||
// The matcher takes ownership of 'regex'.
|
||||
inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
|
||||
const internal::RE* regex) {
|
||||
return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
|
||||
}
|
||||
template <typename T = std::string>
|
||||
PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
|
||||
const internal::StringLike<T>& regex) {
|
||||
return ContainsRegex(new internal::RE(std::string(regex)));
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything equal to x.
|
||||
// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
|
||||
// wouldn't compile.
|
||||
template <typename T>
|
||||
inline internal::EqMatcher<T> Eq(T x) {
|
||||
return internal::EqMatcher<T>(x);
|
||||
}
|
||||
|
||||
// Constructs a Matcher<T> from a 'value' of type T. The constructed
|
||||
// matcher matches any value that's equal to 'value'.
|
||||
template <typename T>
|
||||
Matcher<T>::Matcher(T value) {
|
||||
*this = Eq(value);
|
||||
}
|
||||
|
||||
// Creates a monomorphic matcher that matches anything with type Lhs
|
||||
// and equal to rhs. A user may need to use this instead of Eq(...)
|
||||
// in order to resolve an overloading ambiguity.
|
||||
//
|
||||
// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
|
||||
// or Matcher<T>(x), but more readable than the latter.
|
||||
//
|
||||
// We could define similar monomorphic matchers for other comparison
|
||||
// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
|
||||
// it yet as those are used much less than Eq() in practice. A user
|
||||
// can always write Matcher<T>(Lt(5)) to be explicit about the type,
|
||||
// for example.
|
||||
template <typename Lhs, typename Rhs>
|
||||
inline Matcher<Lhs> TypedEq(const Rhs& rhs) {
|
||||
return Eq(rhs);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything >= x.
|
||||
template <typename Rhs>
|
||||
inline internal::GeMatcher<Rhs> Ge(Rhs x) {
|
||||
return internal::GeMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything > x.
|
||||
template <typename Rhs>
|
||||
inline internal::GtMatcher<Rhs> Gt(Rhs x) {
|
||||
return internal::GtMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything <= x.
|
||||
template <typename Rhs>
|
||||
inline internal::LeMatcher<Rhs> Le(Rhs x) {
|
||||
return internal::LeMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything < x.
|
||||
template <typename Rhs>
|
||||
inline internal::LtMatcher<Rhs> Lt(Rhs x) {
|
||||
return internal::LtMatcher<Rhs>(x);
|
||||
}
|
||||
|
||||
// Creates a polymorphic matcher that matches anything != x.
|
||||
template <typename Rhs>
|
||||
inline internal::NeMatcher<Rhs> Ne(Rhs x) {
|
||||
return internal::NeMatcher<Rhs>(x);
|
||||
}
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
|
||||
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
|
||||
|
|
@ -26,10 +26,8 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines the Message class.
|
||||
//
|
||||
|
|
@ -43,13 +41,22 @@
|
|||
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
|
||||
// program!
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
// Ensures that there is at least one operator<< in the global namespace.
|
||||
// See Message& operator<<(...) below for why.
|
||||
void operator<<(const testing::internal::Secret&, int);
|
||||
|
|
@ -102,18 +109,10 @@ class GTEST_API_ Message {
|
|||
*ss_ << str;
|
||||
}
|
||||
|
||||
#if GTEST_OS_SYMBIAN
|
||||
// Streams a value (either a pointer or not) to this object.
|
||||
template <typename T>
|
||||
inline Message& operator <<(const T& value) {
|
||||
StreamHelper(typename internal::is_pointer<T>::type(), value);
|
||||
return *this;
|
||||
}
|
||||
#else
|
||||
// Streams a non-pointer value to this object.
|
||||
template <typename T>
|
||||
inline Message& operator <<(const T& val) {
|
||||
// Some libraries overload << for STL containers. These
|
||||
inline Message& operator<<(const T& val) {
|
||||
// Some libraries overload << for STL containers. These
|
||||
// overloads are defined in the global namespace instead of ::std.
|
||||
//
|
||||
// C++'s symbol lookup rule (i.e. Koenig lookup) says that these
|
||||
|
|
@ -127,7 +126,7 @@ class GTEST_API_ Message {
|
|||
// from the global namespace. With this using declaration,
|
||||
// overloads of << defined in the global namespace and those
|
||||
// visible via Koenig lookup are both exposed in this function.
|
||||
using ::operator <<;
|
||||
using ::operator<<;
|
||||
*ss_ << val;
|
||||
return *this;
|
||||
}
|
||||
|
|
@ -146,15 +145,14 @@ class GTEST_API_ Message {
|
|||
// ensure consistent result across compilers, we always treat NULL
|
||||
// as "(null)".
|
||||
template <typename T>
|
||||
inline Message& operator <<(T* const& pointer) { // NOLINT
|
||||
if (pointer == NULL) {
|
||||
inline Message& operator<<(T* const& pointer) { // NOLINT
|
||||
if (pointer == nullptr) {
|
||||
*ss_ << "(null)";
|
||||
} else {
|
||||
*ss_ << pointer;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
|
||||
// Since the basic IO manipulators are overloaded for both narrow
|
||||
// and wide streams, we have to provide this specialized definition
|
||||
|
|
@ -162,33 +160,25 @@ class GTEST_API_ Message {
|
|||
// templatized version above. Without this definition, streaming
|
||||
// endl or other basic IO manipulators to Message will confuse the
|
||||
// compiler.
|
||||
Message& operator <<(BasicNarrowIoManip val) {
|
||||
Message& operator<<(BasicNarrowIoManip val) {
|
||||
*ss_ << val;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Instead of 1/0, we want to see true/false for bool values.
|
||||
Message& operator <<(bool b) {
|
||||
return *this << (b ? "true" : "false");
|
||||
}
|
||||
Message& operator<<(bool b) { return *this << (b ? "true" : "false"); }
|
||||
|
||||
// These two overloads allow streaming a wide C string to a Message
|
||||
// using the UTF-8 encoding.
|
||||
Message& operator <<(const wchar_t* wide_c_str);
|
||||
Message& operator <<(wchar_t* wide_c_str);
|
||||
Message& operator<<(const wchar_t* wide_c_str);
|
||||
Message& operator<<(wchar_t* wide_c_str);
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
// Converts the given wide string to a narrow string using the UTF-8
|
||||
// encoding, and streams the result to this Message object.
|
||||
Message& operator <<(const ::std::wstring& wstr);
|
||||
Message& operator<<(const ::std::wstring& wstr);
|
||||
#endif // GTEST_HAS_STD_WSTRING
|
||||
|
||||
#if GTEST_HAS_GLOBAL_WSTRING
|
||||
// Converts the given wide string to a narrow string using the UTF-8
|
||||
// encoding, and streams the result to this Message object.
|
||||
Message& operator <<(const ::wstring& wstr);
|
||||
#endif // GTEST_HAS_GLOBAL_WSTRING
|
||||
|
||||
// Gets the text streamed to this object so far as an std::string.
|
||||
// Each '\0' character in the buffer is replaced with "\\0".
|
||||
//
|
||||
|
|
@ -196,32 +186,8 @@ class GTEST_API_ Message {
|
|||
std::string GetString() const;
|
||||
|
||||
private:
|
||||
|
||||
#if GTEST_OS_SYMBIAN
|
||||
// These are needed as the Nokia Symbian Compiler cannot decide between
|
||||
// const T& and const T* in a function template. The Nokia compiler _can_
|
||||
// decide between class template specializations for T and T*, so a
|
||||
// tr1::type_traits-like is_pointer works, and we can overload on that.
|
||||
template <typename T>
|
||||
inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) {
|
||||
if (pointer == NULL) {
|
||||
*ss_ << "(null)";
|
||||
} else {
|
||||
*ss_ << pointer;
|
||||
}
|
||||
}
|
||||
template <typename T>
|
||||
inline void StreamHelper(internal::false_type /*is_pointer*/,
|
||||
const T& value) {
|
||||
// See the comments in Message& operator <<(const T&) above for why
|
||||
// we need this using statement.
|
||||
using ::operator <<;
|
||||
*ss_ << value;
|
||||
}
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
|
||||
// We'll hold the text streamed to this object here.
|
||||
const internal::scoped_ptr< ::std::stringstream> ss_;
|
||||
const std::unique_ptr< ::std::stringstream> ss_;
|
||||
|
||||
// We declare (but don't implement) this to prevent the compiler
|
||||
// from implementing the assignment operator.
|
||||
|
|
@ -229,7 +195,7 @@ class GTEST_API_ Message {
|
|||
};
|
||||
|
||||
// Streams a Message to an ostream.
|
||||
inline std::ostream& operator <<(std::ostream& os, const Message& sb) {
|
||||
inline std::ostream& operator<<(std::ostream& os, const Message& sb) {
|
||||
return os << sb.GetString();
|
||||
}
|
||||
|
||||
|
|
@ -247,4 +213,6 @@ std::string StreamableToString(const T& streamable) {
|
|||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -26,17 +26,18 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
|
||||
// Utilities for testing Google Test itself and code that uses Google Test
|
||||
// (e.g. frameworks built on top of Google Test).
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This helper class can be used to mock out Google Test failure reporting
|
||||
|
|
@ -68,14 +69,15 @@ class GTEST_API_ ScopedFakeTestPartResultReporter
|
|||
TestPartResultArray* result);
|
||||
|
||||
// The d'tor restores the previous test part result reporter.
|
||||
virtual ~ScopedFakeTestPartResultReporter();
|
||||
~ScopedFakeTestPartResultReporter() override;
|
||||
|
||||
// Appends the TestPartResult object to the TestPartResultArray
|
||||
// received in the constructor.
|
||||
//
|
||||
// This method is from the TestPartResultReporterInterface
|
||||
// interface.
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
void ReportTestPartResult(const TestPartResult& result) override;
|
||||
|
||||
private:
|
||||
void Init();
|
||||
|
||||
|
|
@ -83,7 +85,10 @@ class GTEST_API_ ScopedFakeTestPartResultReporter
|
|||
TestPartResultReporterInterface* old_reporter_;
|
||||
TestPartResultArray* const result_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
|
||||
ScopedFakeTestPartResultReporter(const ScopedFakeTestPartResultReporter&) =
|
||||
delete;
|
||||
ScopedFakeTestPartResultReporter& operator=(
|
||||
const ScopedFakeTestPartResultReporter&) = delete;
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
|
|
@ -97,23 +102,27 @@ class GTEST_API_ SingleFailureChecker {
|
|||
public:
|
||||
// The constructor remembers the arguments.
|
||||
SingleFailureChecker(const TestPartResultArray* results,
|
||||
TestPartResult::Type type,
|
||||
const string& substr);
|
||||
TestPartResult::Type type, const std::string& substr);
|
||||
~SingleFailureChecker();
|
||||
|
||||
private:
|
||||
const TestPartResultArray* const results_;
|
||||
const TestPartResult::Type type_;
|
||||
const string substr_;
|
||||
const std::string substr_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
|
||||
SingleFailureChecker(const SingleFailureChecker&) = delete;
|
||||
SingleFailureChecker& operator=(const SingleFailureChecker&) = delete;
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
// A set of macros for testing Google Test assertions or code that's expected
|
||||
// to generate Google Test fatal failures. It verifies that the given
|
||||
// to generate Google Test fatal failures (e.g. a failure from an ASSERT_EQ, but
|
||||
// not a non-fatal failure, as from EXPECT_EQ). It verifies that the given
|
||||
// statement will cause exactly one fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
//
|
||||
|
|
@ -135,44 +144,46 @@ class GTEST_API_ SingleFailureChecker {
|
|||
// helper macro, due to some peculiarity in how the preprocessor
|
||||
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
|
||||
// gtest_unittest.cc will fail to compile if we do that.
|
||||
#define EXPECT_FATAL_FAILURE(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
#define EXPECT_FATAL_FAILURE(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper { \
|
||||
public: \
|
||||
static void Execute() { statement; } \
|
||||
}; \
|
||||
::testing::TestPartResultArray gtest_failures; \
|
||||
::testing::internal::SingleFailureChecker gtest_checker( \
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \
|
||||
{ \
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, \
|
||||
>est_failures); \
|
||||
GTestExpectFatalFailureHelper::Execute(); \
|
||||
} \
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper {\
|
||||
public:\
|
||||
static void Execute() { statement; }\
|
||||
};\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ALL_THREADS, >est_failures);\
|
||||
GTestExpectFatalFailureHelper::Execute();\
|
||||
}\
|
||||
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do { \
|
||||
class GTestExpectFatalFailureHelper { \
|
||||
public: \
|
||||
static void Execute() { statement; } \
|
||||
}; \
|
||||
::testing::TestPartResultArray gtest_failures; \
|
||||
::testing::internal::SingleFailureChecker gtest_checker( \
|
||||
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \
|
||||
{ \
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
|
||||
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
|
||||
>est_failures); \
|
||||
GTestExpectFatalFailureHelper::Execute(); \
|
||||
} \
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
// A macro for testing Google Test assertions or code that's expected to
|
||||
// generate Google Test non-fatal failures. It asserts that the given
|
||||
// statement will cause exactly one non-fatal Google Test failure with 'substr'
|
||||
// being part of the failure message.
|
||||
// generate Google Test non-fatal failures (e.g. a failure from an EXPECT_EQ,
|
||||
// but not from an ASSERT_EQ). It asserts that the given statement will cause
|
||||
// exactly one non-fatal Google Test failure with 'substr' being part of the
|
||||
// failure message.
|
||||
//
|
||||
// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
|
||||
// affects and considers failures generated in the current thread and
|
||||
|
|
@ -201,32 +212,37 @@ class GTEST_API_ SingleFailureChecker {
|
|||
// instead of
|
||||
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
|
||||
// to avoid an MSVC warning on unreachable code.
|
||||
#define EXPECT_NONFATAL_FAILURE(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
#define EXPECT_NONFATAL_FAILURE(statement, substr) \
|
||||
do { \
|
||||
::testing::TestPartResultArray gtest_failures; \
|
||||
::testing::internal::SingleFailureChecker gtest_checker( \
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
(substr)); \
|
||||
{ \
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
|
||||
::testing::ScopedFakeTestPartResultReporter:: \
|
||||
INTERCEPT_ONLY_CURRENT_THREAD, \
|
||||
>est_failures); \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
statement; \
|
||||
} \
|
||||
} \
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do {\
|
||||
::testing::TestPartResultArray gtest_failures;\
|
||||
::testing::internal::SingleFailureChecker gtest_checker(\
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr));\
|
||||
{\
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
|
||||
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
|
||||
do { \
|
||||
::testing::TestPartResultArray gtest_failures; \
|
||||
::testing::internal::SingleFailureChecker gtest_checker( \
|
||||
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
|
||||
(substr)); \
|
||||
{ \
|
||||
::testing::ScopedFakeTestPartResultReporter gtest_reporter( \
|
||||
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
|
||||
>est_failures);\
|
||||
if (::testing::internal::AlwaysTrue()) { statement; }\
|
||||
}\
|
||||
>est_failures); \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
statement; \
|
||||
} \
|
||||
} \
|
||||
} while (::testing::internal::AlwaysFalse())
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_
|
||||
|
|
|
|||
|
|
@ -26,18 +26,23 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: mheule@google.com (Markus Heule)
|
||||
//
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
|
||||
#include <iosfwd>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-string.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
namespace testing {
|
||||
|
||||
// A copyable object representing the result of a test part (i.e. an
|
||||
|
|
@ -51,22 +56,20 @@ class GTEST_API_ TestPartResult {
|
|||
enum Type {
|
||||
kSuccess, // Succeeded.
|
||||
kNonFatalFailure, // Failed but the test can continue.
|
||||
kFatalFailure // Failed and the test should be terminated.
|
||||
kFatalFailure, // Failed and the test should be terminated.
|
||||
kSkip // Skipped.
|
||||
};
|
||||
|
||||
// C'tor. TestPartResult does NOT have a default constructor.
|
||||
// Always use this constructor (with parameters) to create a
|
||||
// TestPartResult object.
|
||||
TestPartResult(Type a_type,
|
||||
const char* a_file_name,
|
||||
int a_line_number,
|
||||
TestPartResult(Type a_type, const char* a_file_name, int a_line_number,
|
||||
const char* a_message)
|
||||
: type_(a_type),
|
||||
file_name_(a_file_name == NULL ? "" : a_file_name),
|
||||
file_name_(a_file_name == nullptr ? "" : a_file_name),
|
||||
line_number_(a_line_number),
|
||||
summary_(ExtractSummary(a_message)),
|
||||
message_(a_message) {
|
||||
}
|
||||
message_(a_message) {}
|
||||
|
||||
// Gets the outcome of the test part.
|
||||
Type type() const { return type_; }
|
||||
|
|
@ -74,7 +77,7 @@ class GTEST_API_ TestPartResult {
|
|||
// Gets the name of the source file where the test part took place, or
|
||||
// NULL if it's unknown.
|
||||
const char* file_name() const {
|
||||
return file_name_.empty() ? NULL : file_name_.c_str();
|
||||
return file_name_.empty() ? nullptr : file_name_.c_str();
|
||||
}
|
||||
|
||||
// Gets the line in the source file where the test part took place,
|
||||
|
|
@ -87,18 +90,21 @@ class GTEST_API_ TestPartResult {
|
|||
// Gets the message associated with the test part.
|
||||
const char* message() const { return message_.c_str(); }
|
||||
|
||||
// Returns true iff the test part passed.
|
||||
// Returns true if and only if the test part was skipped.
|
||||
bool skipped() const { return type_ == kSkip; }
|
||||
|
||||
// Returns true if and only if the test part passed.
|
||||
bool passed() const { return type_ == kSuccess; }
|
||||
|
||||
// Returns true iff the test part failed.
|
||||
bool failed() const { return type_ != kSuccess; }
|
||||
|
||||
// Returns true iff the test part non-fatally failed.
|
||||
// Returns true if and only if the test part non-fatally failed.
|
||||
bool nonfatally_failed() const { return type_ == kNonFatalFailure; }
|
||||
|
||||
// Returns true iff the test part fatally failed.
|
||||
// Returns true if and only if the test part fatally failed.
|
||||
bool fatally_failed() const { return type_ == kFatalFailure; }
|
||||
|
||||
// Returns true if and only if the test part failed.
|
||||
bool failed() const { return fatally_failed() || nonfatally_failed(); }
|
||||
|
||||
private:
|
||||
Type type_;
|
||||
|
||||
|
|
@ -139,11 +145,12 @@ class GTEST_API_ TestPartResultArray {
|
|||
private:
|
||||
std::vector<TestPartResult> array_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray);
|
||||
TestPartResultArray(const TestPartResultArray&) = delete;
|
||||
TestPartResultArray& operator=(const TestPartResultArray&) = delete;
|
||||
};
|
||||
|
||||
// This interface knows how to report a test part result.
|
||||
class TestPartResultReporterInterface {
|
||||
class GTEST_API_ TestPartResultReporterInterface {
|
||||
public:
|
||||
virtual ~TestPartResultReporterInterface() {}
|
||||
|
||||
|
|
@ -162,18 +169,22 @@ class GTEST_API_ HasNewFatalFailureHelper
|
|||
: public TestPartResultReporterInterface {
|
||||
public:
|
||||
HasNewFatalFailureHelper();
|
||||
virtual ~HasNewFatalFailureHelper();
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
~HasNewFatalFailureHelper() override;
|
||||
void ReportTestPartResult(const TestPartResult& result) override;
|
||||
bool has_new_fatal_failure() const { return has_new_fatal_failure_; }
|
||||
|
||||
private:
|
||||
bool has_new_fatal_failure_;
|
||||
TestPartResultReporterInterface* original_reporter_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper);
|
||||
HasNewFatalFailureHelper(const HasNewFatalFailureHelper&) = delete;
|
||||
HasNewFatalFailureHelper& operator=(const HasNewFatalFailureHelper&) = delete;
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
|
||||
|
|
|
|||
|
|
@ -26,11 +26,13 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
|
||||
// This header implements typed tests and type-parameterized tests.
|
||||
|
||||
|
|
@ -51,22 +53,22 @@ class FooTest : public testing::Test {
|
|||
T value_;
|
||||
};
|
||||
|
||||
// Next, associate a list of types with the test case, which will be
|
||||
// Next, associate a list of types with the test suite, which will be
|
||||
// repeated for each type in the list. The typedef is necessary for
|
||||
// the macro to parse correctly.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
TYPED_TEST_CASE(FooTest, MyTypes);
|
||||
TYPED_TEST_SUITE(FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// TYPED_TEST_CASE(FooTest, int);
|
||||
// TYPED_TEST_SUITE(FooTest, int);
|
||||
|
||||
// Then, use TYPED_TEST() instead of TEST_F() to define as many typed
|
||||
// tests for this test case as you want.
|
||||
// tests for this test suite as you want.
|
||||
TYPED_TEST(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to TypeParam to get the type parameter.
|
||||
// Since we are inside a derived class template, C++ requires use to
|
||||
// visit the members of FooTest via 'this'.
|
||||
// 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 FooTest via 'this'.
|
||||
TypeParam n = this->value_;
|
||||
|
||||
// To visit static members of the fixture, add the TestFixture::
|
||||
|
|
@ -82,6 +84,24 @@ TYPED_TEST(FooTest, DoesBlah) {
|
|||
|
||||
TYPED_TEST(FooTest, HasPropertyA) { ... }
|
||||
|
||||
// TYPED_TEST_SUITE takes an optional third argument which allows to specify a
|
||||
// class that generates custom test name suffixes based on the type. This should
|
||||
// be a class which has a static template function GetName(int index) returning
|
||||
// a string for each type. The provided integer index equals the index of the
|
||||
// type in the provided type list. In many cases the index can be ignored.
|
||||
//
|
||||
// For example:
|
||||
// class MyTypeNames {
|
||||
// public:
|
||||
// template <typename T>
|
||||
// static std::string GetName(int) {
|
||||
// if (std::is_same<T, char>()) return "char";
|
||||
// if (std::is_same<T, int>()) return "int";
|
||||
// if (std::is_same<T, unsigned int>()) return "unsignedInt";
|
||||
// }
|
||||
// };
|
||||
// TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);
|
||||
|
||||
#endif // 0
|
||||
|
||||
// Type-parameterized tests are abstract test patterns parameterized
|
||||
|
|
@ -107,13 +127,13 @@ class FooTest : public testing::Test {
|
|||
...
|
||||
};
|
||||
|
||||
// Next, declare that you will define a type-parameterized test case
|
||||
// Next, declare that you will define a type-parameterized test suite
|
||||
// (the _P suffix is for "parameterized" or "pattern", whichever you
|
||||
// prefer):
|
||||
TYPED_TEST_CASE_P(FooTest);
|
||||
TYPED_TEST_SUITE_P(FooTest);
|
||||
|
||||
// Then, use TYPED_TEST_P() to define as many type-parameterized tests
|
||||
// for this type-parameterized test case as you want.
|
||||
// for this type-parameterized test suite as you want.
|
||||
TYPED_TEST_P(FooTest, DoesBlah) {
|
||||
// Inside a test, refer to TypeParam to get the type parameter.
|
||||
TypeParam n = 0;
|
||||
|
|
@ -124,10 +144,10 @@ TYPED_TEST_P(FooTest, HasPropertyA) { ... }
|
|||
|
||||
// Now the tricky part: you need to register all test patterns before
|
||||
// you can instantiate them. The first argument of the macro is the
|
||||
// test case name; the rest are the names of the tests in this test
|
||||
// test suite name; the rest are the names of the tests in this test
|
||||
// case.
|
||||
REGISTER_TYPED_TEST_CASE_P(FooTest,
|
||||
DoesBlah, HasPropertyA);
|
||||
REGISTER_TYPED_TEST_SUITE_P(FooTest,
|
||||
DoesBlah, HasPropertyA);
|
||||
|
||||
// Finally, you are free to instantiate the pattern with the types you
|
||||
// want. If you put the above code in a header file, you can #include
|
||||
|
|
@ -135,129 +155,177 @@ REGISTER_TYPED_TEST_CASE_P(FooTest,
|
|||
//
|
||||
// To distinguish different instances of the pattern, the first
|
||||
// argument to the INSTANTIATE_* macro is a prefix that will be added
|
||||
// to the actual test case name. Remember to pick unique prefixes for
|
||||
// to the actual test suite name. Remember to pick unique prefixes for
|
||||
// different instances.
|
||||
typedef testing::Types<char, int, unsigned int> MyTypes;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes);
|
||||
INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);
|
||||
|
||||
// If the type list contains only one type, you can write that type
|
||||
// directly without Types<...>:
|
||||
// INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int);
|
||||
// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);
|
||||
//
|
||||
// Similar to the optional argument of TYPED_TEST_SUITE above,
|
||||
// INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to
|
||||
// generate custom names.
|
||||
// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);
|
||||
|
||||
#endif // 0
|
||||
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "gtest/internal/gtest-type-util.h"
|
||||
|
||||
// Implements typed tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the typedef for the type parameters of the
|
||||
// given test case.
|
||||
# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_
|
||||
// given test suite.
|
||||
#define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_
|
||||
|
||||
// The 'Types' template argument below must have spaces around it
|
||||
// since some compilers may choke on '>>' when passing a template
|
||||
// instance (e.g. Types<int>)
|
||||
# define TYPED_TEST_CASE(CaseName, Types) \
|
||||
typedef ::testing::internal::TypeList< Types >::type \
|
||||
GTEST_TYPE_PARAMS_(CaseName)
|
||||
// Expands to the name of the typedef for the NameGenerator, responsible for
|
||||
// creating the suffixes of the name.
|
||||
#define GTEST_NAME_GENERATOR_(TestSuiteName) \
|
||||
gtest_type_params_##TestSuiteName##_NameGenerator
|
||||
|
||||
# define TYPED_TEST(CaseName, TestName) \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
|
||||
: public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
::testing::internal::TypeParameterizedTest< \
|
||||
CaseName, \
|
||||
::testing::internal::TemplateSel< \
|
||||
GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \
|
||||
GTEST_TYPE_PARAMS_(CaseName)>::Register(\
|
||||
"", ::testing::internal::CodeLocation(__FILE__, __LINE__), \
|
||||
#CaseName, #TestName, 0); \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_TEST_CLASS_NAME_(CaseName, TestName)<gtest_TypeParam_>::TestBody()
|
||||
#define TYPED_TEST_SUITE(CaseName, Types, ...) \
|
||||
typedef ::testing::internal::GenerateTypeList<Types>::type \
|
||||
GTEST_TYPE_PARAMS_(CaseName); \
|
||||
typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \
|
||||
GTEST_NAME_GENERATOR_(CaseName)
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
#define TYPED_TEST(CaseName, TestName) \
|
||||
static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \
|
||||
"test-name must not be empty"); \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \
|
||||
: public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
void TestBody() override; \
|
||||
}; \
|
||||
static bool gtest_##CaseName##_##TestName##_registered_ \
|
||||
GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \
|
||||
CaseName, \
|
||||
::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \
|
||||
TestName)>, \
|
||||
GTEST_TYPE_PARAMS_( \
|
||||
CaseName)>::Register("", \
|
||||
::testing::internal::CodeLocation( \
|
||||
__FILE__, __LINE__), \
|
||||
GTEST_STRINGIFY_(CaseName), \
|
||||
GTEST_STRINGIFY_(TestName), 0, \
|
||||
::testing::internal::GenerateNames< \
|
||||
GTEST_NAME_GENERATOR_(CaseName), \
|
||||
GTEST_TYPE_PARAMS_(CaseName)>()); \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_TEST_CLASS_NAME_(CaseName, \
|
||||
TestName)<gtest_TypeParam_>::TestBody()
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define TYPED_TEST_CASE \
|
||||
static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \
|
||||
TYPED_TEST_SUITE
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
// Implements type-parameterized tests.
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the namespace name that the type-parameterized tests for
|
||||
// the given type-parameterized test case are defined in. The exact
|
||||
// the given type-parameterized test suite are defined in. The exact
|
||||
// name of the namespace is subject to change without notice.
|
||||
# define GTEST_CASE_NAMESPACE_(TestCaseName) \
|
||||
gtest_case_##TestCaseName##_
|
||||
#define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the defined tests in the given test case.
|
||||
# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \
|
||||
gtest_typed_test_case_p_state_##TestCaseName##_
|
||||
// the defined tests in the given test suite.
|
||||
#define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \
|
||||
gtest_typed_test_suite_p_state_##TestSuiteName##_
|
||||
|
||||
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.
|
||||
//
|
||||
// Expands to the name of the variable used to remember the names of
|
||||
// the registered tests in the given test case.
|
||||
# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \
|
||||
gtest_registered_test_names_##TestCaseName##_
|
||||
// the registered tests in the given test suite.
|
||||
#define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \
|
||||
gtest_registered_test_names_##TestSuiteName##_
|
||||
|
||||
// The variables defined in the type-parameterized test macros are
|
||||
// static as typically these macros are used in a .h file that can be
|
||||
// #included in multiple translation units linked together.
|
||||
# define TYPED_TEST_CASE_P(CaseName) \
|
||||
static ::testing::internal::TypedTestCasePState \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName)
|
||||
#define TYPED_TEST_SUITE_P(SuiteName) \
|
||||
static ::testing::internal::TypedTestSuitePState \
|
||||
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)
|
||||
|
||||
# define TYPED_TEST_P(CaseName, TestName) \
|
||||
namespace GTEST_CASE_NAMESPACE_(CaseName) { \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class TestName : public CaseName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef CaseName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
virtual void TestBody(); \
|
||||
}; \
|
||||
static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\
|
||||
__FILE__, __LINE__, #CaseName, #TestName); \
|
||||
} \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody()
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define TYPED_TEST_CASE_P \
|
||||
static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \
|
||||
TYPED_TEST_SUITE_P
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \
|
||||
namespace GTEST_CASE_NAMESPACE_(CaseName) { \
|
||||
typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \
|
||||
} \
|
||||
static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \
|
||||
GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\
|
||||
__FILE__, __LINE__, #__VA_ARGS__)
|
||||
#define TYPED_TEST_P(SuiteName, TestName) \
|
||||
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
|
||||
template <typename gtest_TypeParam_> \
|
||||
class TestName : public SuiteName<gtest_TypeParam_> { \
|
||||
private: \
|
||||
typedef SuiteName<gtest_TypeParam_> TestFixture; \
|
||||
typedef gtest_TypeParam_ TypeParam; \
|
||||
void TestBody() override; \
|
||||
}; \
|
||||
static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \
|
||||
__FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \
|
||||
GTEST_STRINGIFY_(TestName)); \
|
||||
} \
|
||||
template <typename gtest_TypeParam_> \
|
||||
void GTEST_SUITE_NAMESPACE_( \
|
||||
SuiteName)::TestName<gtest_TypeParam_>::TestBody()
|
||||
|
||||
// The 'Types' template argument below must have spaces around it
|
||||
// since some compilers may choke on '>>' when passing a template
|
||||
// instance (e.g. Types<int>)
|
||||
# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \
|
||||
bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
::testing::internal::TypeParameterizedTestCase<CaseName, \
|
||||
GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \
|
||||
::testing::internal::TypeList< Types >::type>::Register(\
|
||||
#Prefix, \
|
||||
::testing::internal::CodeLocation(__FILE__, __LINE__), \
|
||||
>EST_TYPED_TEST_CASE_P_STATE_(CaseName), \
|
||||
#CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName))
|
||||
// Note: this won't work correctly if the trailing arguments are macros.
|
||||
#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \
|
||||
namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \
|
||||
typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \
|
||||
} \
|
||||
static const char* const GTEST_REGISTERED_TEST_NAMES_( \
|
||||
SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \
|
||||
GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define REGISTER_TYPED_TEST_CASE_P \
|
||||
static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \
|
||||
""); \
|
||||
REGISTER_TYPED_TEST_SUITE_P
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \
|
||||
static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \
|
||||
"test-suit-prefix must not be empty"); \
|
||||
static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \
|
||||
::testing::internal::TypeParameterizedTestSuite< \
|
||||
SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \
|
||||
::testing::internal::GenerateTypeList<Types>::type>:: \
|
||||
Register(GTEST_STRINGIFY_(Prefix), \
|
||||
::testing::internal::CodeLocation(__FILE__, __LINE__), \
|
||||
>EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \
|
||||
GTEST_STRINGIFY_(SuiteName), \
|
||||
GTEST_REGISTERED_TEST_NAMES_(SuiteName), \
|
||||
::testing::internal::GenerateNames< \
|
||||
::testing::internal::NameGeneratorSelector< \
|
||||
__VA_ARGS__>::type, \
|
||||
::testing::internal::GenerateTypeList<Types>::type>())
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
#define INSTANTIATE_TYPED_TEST_CASE_P \
|
||||
static_assert( \
|
||||
::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \
|
||||
INSTANTIATE_TYPED_TEST_SUITE_P
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -26,19 +26,21 @@
|
|||
// 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 10/31/2011 by command
|
||||
// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND!
|
||||
//
|
||||
// Implements a family of generic predicate assertion macros.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
// Makes sure this header is not included before gtest.h.
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
# error Do not include gtest_pred_impl.h directly. Include gtest.h instead.
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
||||
#include "gtest/gtest-assertion-result.h"
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// This header implements a family of generic predicate assertion
|
||||
// macros:
|
||||
|
|
@ -72,90 +74,70 @@
|
|||
// 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_ \
|
||||
#define GTEST_ASSERT_(expression, on_failure) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (const ::testing::AssertionResult gtest_ar = (expression)) \
|
||||
; \
|
||||
else \
|
||||
; \
|
||||
else \
|
||||
on_failure(gtest_ar.failure_message())
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1>
|
||||
AssertionResult AssertPred1Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
Pred pred,
|
||||
const T1& v1) {
|
||||
template <typename Pred, typename T1>
|
||||
AssertionResult AssertPred1Helper(const char* pred_text, const char* e1,
|
||||
Pred pred, const T1& v1) {
|
||||
if (pred(v1)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure() << pred_text << "("
|
||||
<< e1 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1;
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, v1), \
|
||||
on_failure)
|
||||
#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \
|
||||
GTEST_ASSERT_(pred_format(#v1, v1), on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED1_(pred, v1, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \
|
||||
#v1, \
|
||||
pred, \
|
||||
v1), on_failure)
|
||||
#define GTEST_PRED1_(pred, v1, on_failure) \
|
||||
GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure)
|
||||
|
||||
// Unary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)
|
||||
#define ASSERT_PRED_FORMAT1(pred_format, v1) \
|
||||
GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)
|
||||
#define ASSERT_PRED1(pred, v1) \
|
||||
GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
#define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2>
|
||||
AssertionResult AssertPred2Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
template <typename Pred, typename T1, typename T2>
|
||||
AssertionResult AssertPred2Helper(const char* pred_text, const char* e1,
|
||||
const char* e2, Pred pred, const T1& v1,
|
||||
const T2& v2) {
|
||||
if (pred(v1, v2)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure() << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2;
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2
|
||||
<< ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \
|
||||
on_failure)
|
||||
#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED2_(pred, v1, v2, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2), on_failure)
|
||||
#define GTEST_PRED2_(pred, v1, v2, on_failure) \
|
||||
GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \
|
||||
on_failure)
|
||||
|
||||
// Binary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \
|
||||
|
|
@ -167,50 +149,34 @@ AssertionResult AssertPred2Helper(const char* pred_text,
|
|||
#define ASSERT_PRED2(pred, v1, v2) \
|
||||
GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3>
|
||||
AssertionResult AssertPred3Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3) {
|
||||
template <typename Pred, typename T1, typename T2, typename T3>
|
||||
AssertionResult AssertPred3Helper(const char* pred_text, const char* e1,
|
||||
const char* e2, const char* e3, Pred pred,
|
||||
const T1& v1, const T2& v2, const T3& v3) {
|
||||
if (pred(v1, v2, v3)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure() << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3;
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2 << ", " << e3
|
||||
<< ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
|
||||
<< e3 << " evaluates to " << ::testing::PrintToString(v3);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \
|
||||
on_failure)
|
||||
#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3), on_failure)
|
||||
#define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \
|
||||
GTEST_ASSERT_( \
|
||||
::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \
|
||||
on_failure)
|
||||
|
||||
// Ternary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \
|
||||
|
|
@ -222,57 +188,36 @@ AssertionResult AssertPred3Helper(const char* pred_text,
|
|||
#define ASSERT_PRED3(pred, v1, v2, v3) \
|
||||
GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4>
|
||||
AssertionResult AssertPred4Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4) {
|
||||
template <typename Pred, typename T1, typename T2, typename T3, typename T4>
|
||||
AssertionResult AssertPred4Helper(const char* pred_text, const char* e1,
|
||||
const char* e2, const char* e3,
|
||||
const char* e4, Pred pred, const T1& v1,
|
||||
const T2& v2, const T3& v3, const T4& v4) {
|
||||
if (pred(v1, v2, v3, v4)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure() << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ", "
|
||||
<< e4 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3
|
||||
<< "\n" << e4 << " evaluates to " << v4;
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
|
||||
<< ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
|
||||
<< e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
|
||||
<< e4 << " evaluates to " << ::testing::PrintToString(v4);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \
|
||||
on_failure)
|
||||
#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4), on_failure)
|
||||
#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \
|
||||
GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \
|
||||
v1, v2, v3, v4), \
|
||||
on_failure)
|
||||
|
||||
// 4-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \
|
||||
|
|
@ -284,64 +229,40 @@ AssertionResult AssertPred4Helper(const char* pred_text,
|
|||
#define ASSERT_PRED4(pred, v1, v2, v3, v4) \
|
||||
GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)
|
||||
|
||||
|
||||
|
||||
// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
template <typename Pred,
|
||||
typename T1,
|
||||
typename T2,
|
||||
typename T3,
|
||||
typename T4,
|
||||
template <typename Pred, typename T1, typename T2, typename T3, typename T4,
|
||||
typename T5>
|
||||
AssertionResult AssertPred5Helper(const char* pred_text,
|
||||
const char* e1,
|
||||
const char* e2,
|
||||
const char* e3,
|
||||
const char* e4,
|
||||
const char* e5,
|
||||
Pred pred,
|
||||
const T1& v1,
|
||||
const T2& v2,
|
||||
const T3& v3,
|
||||
const T4& v4,
|
||||
const T5& v5) {
|
||||
AssertionResult AssertPred5Helper(const char* pred_text, const char* e1,
|
||||
const char* e2, const char* e3,
|
||||
const char* e4, const char* e5, Pred pred,
|
||||
const T1& v1, const T2& v2, const T3& v3,
|
||||
const T4& v4, const T5& v5) {
|
||||
if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();
|
||||
|
||||
return AssertionFailure() << pred_text << "("
|
||||
<< e1 << ", "
|
||||
<< e2 << ", "
|
||||
<< e3 << ", "
|
||||
<< e4 << ", "
|
||||
<< e5 << ") evaluates to false, where"
|
||||
<< "\n" << e1 << " evaluates to " << v1
|
||||
<< "\n" << e2 << " evaluates to " << v2
|
||||
<< "\n" << e3 << " evaluates to " << v3
|
||||
<< "\n" << e4 << " evaluates to " << v4
|
||||
<< "\n" << e5 << " evaluates to " << v5;
|
||||
return AssertionFailure()
|
||||
<< pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4
|
||||
<< ", " << e5 << ") evaluates to false, where"
|
||||
<< "\n"
|
||||
<< e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n"
|
||||
<< e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n"
|
||||
<< e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n"
|
||||
<< e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n"
|
||||
<< e5 << " evaluates to " << ::testing::PrintToString(v5);
|
||||
}
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.
|
||||
// Don't use this in your code.
|
||||
#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\
|
||||
#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure) \
|
||||
GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \
|
||||
on_failure)
|
||||
|
||||
// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use
|
||||
// this in your code.
|
||||
#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\
|
||||
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \
|
||||
#v1, \
|
||||
#v2, \
|
||||
#v3, \
|
||||
#v4, \
|
||||
#v5, \
|
||||
pred, \
|
||||
v1, \
|
||||
v2, \
|
||||
v3, \
|
||||
v4, \
|
||||
v5), on_failure)
|
||||
#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \
|
||||
GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \
|
||||
pred, v1, v2, v3, v4, v5), \
|
||||
on_failure)
|
||||
|
||||
// 5-ary predicate assertion macros.
|
||||
#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \
|
||||
|
|
@ -353,6 +274,6 @@ AssertionResult AssertPred5Helper(const char* pred_text,
|
|||
#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \
|
||||
GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)
|
||||
|
||||
} // namespace testing
|
||||
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
|
|
|||
|
|
@ -26,13 +26,12 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
// Google C++ Testing Framework definitions useful in production code.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
// Google C++ Testing and Mocking Framework definitions useful in production
|
||||
// code.
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
|
||||
// When you need to test the private or protected members of a class,
|
||||
// use the FRIEND_TEST macro to declare your tests as friends of the
|
||||
|
|
@ -40,19 +39,22 @@
|
|||
//
|
||||
// class MyClass {
|
||||
// private:
|
||||
// void MyMethod();
|
||||
// FRIEND_TEST(MyClassTest, MyMethod);
|
||||
// void PrivateMethod();
|
||||
// FRIEND_TEST(MyClassTest, PrivateMethodWorks);
|
||||
// };
|
||||
//
|
||||
// class MyClassTest : public testing::Test {
|
||||
// // ...
|
||||
// };
|
||||
//
|
||||
// TEST_F(MyClassTest, MyMethod) {
|
||||
// // Can call MyClass::MyMethod() here.
|
||||
// TEST_F(MyClassTest, PrivateMethodWorks) {
|
||||
// // Can call MyClass::PrivateMethod() here.
|
||||
// }
|
||||
//
|
||||
// Note: The test class must be in the same namespace as the class being tested.
|
||||
// For example, putting MyClassTest in an anonymous namespace will not work.
|
||||
|
||||
#define FRIEND_TEST(test_case_name, test_name)\
|
||||
friend class test_case_name##_##test_name##_Test
|
||||
#define FRIEND_TEST(test_case_name, test_name) \
|
||||
friend class test_case_name##_##test_name##_Test
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_
|
||||
|
|
|
|||
|
|
@ -0,0 +1,44 @@
|
|||
# Customization Points
|
||||
|
||||
The custom directory is an injection point for custom user configurations.
|
||||
|
||||
## Header `gtest.h`
|
||||
|
||||
### The following macros can be defined:
|
||||
|
||||
* `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of
|
||||
`OsStackTraceGetterInterface`.
|
||||
* `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for `testing::TempDir()`. See
|
||||
`testing::TempDir` for semantics and signature.
|
||||
|
||||
## Header `gtest-port.h`
|
||||
|
||||
The following macros can be defined:
|
||||
|
||||
### Logging:
|
||||
|
||||
* `GTEST_LOG_(severity)`
|
||||
* `GTEST_CHECK_(condition)`
|
||||
* Functions `LogToStderr()` and `FlushInfoLog()` have to be provided too.
|
||||
|
||||
### Threading:
|
||||
|
||||
* `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided.
|
||||
* `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if `Mutex` and `ThreadLocal`
|
||||
are already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)`
|
||||
and `GTEST_DEFINE_STATIC_MUTEX_(mutex)`
|
||||
* `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)`
|
||||
* `GTEST_LOCK_EXCLUDED_(locks)`
|
||||
|
||||
### Underlying library support features
|
||||
|
||||
* `GTEST_HAS_CXXABI_H_`
|
||||
|
||||
### Exporting API symbols:
|
||||
|
||||
* `GTEST_API_` - Specifier for exported symbols.
|
||||
|
||||
## Header `gtest-printers.h`
|
||||
|
||||
* See documentation at `gtest/gtest-printers.h` for details on how to define a
|
||||
custom printer.
|
||||
|
|
@ -27,43 +27,11 @@
|
|||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// Injection point for custom user configurations.
|
||||
// The following macros can be defined:
|
||||
//
|
||||
// Flag related macros:
|
||||
// GTEST_FLAG(flag_name)
|
||||
// GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its
|
||||
// own flagfile flag parsing.
|
||||
// GTEST_DECLARE_bool_(name)
|
||||
// GTEST_DECLARE_int32_(name)
|
||||
// GTEST_DECLARE_string_(name)
|
||||
// GTEST_DEFINE_bool_(name, default_val, doc)
|
||||
// GTEST_DEFINE_int32_(name, default_val, doc)
|
||||
// GTEST_DEFINE_string_(name, default_val, doc)
|
||||
//
|
||||
// Test filtering:
|
||||
// GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that
|
||||
// will be used if --GTEST_FLAG(test_filter)
|
||||
// is not provided.
|
||||
//
|
||||
// Logging:
|
||||
// GTEST_LOG_(severity)
|
||||
// GTEST_CHECK_(condition)
|
||||
// Functions LogToStderr() and FlushInfoLog() have to be provided too.
|
||||
//
|
||||
// Threading:
|
||||
// GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided.
|
||||
// GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are
|
||||
// already provided.
|
||||
// Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and
|
||||
// GTEST_DEFINE_STATIC_MUTEX_(mutex)
|
||||
//
|
||||
// GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
|
||||
// GTEST_LOCK_EXCLUDED_(locks)
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// ** Custom implementation starts here **
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
|
||||
|
|
|
|||
|
|
@ -31,12 +31,12 @@
|
|||
// installation of gTest.
|
||||
// It will be included from gtest-printers.h and the overrides in this file
|
||||
// will be visible to everyone.
|
||||
// See documentation at gtest/gtest-printers.h for details on how to define a
|
||||
// custom printer.
|
||||
//
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// ** Custom implementation starts here **
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
|
||||
|
|
|
|||
|
|
@ -27,15 +27,11 @@
|
|||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// Injection point for custom user configurations.
|
||||
// The following macros can be defined:
|
||||
//
|
||||
// GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of
|
||||
// OsStackTraceGetterInterface.
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// ** Custom implementation starts here **
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
|
||||
|
|
|
|||
|
|
@ -26,26 +26,31 @@
|
|||
// 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.
|
||||
//
|
||||
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines internal utilities needed for implementing
|
||||
// death tests. They are subject to change without notice.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
#include <memory>
|
||||
|
||||
#include "gtest/gtest-matchers.h"
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
|
||||
GTEST_DECLARE_string_(internal_run_death_test);
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// Names of the flags (needed for parsing Google Test flags).
|
||||
const char kDeathTestStyleFlag[] = "death_test_style";
|
||||
const char kDeathTestUseFork[] = "death_test_use_fork";
|
||||
|
|
@ -53,6 +58,9 @@ const char kInternalRunDeathTestFlag[] = "internal_run_death_test";
|
|||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
// DeathTest is a class that hides much of the complexity of the
|
||||
// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method
|
||||
// returns a concrete class that depends on the prevailing death test
|
||||
|
|
@ -76,19 +84,21 @@ class GTEST_API_ DeathTest {
|
|||
// argument is set. If the death test should be skipped, the pointer
|
||||
// is set to NULL; otherwise, it is set to the address of a new concrete
|
||||
// DeathTest object that controls the execution of the current test.
|
||||
static bool Create(const char* statement, const RE* regex,
|
||||
static bool Create(const char* statement, Matcher<const std::string&> matcher,
|
||||
const char* file, int line, DeathTest** test);
|
||||
DeathTest();
|
||||
virtual ~DeathTest() { }
|
||||
virtual ~DeathTest() {}
|
||||
|
||||
// A helper class that aborts a death test when it's deleted.
|
||||
class ReturnSentinel {
|
||||
public:
|
||||
explicit ReturnSentinel(DeathTest* test) : test_(test) { }
|
||||
explicit ReturnSentinel(DeathTest* test) : test_(test) {}
|
||||
~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }
|
||||
|
||||
private:
|
||||
DeathTest* const test_;
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel);
|
||||
ReturnSentinel(const ReturnSentinel&) = delete;
|
||||
ReturnSentinel& operator=(const ReturnSentinel&) = delete;
|
||||
} GTEST_ATTRIBUTE_UNUSED_;
|
||||
|
||||
// An enumeration of possible roles that may be taken when a death
|
||||
|
|
@ -133,99 +143,126 @@ class GTEST_API_ DeathTest {
|
|||
// A string containing a description of the outcome of the last death test.
|
||||
static std::string last_death_test_message_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest);
|
||||
DeathTest(const DeathTest&) = delete;
|
||||
DeathTest& operator=(const DeathTest&) = delete;
|
||||
};
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
// Factory interface for death tests. May be mocked out for testing.
|
||||
class DeathTestFactory {
|
||||
public:
|
||||
virtual ~DeathTestFactory() { }
|
||||
virtual bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test) = 0;
|
||||
virtual ~DeathTestFactory() {}
|
||||
virtual bool Create(const char* statement,
|
||||
Matcher<const std::string&> matcher, const char* file,
|
||||
int line, DeathTest** test) = 0;
|
||||
};
|
||||
|
||||
// A concrete DeathTestFactory implementation for normal use.
|
||||
class DefaultDeathTestFactory : public DeathTestFactory {
|
||||
public:
|
||||
virtual bool Create(const char* statement, const RE* regex,
|
||||
const char* file, int line, DeathTest** test);
|
||||
bool Create(const char* statement, Matcher<const std::string&> matcher,
|
||||
const char* file, int line, DeathTest** test) override;
|
||||
};
|
||||
|
||||
// Returns true if exit_status describes a process that was terminated
|
||||
// by a signal, or exited normally with a nonzero exit code.
|
||||
GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
|
||||
|
||||
// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads
|
||||
// and interpreted as a regex (rather than an Eq matcher) for legacy
|
||||
// compatibility.
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
|
||||
::testing::internal::RE regex) {
|
||||
return ContainsRegex(regex.pattern());
|
||||
}
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {
|
||||
return ContainsRegex(regex);
|
||||
}
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
|
||||
const ::std::string& regex) {
|
||||
return ContainsRegex(regex);
|
||||
}
|
||||
|
||||
// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's
|
||||
// used directly.
|
||||
inline Matcher<const ::std::string&> MakeDeathTestMatcher(
|
||||
Matcher<const ::std::string&> matcher) {
|
||||
return matcher;
|
||||
}
|
||||
|
||||
// Traps C++ exceptions escaping statement and reports them as test
|
||||
// failures. Note that trapping SEH exceptions is not implemented here.
|
||||
# if GTEST_HAS_EXCEPTIONS
|
||||
# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
|
||||
try { \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
} catch (const ::std::exception& gtest_exception) { \
|
||||
fprintf(\
|
||||
stderr, \
|
||||
"\n%s: Caught std::exception-derived exception escaping the " \
|
||||
"death test statement. Exception message: %s\n", \
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
|
||||
try { \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
} catch (const ::std::exception& gtest_exception) { \
|
||||
fprintf( \
|
||||
stderr, \
|
||||
"\n%s: Caught std::exception-derived exception escaping the " \
|
||||
"death test statement. Exception message: %s\n", \
|
||||
::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \
|
||||
gtest_exception.what()); \
|
||||
fflush(stderr); \
|
||||
gtest_exception.what()); \
|
||||
fflush(stderr); \
|
||||
death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
|
||||
} catch (...) { \
|
||||
} catch (...) { \
|
||||
death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \
|
||||
}
|
||||
|
||||
# else
|
||||
# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
|
||||
#else
|
||||
#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
|
||||
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,
|
||||
// ASSERT_EXIT*, and EXPECT_EXIT*.
|
||||
# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
const ::testing::internal::RE& gtest_regex = (regex); \
|
||||
::testing::internal::DeathTest* gtest_dt; \
|
||||
if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \
|
||||
__FILE__, __LINE__, >est_dt)) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
if (gtest_dt != NULL) { \
|
||||
::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
|
||||
gtest_dt_ptr(gtest_dt); \
|
||||
switch (gtest_dt->AssumeRole()) { \
|
||||
case ::testing::internal::DeathTest::OVERSEE_TEST: \
|
||||
if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
break; \
|
||||
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
|
||||
::testing::internal::DeathTest::ReturnSentinel \
|
||||
gtest_sentinel(gtest_dt); \
|
||||
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
|
||||
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
|
||||
break; \
|
||||
} \
|
||||
default: \
|
||||
break; \
|
||||
} \
|
||||
} \
|
||||
} else \
|
||||
GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \
|
||||
fail(::testing::internal::DeathTest::LastMessage())
|
||||
#define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
::testing::internal::DeathTest* gtest_dt; \
|
||||
if (!::testing::internal::DeathTest::Create( \
|
||||
#statement, \
|
||||
::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \
|
||||
__FILE__, __LINE__, >est_dt)) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
if (gtest_dt != nullptr) { \
|
||||
std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \
|
||||
switch (gtest_dt->AssumeRole()) { \
|
||||
case ::testing::internal::DeathTest::OVERSEE_TEST: \
|
||||
if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \
|
||||
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
|
||||
} \
|
||||
break; \
|
||||
case ::testing::internal::DeathTest::EXECUTE_TEST: { \
|
||||
::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
|
||||
gtest_dt); \
|
||||
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
|
||||
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
|
||||
break; \
|
||||
} \
|
||||
} \
|
||||
} \
|
||||
} else \
|
||||
GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
|
||||
: fail(::testing::internal::DeathTest::LastMessage())
|
||||
// The symbol "fail" here expands to something into which a message
|
||||
// can be streamed.
|
||||
|
||||
// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in
|
||||
// NDEBUG mode. In this case we need the statements to be executed, the regex is
|
||||
// ignored, and the macro must accept a streamed message even though the message
|
||||
// is never printed.
|
||||
# define GTEST_EXECUTE_STATEMENT_(statement, regex) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
} else \
|
||||
// NDEBUG mode. In this case we need the statements to be executed and the macro
|
||||
// must accept a streamed message even though the message is never printed.
|
||||
// The regex object is not evaluated, but it is used to prevent "unused"
|
||||
// warnings and to avoid an expression that doesn't compile in debug mode.
|
||||
#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
} else if (!::testing::internal::AlwaysTrue()) { \
|
||||
::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \
|
||||
} else \
|
||||
::testing::Message()
|
||||
|
||||
// A class representing the parsed contents of the
|
||||
|
|
@ -233,16 +270,12 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
|
|||
// RUN_ALL_TESTS was called.
|
||||
class InternalRunDeathTestFlag {
|
||||
public:
|
||||
InternalRunDeathTestFlag(const std::string& a_file,
|
||||
int a_line,
|
||||
int an_index,
|
||||
InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,
|
||||
int a_write_fd)
|
||||
: file_(a_file), line_(a_line), index_(an_index),
|
||||
write_fd_(a_write_fd) {}
|
||||
: file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {}
|
||||
|
||||
~InternalRunDeathTestFlag() {
|
||||
if (write_fd_ >= 0)
|
||||
posix::Close(write_fd_);
|
||||
if (write_fd_ >= 0) posix::Close(write_fd_);
|
||||
}
|
||||
|
||||
const std::string& file() const { return file_; }
|
||||
|
|
@ -256,7 +289,8 @@ class InternalRunDeathTestFlag {
|
|||
int index_;
|
||||
int write_fd_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag);
|
||||
InternalRunDeathTestFlag(const InternalRunDeathTestFlag&) = delete;
|
||||
InternalRunDeathTestFlag& operator=(const InternalRunDeathTestFlag&) = delete;
|
||||
};
|
||||
|
||||
// Returns a newly created InternalRunDeathTestFlag object with fields
|
||||
|
|
@ -264,56 +298,9 @@ class InternalRunDeathTestFlag {
|
|||
// the flag is specified; otherwise returns NULL.
|
||||
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();
|
||||
|
||||
#else // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// This macro is used for implementing macros such as
|
||||
// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where
|
||||
// death tests are not supported. Those macros must compile on such systems
|
||||
// iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on
|
||||
// systems that support death tests. This allows one to write such a macro
|
||||
// on a system that does not support death tests and be sure that it will
|
||||
// compile on a death-test supporting system.
|
||||
//
|
||||
// Parameters:
|
||||
// statement - A statement that a macro such as EXPECT_DEATH would test
|
||||
// for program termination. This macro has to make sure this
|
||||
// statement is compiled but not executed, to ensure that
|
||||
// EXPECT_DEATH_IF_SUPPORTED compiles with a certain
|
||||
// parameter iff EXPECT_DEATH compiles with it.
|
||||
// regex - A regex that a macro such as EXPECT_DEATH would use to test
|
||||
// the output of statement. This parameter has to be
|
||||
// compiled but not evaluated by this macro, to ensure that
|
||||
// this macro only accepts expressions that a macro such as
|
||||
// EXPECT_DEATH would accept.
|
||||
// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED
|
||||
// and a return statement for ASSERT_DEATH_IF_SUPPORTED.
|
||||
// This ensures that ASSERT_DEATH_IF_SUPPORTED will not
|
||||
// compile inside functions where ASSERT_DEATH doesn't
|
||||
// compile.
|
||||
//
|
||||
// The branch that has an always false condition is used to ensure that
|
||||
// statement and regex are compiled (and thus syntactically correct) but
|
||||
// never executed. The unreachable code macro protects the terminator
|
||||
// statement from generating an 'unreachable code' warning in case
|
||||
// statement unconditionally returns or throws. The Message constructor at
|
||||
// the end allows the syntax of streaming additional messages into the
|
||||
// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.
|
||||
# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \
|
||||
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
|
||||
if (::testing::internal::AlwaysTrue()) { \
|
||||
GTEST_LOG_(WARNING) \
|
||||
<< "Death tests are not supported on this platform.\n" \
|
||||
<< "Statement '" #statement "' cannot be verified."; \
|
||||
} else if (::testing::internal::AlwaysFalse()) { \
|
||||
::testing::internal::RE::PartialMatch(".*", (regex)); \
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \
|
||||
terminator; \
|
||||
} else \
|
||||
::testing::Message()
|
||||
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
|
||||
|
|
|
|||
|
|
@ -26,22 +26,27 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: keith.ray@gmail.com (Keith Ray)
|
||||
//
|
||||
|
||||
// Google Test filepath utilities
|
||||
//
|
||||
// This header file declares classes and functions used internally by
|
||||
// Google Test. They are subject to change without notice.
|
||||
//
|
||||
// This file is #included in <gtest/internal/gtest-internal.h>.
|
||||
// This file is #included in gtest/internal/gtest-internal.h.
|
||||
// Do not include this header file separately!
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
|
||||
#include "gtest/internal/gtest-string.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
|
|
@ -58,8 +63,8 @@ namespace internal {
|
|||
|
||||
class GTEST_API_ FilePath {
|
||||
public:
|
||||
FilePath() : pathname_("") { }
|
||||
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { }
|
||||
FilePath() : pathname_("") {}
|
||||
FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {}
|
||||
|
||||
explicit FilePath(const std::string& pathname) : pathname_(pathname) {
|
||||
Normalize();
|
||||
|
|
@ -70,9 +75,7 @@ class GTEST_API_ FilePath {
|
|||
return *this;
|
||||
}
|
||||
|
||||
void Set(const FilePath& rhs) {
|
||||
pathname_ = rhs.pathname_;
|
||||
}
|
||||
void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; }
|
||||
|
||||
const std::string& string() const { return pathname_; }
|
||||
const char* c_str() const { return pathname_.c_str(); }
|
||||
|
|
@ -85,8 +88,7 @@ class GTEST_API_ FilePath {
|
|||
// than zero (e.g., 12), returns "dir/test_12.xml".
|
||||
// On Windows platform, uses \ as the separator rather than /.
|
||||
static FilePath MakeFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
int number,
|
||||
const FilePath& base_name, int number,
|
||||
const char* extension);
|
||||
|
||||
// Given directory = "dir", relative_path = "test.xml",
|
||||
|
|
@ -107,7 +109,7 @@ class GTEST_API_ FilePath {
|
|||
const FilePath& base_name,
|
||||
const char* extension);
|
||||
|
||||
// Returns true iff the path is "".
|
||||
// Returns true if and only if the path is "".
|
||||
bool IsEmpty() const { return pathname_.empty(); }
|
||||
|
||||
// If input name has a trailing separator character, removes it and returns
|
||||
|
|
@ -192,7 +194,7 @@ class GTEST_API_ FilePath {
|
|||
|
||||
void Normalize();
|
||||
|
||||
// Returns a pointer to the last occurence of a valid path separator in
|
||||
// Returns a pointer to the last occurrence of a valid path separator in
|
||||
// the FilePath. On Windows, for example, both '/' and '\' are valid path
|
||||
// separators. Returns NULL if no path separator was found.
|
||||
const char* FindLastPathSeparator() const;
|
||||
|
|
@ -203,4 +205,6 @@ class GTEST_API_ FilePath {
|
|||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -26,68 +26,91 @@
|
|||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file defines the GTEST_OS_* macro.
|
||||
// It is separate from gtest-port.h so that custom/gtest-port.h can include it.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
|
||||
// Determines the platform on which Google Test is compiled.
|
||||
#ifdef __CYGWIN__
|
||||
# define GTEST_OS_CYGWIN 1
|
||||
#elif defined __SYMBIAN32__
|
||||
# define GTEST_OS_SYMBIAN 1
|
||||
#define GTEST_OS_CYGWIN 1
|
||||
#elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)
|
||||
#define GTEST_OS_WINDOWS_MINGW 1
|
||||
#define GTEST_OS_WINDOWS 1
|
||||
#elif defined _WIN32
|
||||
# define GTEST_OS_WINDOWS 1
|
||||
# ifdef _WIN32_WCE
|
||||
# define GTEST_OS_WINDOWS_MOBILE 1
|
||||
# elif defined(__MINGW__) || defined(__MINGW32__)
|
||||
# define GTEST_OS_WINDOWS_MINGW 1
|
||||
# elif defined(WINAPI_FAMILY)
|
||||
# include <winapifamily.h>
|
||||
# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
|
||||
# define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
|
||||
# define GTEST_OS_WINDOWS_PHONE 1
|
||||
# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
|
||||
# define GTEST_OS_WINDOWS_RT 1
|
||||
# else
|
||||
// WINAPI_FAMILY defined but no known partition matched.
|
||||
// Default to desktop.
|
||||
# define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
# endif
|
||||
# else
|
||||
# define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
# endif // _WIN32_WCE
|
||||
#define GTEST_OS_WINDOWS 1
|
||||
#ifdef _WIN32_WCE
|
||||
#define GTEST_OS_WINDOWS_MOBILE 1
|
||||
#elif defined(WINAPI_FAMILY)
|
||||
#include <winapifamily.h>
|
||||
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
|
||||
#define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
|
||||
#define GTEST_OS_WINDOWS_PHONE 1
|
||||
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
|
||||
#define GTEST_OS_WINDOWS_RT 1
|
||||
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)
|
||||
#define GTEST_OS_WINDOWS_PHONE 1
|
||||
#define GTEST_OS_WINDOWS_TV_TITLE 1
|
||||
#else
|
||||
// WINAPI_FAMILY defined but no known partition matched.
|
||||
// Default to desktop.
|
||||
#define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
#endif
|
||||
#else
|
||||
#define GTEST_OS_WINDOWS_DESKTOP 1
|
||||
#endif // _WIN32_WCE
|
||||
#elif defined __OS2__
|
||||
#define GTEST_OS_OS2 1
|
||||
#elif defined __APPLE__
|
||||
# define GTEST_OS_MAC 1
|
||||
# if TARGET_OS_IPHONE
|
||||
# define GTEST_OS_IOS 1
|
||||
# endif
|
||||
#define GTEST_OS_MAC 1
|
||||
#include <TargetConditionals.h>
|
||||
#if TARGET_OS_IPHONE
|
||||
#define GTEST_OS_IOS 1
|
||||
#endif
|
||||
#elif defined __DragonFly__
|
||||
#define GTEST_OS_DRAGONFLY 1
|
||||
#elif defined __FreeBSD__
|
||||
# define GTEST_OS_FREEBSD 1
|
||||
#define GTEST_OS_FREEBSD 1
|
||||
#elif defined __Fuchsia__
|
||||
#define GTEST_OS_FUCHSIA 1
|
||||
#elif defined(__GNU__)
|
||||
#define GTEST_OS_GNU_HURD 1
|
||||
#elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)
|
||||
#define GTEST_OS_GNU_KFREEBSD 1
|
||||
#elif defined __linux__
|
||||
# define GTEST_OS_LINUX 1
|
||||
# if defined __ANDROID__
|
||||
# define GTEST_OS_LINUX_ANDROID 1
|
||||
# endif
|
||||
#define GTEST_OS_LINUX 1
|
||||
#if defined __ANDROID__
|
||||
#define GTEST_OS_LINUX_ANDROID 1
|
||||
#endif
|
||||
#elif defined __MVS__
|
||||
# define GTEST_OS_ZOS 1
|
||||
#define GTEST_OS_ZOS 1
|
||||
#elif defined(__sun) && defined(__SVR4)
|
||||
# define GTEST_OS_SOLARIS 1
|
||||
#define GTEST_OS_SOLARIS 1
|
||||
#elif defined(_AIX)
|
||||
# define GTEST_OS_AIX 1
|
||||
#define GTEST_OS_AIX 1
|
||||
#elif defined(__hpux)
|
||||
# define GTEST_OS_HPUX 1
|
||||
#define GTEST_OS_HPUX 1
|
||||
#elif defined __native_client__
|
||||
# define GTEST_OS_NACL 1
|
||||
#define GTEST_OS_NACL 1
|
||||
#elif defined __NetBSD__
|
||||
#define GTEST_OS_NETBSD 1
|
||||
#elif defined __OpenBSD__
|
||||
# define GTEST_OS_OPENBSD 1
|
||||
#define GTEST_OS_OPENBSD 1
|
||||
#elif defined __QNX__
|
||||
# define GTEST_OS_QNX 1
|
||||
#define GTEST_OS_QNX 1
|
||||
#elif defined(__HAIKU__)
|
||||
#define GTEST_OS_HAIKU 1
|
||||
#elif defined ESP8266
|
||||
#define GTEST_OS_ESP8266 1
|
||||
#elif defined ESP32
|
||||
#define GTEST_OS_ESP32 1
|
||||
#elif defined(__XTENSA__)
|
||||
#define GTEST_OS_XTENSA 1
|
||||
#endif // __CYGWIN__
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -26,27 +26,31 @@
|
|||
// 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.
|
||||
//
|
||||
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This header file declares the String class and functions used internally by
|
||||
// Google Test. They are subject to change without notice. They should not used
|
||||
// by code external to Google Test.
|
||||
//
|
||||
// This header file is #included by <gtest/internal/gtest-internal.h>.
|
||||
// This header file is #included by gtest-internal.h.
|
||||
// It should not be #included by other files.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
// IWYU pragma: private, include "gtest/gtest.h"
|
||||
// IWYU pragma: friend gtest/.*
|
||||
// IWYU pragma: friend gmock/.*
|
||||
|
||||
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
|
||||
#ifdef __BORLANDC__
|
||||
// string.h is not guaranteed to provide strcpy on C++ Builder.
|
||||
# include <mem.h>
|
||||
#include <mem.h>
|
||||
#endif
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
|
@ -94,7 +98,8 @@ class GTEST_API_ String {
|
|||
static const char* Utf16ToAnsi(LPCWSTR utf16_str);
|
||||
#endif
|
||||
|
||||
// Compares two C strings. Returns true iff they have the same content.
|
||||
// Compares two C strings. Returns true if and only if they have the same
|
||||
// content.
|
||||
//
|
||||
// Unlike strcmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
|
|
@ -107,25 +112,24 @@ class GTEST_API_ String {
|
|||
// returned.
|
||||
static std::string ShowWideCString(const wchar_t* wide_c_str);
|
||||
|
||||
// Compares two wide C strings. Returns true iff they have the same
|
||||
// content.
|
||||
// Compares two wide C strings. Returns true if and only if they have the
|
||||
// same content.
|
||||
//
|
||||
// Unlike wcscmp(), this function can handle NULL argument(s). A
|
||||
// NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
|
||||
|
||||
// Compares two C strings, ignoring case. Returns true iff they
|
||||
// have the same content.
|
||||
// Compares two C strings, ignoring case. Returns true if and only if
|
||||
// they have the same content.
|
||||
//
|
||||
// Unlike strcasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL C string,
|
||||
// including the empty string.
|
||||
static bool CaseInsensitiveCStringEquals(const char* lhs,
|
||||
const char* rhs);
|
||||
static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs);
|
||||
|
||||
// Compares two wide C strings, ignoring case. Returns true iff they
|
||||
// have the same content.
|
||||
// Compares two wide C strings, ignoring case. Returns true if and only if
|
||||
// they have the same content.
|
||||
//
|
||||
// Unlike wcscasecmp(), this function can handle NULL argument(s).
|
||||
// A NULL C string is considered different to any non-NULL wide C string,
|
||||
|
|
@ -139,23 +143,29 @@ class GTEST_API_ String {
|
|||
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
|
||||
const wchar_t* rhs);
|
||||
|
||||
// Returns true iff the given string ends with the given suffix, ignoring
|
||||
// case. Any string is considered to end with an empty suffix.
|
||||
static bool EndsWithCaseInsensitive(
|
||||
const std::string& str, const std::string& suffix);
|
||||
// Returns true if and only if the given string ends with the given suffix,
|
||||
// ignoring case. Any string is considered to end with an empty suffix.
|
||||
static bool EndsWithCaseInsensitive(const std::string& str,
|
||||
const std::string& suffix);
|
||||
|
||||
// Formats an int value as "%02d".
|
||||
static std::string FormatIntWidth2(int value); // "%02d" for width == 2
|
||||
|
||||
// Formats an int value to given width with leading zeros.
|
||||
static std::string FormatIntWidthN(int value, int width);
|
||||
|
||||
// Formats an int value as "%X".
|
||||
static std::string FormatHexInt(int value);
|
||||
|
||||
// Formats an int value as "%X".
|
||||
static std::string FormatHexUInt32(uint32_t value);
|
||||
|
||||
// Formats a byte as "%02X".
|
||||
static std::string FormatByte(unsigned char value);
|
||||
|
||||
private:
|
||||
String(); // Not meant to be instantiated.
|
||||
}; // class String
|
||||
}; // class String
|
||||
|
||||
// Gets the content of the stringstream's buffer as an std::string. Each '\0'
|
||||
// character in the buffer is replaced with "\\0".
|
||||
|
|
@ -164,4 +174,4 @@ GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
|
|||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -26,16 +26,13 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
|
||||
// This provides interface PrimeTable that determines whether a number is a
|
||||
// prime and determines a next prime number. This interface is used
|
||||
// in Google Test samples demonstrating use of parameterized tests.
|
||||
|
||||
#ifndef GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
#define GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
#ifndef GOOGLETEST_SAMPLES_PRIME_TABLES_H_
|
||||
#define GOOGLETEST_SAMPLES_PRIME_TABLES_H_
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
|
|
@ -44,7 +41,7 @@ class PrimeTable {
|
|||
public:
|
||||
virtual ~PrimeTable() {}
|
||||
|
||||
// Returns true iff n is a prime number.
|
||||
// Returns true if and only if n is a prime number.
|
||||
virtual bool IsPrime(int n) const = 0;
|
||||
|
||||
// Returns the smallest prime number greater than p; or returns -1
|
||||
|
|
@ -55,10 +52,10 @@ class PrimeTable {
|
|||
// Implementation #1 calculates the primes on-the-fly.
|
||||
class OnTheFlyPrimeTable : public PrimeTable {
|
||||
public:
|
||||
virtual bool IsPrime(int n) const {
|
||||
bool IsPrime(int n) const override {
|
||||
if (n <= 1) return false;
|
||||
|
||||
for (int i = 2; i*i <= n; i++) {
|
||||
for (int i = 2; i * i <= n; i++) {
|
||||
// n is divisible by an integer other than 1 and itself.
|
||||
if ((n % i) == 0) return false;
|
||||
}
|
||||
|
|
@ -66,12 +63,12 @@ class OnTheFlyPrimeTable : public PrimeTable {
|
|||
return true;
|
||||
}
|
||||
|
||||
virtual int GetNextPrime(int p) const {
|
||||
for (int n = p + 1; n > 0; n++) {
|
||||
int GetNextPrime(int p) const override {
|
||||
if (p < 0) return -1;
|
||||
|
||||
for (int n = p + 1;; n++) {
|
||||
if (IsPrime(n)) return n;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -84,13 +81,13 @@ class PreCalculatedPrimeTable : public PrimeTable {
|
|||
: is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {
|
||||
CalculatePrimesUpTo(max);
|
||||
}
|
||||
virtual ~PreCalculatedPrimeTable() { delete[] is_prime_; }
|
||||
~PreCalculatedPrimeTable() override { delete[] is_prime_; }
|
||||
|
||||
virtual bool IsPrime(int n) const {
|
||||
bool IsPrime(int n) const override {
|
||||
return 0 <= n && n < is_prime_size_ && is_prime_[n];
|
||||
}
|
||||
|
||||
virtual int GetNextPrime(int p) const {
|
||||
int GetNextPrime(int p) const override {
|
||||
for (int n = p + 1; n < is_prime_size_; n++) {
|
||||
if (is_prime_[n]) return n;
|
||||
}
|
||||
|
|
@ -103,11 +100,15 @@ class PreCalculatedPrimeTable : public PrimeTable {
|
|||
::std::fill(is_prime_, is_prime_ + is_prime_size_, true);
|
||||
is_prime_[0] = is_prime_[1] = false;
|
||||
|
||||
for (int i = 2; i <= max; i++) {
|
||||
// Checks every candidate for prime number (we know that 2 is the only even
|
||||
// prime).
|
||||
for (int i = 2; i * i <= max; i += i % 2 + 1) {
|
||||
if (!is_prime_[i]) continue;
|
||||
|
||||
// Marks all multiples of i (except i itself) as non-prime.
|
||||
for (int j = 2*i; j <= max; j += i) {
|
||||
// We are starting here from i-th multiplier, because all smaller
|
||||
// complex numbers were already marked.
|
||||
for (int j = i * i; j <= max; j += i) {
|
||||
is_prime_[j] = false;
|
||||
}
|
||||
}
|
||||
|
|
@ -120,4 +121,4 @@ class PreCalculatedPrimeTable : public PrimeTable {
|
|||
void operator=(const PreCalculatedPrimeTable& rhs);
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_PRIME_TABLES_H_
|
||||
#endif // GOOGLETEST_SAMPLES_PRIME_TABLES_H_
|
||||
|
|
|
|||
|
|
@ -28,8 +28,6 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include "sample1.h"
|
||||
|
||||
|
|
@ -43,7 +41,7 @@ int Factorial(int n) {
|
|||
return result;
|
||||
}
|
||||
|
||||
// Returns true iff n is a prime number.
|
||||
// Returns true if and only if n is a prime number.
|
||||
bool IsPrime(int n) {
|
||||
// Trivial case 1: small numbers
|
||||
if (n <= 1) return false;
|
||||
|
|
@ -54,9 +52,9 @@ bool IsPrime(int n) {
|
|||
// Now, we have that n is odd and n >= 3.
|
||||
|
||||
// Try to divide n by every odd number i, starting from 3
|
||||
for (int i = 3; ; i += 2) {
|
||||
// We only have to try i up to the squre root of n
|
||||
if (i > n/i) break;
|
||||
for (int i = 3;; i += 2) {
|
||||
// We only have to try i up to the square root of n
|
||||
if (i > n / i) break;
|
||||
|
||||
// Now, we have i <= n/i < n.
|
||||
// If n is divisible by i, n is not prime.
|
||||
|
|
|
|||
|
|
@ -28,16 +28,14 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE1_H_
|
||||
#define GTEST_SAMPLES_SAMPLE1_H_
|
||||
#ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_
|
||||
#define GOOGLETEST_SAMPLES_SAMPLE1_H_
|
||||
|
||||
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
|
||||
int Factorial(int n);
|
||||
|
||||
// Returns true iff n is a prime number.
|
||||
// Returns true if and only if n is a prime number.
|
||||
bool IsPrime(int n);
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE1_H_
|
||||
#endif // GOOGLETEST_SAMPLES_SAMPLE1_H_
|
||||
|
|
|
|||
|
|
@ -25,8 +25,6 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
|
||||
// This sample shows how to use Google Test listener API to implement
|
||||
// a primitive leak checker.
|
||||
|
|
@ -35,18 +33,15 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
using ::testing::EmptyTestEventListener;
|
||||
using ::testing::InitGoogleTest;
|
||||
using ::testing::Test;
|
||||
using ::testing::TestCase;
|
||||
using ::testing::TestEventListeners;
|
||||
using ::testing::TestInfo;
|
||||
using ::testing::TestPartResult;
|
||||
using ::testing::UnitTest;
|
||||
|
||||
namespace {
|
||||
|
||||
// We will track memory used by this class.
|
||||
class Water {
|
||||
public:
|
||||
|
|
@ -78,12 +73,12 @@ int Water::allocated_ = 0;
|
|||
class LeakChecker : public EmptyTestEventListener {
|
||||
private:
|
||||
// Called before a test starts.
|
||||
virtual void OnTestStart(const TestInfo& /* test_info */) {
|
||||
void OnTestStart(const TestInfo& /* test_info */) override {
|
||||
initially_allocated_ = Water::allocated();
|
||||
}
|
||||
|
||||
// Called after a test ends.
|
||||
virtual void OnTestEnd(const TestInfo& /* test_info */) {
|
||||
void OnTestEnd(const TestInfo& /* test_info */) override {
|
||||
int difference = Water::allocated() - initially_allocated_;
|
||||
|
||||
// You can generate a failure in any event handler except
|
||||
|
|
@ -104,19 +99,19 @@ TEST(ListenersTest, DoesNotLeak) {
|
|||
// specified.
|
||||
TEST(ListenersTest, LeaksWater) {
|
||||
Water* water = new Water;
|
||||
EXPECT_TRUE(water != NULL);
|
||||
EXPECT_TRUE(water != nullptr);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int main(int argc, char** argv) {
|
||||
InitGoogleTest(&argc, argv);
|
||||
|
||||
bool check_for_leaks = false;
|
||||
if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )
|
||||
if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0)
|
||||
check_for_leaks = true;
|
||||
else
|
||||
printf("%s\n", "Run this program with --check_for_leaks to enable "
|
||||
printf("%s\n",
|
||||
"Run this program with --check_for_leaks to enable "
|
||||
"custom leak checking in the tests.");
|
||||
|
||||
// If we are given the --check_for_leaks command line flag, installs the
|
||||
|
|
|
|||
|
|
@ -28,25 +28,23 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
|
||||
// This sample shows how to write a simple unit test for a function,
|
||||
// using Google C++ testing framework.
|
||||
//
|
||||
// Writing a unit test using Google C++ testing framework is easy as 1-2-3:
|
||||
|
||||
|
||||
// Step 1. Include necessary header files such that the stuff your
|
||||
// test logic needs is declared.
|
||||
//
|
||||
// Don't forget gtest.h, which declares the testing framework.
|
||||
|
||||
#include <limits.h>
|
||||
#include "sample1.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
|
||||
// Step 2. Use the TEST macro to define your tests.
|
||||
//
|
||||
|
|
@ -72,7 +70,6 @@
|
|||
//
|
||||
// </TechnicalDetails>
|
||||
|
||||
|
||||
// Tests Factorial().
|
||||
|
||||
// Tests factorial of negative numbers.
|
||||
|
|
@ -100,9 +97,7 @@ TEST(FactorialTest, Negative) {
|
|||
}
|
||||
|
||||
// Tests factorial of 0.
|
||||
TEST(FactorialTest, Zero) {
|
||||
EXPECT_EQ(1, Factorial(0));
|
||||
}
|
||||
TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); }
|
||||
|
||||
// Tests factorial of positive numbers.
|
||||
TEST(FactorialTest, Positive) {
|
||||
|
|
@ -112,7 +107,6 @@ TEST(FactorialTest, Positive) {
|
|||
EXPECT_EQ(40320, Factorial(8));
|
||||
}
|
||||
|
||||
|
||||
// Tests IsPrime()
|
||||
|
||||
// Tests negative input.
|
||||
|
|
@ -139,6 +133,7 @@ TEST(IsPrimeTest, Positive) {
|
|||
EXPECT_FALSE(IsPrime(6));
|
||||
EXPECT_TRUE(IsPrime(23));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Step 3. Call RUN_ALL_TESTS() in main().
|
||||
//
|
||||
|
|
|
|||
|
|
@ -28,8 +28,6 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include "sample2.h"
|
||||
|
||||
|
|
@ -37,10 +35,10 @@
|
|||
|
||||
// Clones a 0-terminated C string, allocating memory using new.
|
||||
const char* MyString::CloneCString(const char* a_c_string) {
|
||||
if (a_c_string == NULL) return NULL;
|
||||
if (a_c_string == nullptr) return nullptr;
|
||||
|
||||
const size_t len = strlen(a_c_string);
|
||||
char* const clone = new char[ len + 1 ];
|
||||
char* const clone = new char[len + 1];
|
||||
memcpy(clone, a_c_string, len + 1);
|
||||
|
||||
return clone;
|
||||
|
|
|
|||
|
|
@ -28,15 +28,12 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE2_H_
|
||||
#define GTEST_SAMPLES_SAMPLE2_H_
|
||||
#ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_
|
||||
#define GOOGLETEST_SAMPLES_SAMPLE2_H_
|
||||
|
||||
#include <string.h>
|
||||
|
||||
|
||||
// A simple string class.
|
||||
class MyString {
|
||||
private:
|
||||
|
|
@ -52,15 +49,15 @@ class MyString {
|
|||
// C'tors
|
||||
|
||||
// The default c'tor constructs a NULL string.
|
||||
MyString() : c_string_(NULL) {}
|
||||
MyString() : c_string_(nullptr) {}
|
||||
|
||||
// Constructs a MyString by cloning a 0-terminated C string.
|
||||
explicit MyString(const char* a_c_string) : c_string_(NULL) {
|
||||
explicit MyString(const char* a_c_string) : c_string_(nullptr) {
|
||||
Set(a_c_string);
|
||||
}
|
||||
|
||||
// Copy c'tor
|
||||
MyString(const MyString& string) : c_string_(NULL) {
|
||||
MyString(const MyString& string) : c_string_(nullptr) {
|
||||
Set(string.c_string_);
|
||||
}
|
||||
|
||||
|
|
@ -73,13 +70,10 @@ class MyString {
|
|||
// Gets the 0-terminated C string this MyString object represents.
|
||||
const char* c_string() const { return c_string_; }
|
||||
|
||||
size_t Length() const {
|
||||
return c_string_ == NULL ? 0 : strlen(c_string_);
|
||||
}
|
||||
size_t Length() const { return c_string_ == nullptr ? 0 : strlen(c_string_); }
|
||||
|
||||
// Sets the 0-terminated C string this MyString object represents.
|
||||
void Set(const char* c_string);
|
||||
};
|
||||
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE2_H_
|
||||
#endif // GOOGLETEST_SAMPLES_SAMPLE2_H_
|
||||
|
|
|
|||
|
|
@ -28,9 +28,6 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
|
||||
// This sample shows how to write a more complex unit test for a class
|
||||
// that has multiple member functions.
|
||||
|
|
@ -41,8 +38,9 @@
|
|||
// needed.
|
||||
|
||||
#include "sample2.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
namespace {
|
||||
// In this example, we test the MyString class (a simple string).
|
||||
|
||||
// Tests the default c'tor.
|
||||
|
|
@ -69,7 +67,7 @@ TEST(MyString, DefaultConstructor) {
|
|||
// we have to live with this fact.
|
||||
//
|
||||
// </TechnicalDetails>
|
||||
EXPECT_STREQ(NULL, s.c_string());
|
||||
EXPECT_STREQ(nullptr, s.c_string());
|
||||
|
||||
EXPECT_EQ(0u, s.Length());
|
||||
}
|
||||
|
|
@ -80,8 +78,7 @@ const char kHelloString[] = "Hello, world!";
|
|||
TEST(MyString, ConstructorFromCString) {
|
||||
const MyString s(kHelloString);
|
||||
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
|
||||
EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1,
|
||||
s.Length());
|
||||
EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length());
|
||||
}
|
||||
|
||||
// Tests the copy c'tor.
|
||||
|
|
@ -104,6 +101,7 @@ TEST(MyString, Set) {
|
|||
EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));
|
||||
|
||||
// Can we set the MyString to NULL?
|
||||
s.Set(NULL);
|
||||
EXPECT_STREQ(NULL, s.c_string());
|
||||
s.Set(nullptr);
|
||||
EXPECT_STREQ(nullptr, s.c_string());
|
||||
}
|
||||
} // namespace
|
||||
|
|
|
|||
|
|
@ -28,15 +28,12 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
#define GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
#ifndef GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
|
||||
#define GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
// Queue is a simple queue implemented as a singled-linked list.
|
||||
//
|
||||
// The element type must support copy constructor.
|
||||
|
|
@ -60,10 +57,11 @@ class QueueNode {
|
|||
private:
|
||||
// Creates a node with a given element value. The next pointer is
|
||||
// set to NULL.
|
||||
explicit QueueNode(const E& an_element) : element_(an_element), next_(NULL) {}
|
||||
explicit QueueNode(const E& an_element)
|
||||
: element_(an_element), next_(nullptr) {}
|
||||
|
||||
// We disable the default assignment operator and copy c'tor.
|
||||
const QueueNode& operator = (const QueueNode&);
|
||||
const QueueNode& operator=(const QueueNode&);
|
||||
QueueNode(const QueueNode&);
|
||||
|
||||
E element_;
|
||||
|
|
@ -74,7 +72,7 @@ template <typename E> // E is the element type.
|
|||
class Queue {
|
||||
public:
|
||||
// Creates an empty queue.
|
||||
Queue() : head_(NULL), last_(NULL), size_(0) {}
|
||||
Queue() : head_(nullptr), last_(nullptr), size_(0) {}
|
||||
|
||||
// D'tor. Clears the queue.
|
||||
~Queue() { Clear(); }
|
||||
|
|
@ -85,15 +83,15 @@ class Queue {
|
|||
// 1. Deletes every node.
|
||||
QueueNode<E>* node = head_;
|
||||
QueueNode<E>* next = node->next();
|
||||
for (; ;) {
|
||||
for (;;) {
|
||||
delete node;
|
||||
node = next;
|
||||
if (node == NULL) break;
|
||||
if (node == nullptr) break;
|
||||
next = node->next();
|
||||
}
|
||||
|
||||
// 2. Resets the member variables.
|
||||
head_ = last_ = NULL;
|
||||
head_ = last_ = nullptr;
|
||||
size_ = 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -130,14 +128,14 @@ class Queue {
|
|||
// the queue is empty.
|
||||
E* Dequeue() {
|
||||
if (size_ == 0) {
|
||||
return NULL;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const QueueNode<E>* const old_head = head_;
|
||||
head_ = head_->next_;
|
||||
size_--;
|
||||
if (size_ == 0) {
|
||||
last_ = NULL;
|
||||
last_ = nullptr;
|
||||
}
|
||||
|
||||
E* element = new E(old_head->element());
|
||||
|
|
@ -152,7 +150,8 @@ class Queue {
|
|||
template <typename F>
|
||||
Queue* Map(F function) const {
|
||||
Queue* new_queue = new Queue();
|
||||
for (const QueueNode<E>* node = head_; node != NULL; node = node->next_) {
|
||||
for (const QueueNode<E>* node = head_; node != nullptr;
|
||||
node = node->next_) {
|
||||
new_queue->Enqueue(function(node->element()));
|
||||
}
|
||||
|
||||
|
|
@ -162,11 +161,11 @@ class Queue {
|
|||
private:
|
||||
QueueNode<E>* head_; // The first node of the queue.
|
||||
QueueNode<E>* last_; // The last node of the queue.
|
||||
size_t size_; // The number of elements in the queue.
|
||||
size_t size_; // The number of elements in the queue.
|
||||
|
||||
// We disallow copying a queue.
|
||||
Queue(const Queue&);
|
||||
const Queue& operator = (const Queue&);
|
||||
const Queue& operator=(const Queue&);
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE3_INL_H_
|
||||
#endif // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_
|
||||
|
|
|
|||
|
|
@ -28,9 +28,6 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
|
||||
// In this example, we use a more advanced feature of Google Test called
|
||||
// test fixture.
|
||||
|
|
@ -65,16 +62,15 @@
|
|||
|
||||
#include "sample3-inl.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
// To use a test fixture, derive a class from testing::Test.
|
||||
class QueueTest : public testing::Test {
|
||||
class QueueTestSmpl3 : public testing::Test {
|
||||
protected: // You should make the members protected s.t. they can be
|
||||
// accessed from sub-classes.
|
||||
|
||||
// virtual void SetUp() will be called before each test is run. You
|
||||
// should define it if you need to initialize the varaibles.
|
||||
// should define it if you need to initialize the variables.
|
||||
// Otherwise, this can be skipped.
|
||||
virtual void SetUp() {
|
||||
void SetUp() override {
|
||||
q1_.Enqueue(1);
|
||||
q2_.Enqueue(2);
|
||||
q2_.Enqueue(3);
|
||||
|
|
@ -88,22 +84,20 @@ class QueueTest : public testing::Test {
|
|||
// }
|
||||
|
||||
// A helper function that some test uses.
|
||||
static int Double(int n) {
|
||||
return 2*n;
|
||||
}
|
||||
static int Double(int n) { return 2 * n; }
|
||||
|
||||
// A helper function for testing Queue::Map().
|
||||
void MapTester(const Queue<int> * q) {
|
||||
void MapTester(const Queue<int>* q) {
|
||||
// Creates a new queue, where each element is twice as big as the
|
||||
// corresponding one in q.
|
||||
const Queue<int> * const new_q = q->Map(Double);
|
||||
const Queue<int>* const new_q = q->Map(Double);
|
||||
|
||||
// Verifies that the new queue has the same size as q.
|
||||
ASSERT_EQ(q->Size(), new_q->Size());
|
||||
|
||||
// Verifies the relationship between the elements of the two queues.
|
||||
for ( const QueueNode<int> * n1 = q->Head(), * n2 = new_q->Head();
|
||||
n1 != NULL; n1 = n1->next(), n2 = n2->next() ) {
|
||||
for (const QueueNode<int>*n1 = q->Head(), *n2 = new_q->Head();
|
||||
n1 != nullptr; n1 = n1->next(), n2 = n2->next()) {
|
||||
EXPECT_EQ(2 * n1->element(), n2->element());
|
||||
}
|
||||
|
||||
|
|
@ -120,32 +114,33 @@ class QueueTest : public testing::Test {
|
|||
// instead of TEST.
|
||||
|
||||
// Tests the default c'tor.
|
||||
TEST_F(QueueTest, DefaultConstructor) {
|
||||
TEST_F(QueueTestSmpl3, DefaultConstructor) {
|
||||
// You can access data in the test fixture here.
|
||||
EXPECT_EQ(0u, q0_.Size());
|
||||
}
|
||||
|
||||
// Tests Dequeue().
|
||||
TEST_F(QueueTest, Dequeue) {
|
||||
int * n = q0_.Dequeue();
|
||||
EXPECT_TRUE(n == NULL);
|
||||
TEST_F(QueueTestSmpl3, Dequeue) {
|
||||
int* n = q0_.Dequeue();
|
||||
EXPECT_TRUE(n == nullptr);
|
||||
|
||||
n = q1_.Dequeue();
|
||||
ASSERT_TRUE(n != NULL);
|
||||
ASSERT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(1, *n);
|
||||
EXPECT_EQ(0u, q1_.Size());
|
||||
delete n;
|
||||
|
||||
n = q2_.Dequeue();
|
||||
ASSERT_TRUE(n != NULL);
|
||||
ASSERT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(2, *n);
|
||||
EXPECT_EQ(1u, q2_.Size());
|
||||
delete n;
|
||||
}
|
||||
|
||||
// Tests the Queue::Map() function.
|
||||
TEST_F(QueueTest, Map) {
|
||||
TEST_F(QueueTestSmpl3, Map) {
|
||||
MapTester(&q0_);
|
||||
MapTester(&q1_);
|
||||
MapTester(&q2_);
|
||||
}
|
||||
} // namespace
|
||||
|
|
|
|||
|
|
@ -28,19 +28,23 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "sample4.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
// Returns the current counter value, and increments it.
|
||||
int Counter::Increment() {
|
||||
return counter_++;
|
||||
int Counter::Increment() { return counter_++; }
|
||||
|
||||
// Returns the current counter value, and decrements it.
|
||||
// counter can not be less than 0, return 0 in this case
|
||||
int Counter::Decrement() {
|
||||
if (counter_ == 0) {
|
||||
return counter_;
|
||||
} else {
|
||||
return counter_--;
|
||||
}
|
||||
}
|
||||
|
||||
// Prints the current counter value to STDOUT.
|
||||
void Counter::Print() const {
|
||||
printf("%d", counter_);
|
||||
}
|
||||
void Counter::Print() const { printf("%d", counter_); }
|
||||
|
|
|
|||
|
|
@ -28,11 +28,8 @@
|
|||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// A sample program demonstrating using Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_SAMPLES_SAMPLE4_H_
|
||||
#define GTEST_SAMPLES_SAMPLE4_H_
|
||||
#ifndef GOOGLETEST_SAMPLES_SAMPLE4_H_
|
||||
#define GOOGLETEST_SAMPLES_SAMPLE4_H_
|
||||
|
||||
// A simple monotonic counter.
|
||||
class Counter {
|
||||
|
|
@ -46,8 +43,11 @@ class Counter {
|
|||
// Returns the current counter value, and increments it.
|
||||
int Increment();
|
||||
|
||||
// Returns the current counter value, and decrements it.
|
||||
int Decrement();
|
||||
|
||||
// Prints the current counter value to STDOUT.
|
||||
void Print() const;
|
||||
};
|
||||
|
||||
#endif // GTEST_SAMPLES_SAMPLE4_H_
|
||||
#endif // GOOGLETEST_SAMPLES_SAMPLE4_H_
|
||||
|
|
|
|||
|
|
@ -26,20 +26,28 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include "sample4.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
// Tests the Increment() method.
|
||||
|
||||
TEST(Counter, Increment) {
|
||||
Counter c;
|
||||
|
||||
// Test that counter 0 returns 0
|
||||
EXPECT_EQ(0, c.Decrement());
|
||||
|
||||
// EXPECT_EQ() evaluates its arguments exactly once, so they
|
||||
// can have side effects.
|
||||
|
||||
EXPECT_EQ(0, c.Increment());
|
||||
EXPECT_EQ(1, c.Increment());
|
||||
EXPECT_EQ(2, c.Increment());
|
||||
|
||||
EXPECT_EQ(3, c.Decrement());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
|
|
|||
|
|
@ -26,8 +26,6 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
// This sample teaches how to reuse a test fixture in multiple test
|
||||
// cases by deriving sub-fixtures from it.
|
||||
|
|
@ -46,10 +44,11 @@
|
|||
|
||||
#include <limits.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "sample1.h"
|
||||
#include "sample3-inl.h"
|
||||
#include "gtest/gtest.h"
|
||||
#include "sample1.h"
|
||||
|
||||
namespace {
|
||||
// In this sample, we want to ensure that every test finishes within
|
||||
// ~5 seconds. If a test takes longer to run, we consider it a
|
||||
// failure.
|
||||
|
|
@ -64,15 +63,13 @@ class QuickTest : public testing::Test {
|
|||
protected:
|
||||
// Remember that SetUp() is run immediately before a test starts.
|
||||
// This is a good place to record the start time.
|
||||
virtual void SetUp() {
|
||||
start_time_ = time(NULL);
|
||||
}
|
||||
void SetUp() override { start_time_ = time(nullptr); }
|
||||
|
||||
// TearDown() is invoked immediately after a test finishes. Here we
|
||||
// check if the test was too slow.
|
||||
virtual void TearDown() {
|
||||
void TearDown() override {
|
||||
// Gets the time when the test finishes
|
||||
const time_t end_time = time(NULL);
|
||||
const time_t end_time = time(nullptr);
|
||||
|
||||
// Asserts that the test took no more than ~5 seconds. Did you
|
||||
// know that you can use assertions in SetUp() and TearDown() as
|
||||
|
|
@ -84,7 +81,6 @@ class QuickTest : public testing::Test {
|
|||
time_t start_time_;
|
||||
};
|
||||
|
||||
|
||||
// We derive a fixture named IntegerFunctionTest from the QuickTest
|
||||
// fixture. All tests using this fixture will be automatically
|
||||
// required to be quick.
|
||||
|
|
@ -93,7 +89,6 @@ class IntegerFunctionTest : public QuickTest {
|
|||
// Therefore the body is empty.
|
||||
};
|
||||
|
||||
|
||||
// Now we can write tests in the IntegerFunctionTest test case.
|
||||
|
||||
// Tests Factorial()
|
||||
|
|
@ -113,7 +108,6 @@ TEST_F(IntegerFunctionTest, Factorial) {
|
|||
EXPECT_EQ(40320, Factorial(8));
|
||||
}
|
||||
|
||||
|
||||
// Tests IsPrime()
|
||||
TEST_F(IntegerFunctionTest, IsPrime) {
|
||||
// Tests negative input.
|
||||
|
|
@ -134,7 +128,6 @@ TEST_F(IntegerFunctionTest, IsPrime) {
|
|||
EXPECT_TRUE(IsPrime(23));
|
||||
}
|
||||
|
||||
|
||||
// The next test case (named "QueueTest") also needs to be quick, so
|
||||
// we derive another fixture from QuickTest.
|
||||
//
|
||||
|
|
@ -143,7 +136,7 @@ TEST_F(IntegerFunctionTest, IsPrime) {
|
|||
// stuff inside the body of the test fixture, as usual.
|
||||
class QueueTest : public QuickTest {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
void SetUp() override {
|
||||
// First, we need to set up the super fixture (QuickTest).
|
||||
QuickTest::SetUp();
|
||||
|
||||
|
|
@ -166,32 +159,29 @@ class QueueTest : public QuickTest {
|
|||
Queue<int> q2_;
|
||||
};
|
||||
|
||||
|
||||
// Now, let's write tests using the QueueTest fixture.
|
||||
|
||||
// Tests the default constructor.
|
||||
TEST_F(QueueTest, DefaultConstructor) {
|
||||
EXPECT_EQ(0u, q0_.Size());
|
||||
}
|
||||
TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.Size()); }
|
||||
|
||||
// Tests Dequeue().
|
||||
TEST_F(QueueTest, Dequeue) {
|
||||
int* n = q0_.Dequeue();
|
||||
EXPECT_TRUE(n == NULL);
|
||||
EXPECT_TRUE(n == nullptr);
|
||||
|
||||
n = q1_.Dequeue();
|
||||
EXPECT_TRUE(n != NULL);
|
||||
EXPECT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(1, *n);
|
||||
EXPECT_EQ(0u, q1_.Size());
|
||||
delete n;
|
||||
|
||||
n = q2_.Dequeue();
|
||||
EXPECT_TRUE(n != NULL);
|
||||
EXPECT_TRUE(n != nullptr);
|
||||
EXPECT_EQ(2, *n);
|
||||
EXPECT_EQ(1u, q2_.Size());
|
||||
delete n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
// If necessary, you can derive further test fixtures from a derived
|
||||
// fixture itself. For example, you can derive another fixture from
|
||||
// QueueTest. Google Test imposes no limit on how deep the hierarchy
|
||||
|
|
|
|||
|
|
@ -26,17 +26,14 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
// This sample shows how to test common properties of multiple
|
||||
// implementations of the same interface (aka interface tests).
|
||||
|
||||
// The interface and its implementations are in this header.
|
||||
#include "prime_tables.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
// First, we define some factory functions for creating instances of
|
||||
// the implementations. You may be able to skip this step if all your
|
||||
// implementations can be constructed the same way.
|
||||
|
|
@ -62,7 +59,7 @@ class PrimeTableTest : public testing::Test {
|
|||
// implemented by T.
|
||||
PrimeTableTest() : table_(CreatePrimeTable<T>()) {}
|
||||
|
||||
virtual ~PrimeTableTest() { delete table_; }
|
||||
~PrimeTableTest() override { delete table_; }
|
||||
|
||||
// Note that we test an implementation via the base interface
|
||||
// instead of the actual implementation class. This is important
|
||||
|
|
@ -74,8 +71,6 @@ class PrimeTableTest : public testing::Test {
|
|||
PrimeTable* const table_;
|
||||
};
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
|
||||
using testing::Types;
|
||||
|
||||
// Google Test offers two ways for reusing tests for different types.
|
||||
|
|
@ -85,7 +80,7 @@ using testing::Types;
|
|||
|
||||
// To write a typed test case, first use
|
||||
//
|
||||
// TYPED_TEST_CASE(TestCaseName, TypeList);
|
||||
// TYPED_TEST_SUITE(TestCaseName, TypeList);
|
||||
//
|
||||
// to declare it and specify the type parameters. As with TEST_F,
|
||||
// TestCaseName must match the test fixture name.
|
||||
|
|
@ -93,7 +88,7 @@ using testing::Types;
|
|||
// The list of types we want to test.
|
||||
typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable> Implementations;
|
||||
|
||||
TYPED_TEST_CASE(PrimeTableTest, Implementations);
|
||||
TYPED_TEST_SUITE(PrimeTableTest, Implementations);
|
||||
|
||||
// Then use TYPED_TEST(TestCaseName, TestName) to define a typed test,
|
||||
// similar to TEST_F.
|
||||
|
|
@ -132,13 +127,9 @@ TYPED_TEST(PrimeTableTest, CanGetNextPrime) {
|
|||
}
|
||||
|
||||
// That's it! Google Test will repeat each TYPED_TEST for each type
|
||||
// in the type list specified in TYPED_TEST_CASE. Sit back and be
|
||||
// in the type list specified in TYPED_TEST_SUITE. Sit back and be
|
||||
// happy that you don't have to define them multiple times.
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
using testing::Types;
|
||||
|
||||
// Sometimes, however, you don't yet know all the types that you want
|
||||
|
|
@ -158,13 +149,12 @@ using testing::Types;
|
|||
// the PrimeTableTest fixture defined earlier:
|
||||
|
||||
template <class T>
|
||||
class PrimeTableTest2 : public PrimeTableTest<T> {
|
||||
};
|
||||
class PrimeTableTest2 : public PrimeTableTest<T> {};
|
||||
|
||||
// Then, declare the test case. The argument is the name of the test
|
||||
// fixture, and also the name of the test case (as usual). The _P
|
||||
// suffix is for "parameterized" or "pattern".
|
||||
TYPED_TEST_CASE_P(PrimeTableTest2);
|
||||
TYPED_TEST_SUITE_P(PrimeTableTest2);
|
||||
|
||||
// Next, use TYPED_TEST_P(TestCaseName, TestName) to define a test,
|
||||
// similar to what you do with TEST_F.
|
||||
|
|
@ -197,7 +187,7 @@ TYPED_TEST_P(PrimeTableTest2, CanGetNextPrime) {
|
|||
|
||||
// Type-parameterized tests involve one extra step: you have to
|
||||
// enumerate the tests you defined:
|
||||
REGISTER_TYPED_TEST_CASE_P(
|
||||
REGISTER_TYPED_TEST_SUITE_P(
|
||||
PrimeTableTest2, // The first argument is the test case name.
|
||||
// The rest of the arguments are the test names.
|
||||
ReturnsFalseForNonPrimes, ReturnsTrueForPrimes, CanGetNextPrime);
|
||||
|
|
@ -217,8 +207,8 @@ REGISTER_TYPED_TEST_CASE_P(
|
|||
// defined at the time we write the TYPED_TEST_P()s.
|
||||
typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable>
|
||||
PrimeTableImplementations;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(OnTheFlyAndPreCalculated, // Instance name
|
||||
PrimeTableTest2, // Test case name
|
||||
PrimeTableImplementations); // Type list
|
||||
INSTANTIATE_TYPED_TEST_SUITE_P(OnTheFlyAndPreCalculated, // Instance name
|
||||
PrimeTableTest2, // Test case name
|
||||
PrimeTableImplementations); // Type list
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
} // namespace
|
||||
|
|
|
|||
|
|
@ -26,8 +26,6 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
|
||||
// This sample shows how to test common properties of multiple
|
||||
// implementations of an interface (aka interface tests) using
|
||||
|
|
@ -37,10 +35,8 @@
|
|||
|
||||
// The interface and its implementations are in this header.
|
||||
#include "prime_tables.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_PARAM_TEST
|
||||
namespace {
|
||||
|
||||
using ::testing::TestWithParam;
|
||||
using ::testing::Values;
|
||||
|
|
@ -52,9 +48,7 @@ using ::testing::Values;
|
|||
// SetUp() method and delete them in TearDown() method.
|
||||
typedef PrimeTable* CreatePrimeTableFunc();
|
||||
|
||||
PrimeTable* CreateOnTheFlyPrimeTable() {
|
||||
return new OnTheFlyPrimeTable();
|
||||
}
|
||||
PrimeTable* CreateOnTheFlyPrimeTable() { return new OnTheFlyPrimeTable(); }
|
||||
|
||||
template <size_t max_precalculated>
|
||||
PrimeTable* CreatePreCalculatedPrimeTable() {
|
||||
|
|
@ -65,20 +59,20 @@ PrimeTable* CreatePreCalculatedPrimeTable() {
|
|||
// can refer to the test parameter by GetParam(). In this case, the test
|
||||
// parameter is a factory function which we call in fixture's SetUp() to
|
||||
// create and store an instance of PrimeTable.
|
||||
class PrimeTableTest : public TestWithParam<CreatePrimeTableFunc*> {
|
||||
class PrimeTableTestSmpl7 : public TestWithParam<CreatePrimeTableFunc*> {
|
||||
public:
|
||||
virtual ~PrimeTableTest() { delete table_; }
|
||||
virtual void SetUp() { table_ = (*GetParam())(); }
|
||||
virtual void TearDown() {
|
||||
~PrimeTableTestSmpl7() override { delete table_; }
|
||||
void SetUp() override { table_ = (*GetParam())(); }
|
||||
void TearDown() override {
|
||||
delete table_;
|
||||
table_ = NULL;
|
||||
table_ = nullptr;
|
||||
}
|
||||
|
||||
protected:
|
||||
PrimeTable* table_;
|
||||
};
|
||||
|
||||
TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {
|
||||
TEST_P(PrimeTableTestSmpl7, ReturnsFalseForNonPrimes) {
|
||||
EXPECT_FALSE(table_->IsPrime(-5));
|
||||
EXPECT_FALSE(table_->IsPrime(0));
|
||||
EXPECT_FALSE(table_->IsPrime(1));
|
||||
|
|
@ -87,7 +81,7 @@ TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {
|
|||
EXPECT_FALSE(table_->IsPrime(100));
|
||||
}
|
||||
|
||||
TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {
|
||||
TEST_P(PrimeTableTestSmpl7, ReturnsTrueForPrimes) {
|
||||
EXPECT_TRUE(table_->IsPrime(2));
|
||||
EXPECT_TRUE(table_->IsPrime(3));
|
||||
EXPECT_TRUE(table_->IsPrime(5));
|
||||
|
|
@ -96,7 +90,7 @@ TEST_P(PrimeTableTest, ReturnsTrueForPrimes) {
|
|||
EXPECT_TRUE(table_->IsPrime(131));
|
||||
}
|
||||
|
||||
TEST_P(PrimeTableTest, CanGetNextPrime) {
|
||||
TEST_P(PrimeTableTestSmpl7, CanGetNextPrime) {
|
||||
EXPECT_EQ(2, table_->GetNextPrime(0));
|
||||
EXPECT_EQ(3, table_->GetNextPrime(2));
|
||||
EXPECT_EQ(5, table_->GetNextPrime(3));
|
||||
|
|
@ -112,19 +106,8 @@ TEST_P(PrimeTableTest, CanGetNextPrime) {
|
|||
//
|
||||
// Here, we instantiate our tests with a list of two PrimeTable object
|
||||
// factory functions:
|
||||
INSTANTIATE_TEST_CASE_P(
|
||||
OnTheFlyAndPreCalculated,
|
||||
PrimeTableTest,
|
||||
Values(&CreateOnTheFlyPrimeTable, &CreatePreCalculatedPrimeTable<1000>));
|
||||
INSTANTIATE_TEST_SUITE_P(OnTheFlyAndPreCalculated, PrimeTableTestSmpl7,
|
||||
Values(&CreateOnTheFlyPrimeTable,
|
||||
&CreatePreCalculatedPrimeTable<1000>));
|
||||
|
||||
#else
|
||||
|
||||
// Google Test may not support value-parameterized tests with some
|
||||
// compilers. If we use conditional compilation to compile out all
|
||||
// code referring to the gtest_main library, MSVC linker will not link
|
||||
// that library at all and consequently complain about missing entry
|
||||
// point defined in that library (fatal error LNK1561: entry point
|
||||
// must be defined). This dummy test keeps gtest_main linked in.
|
||||
TEST(DummyTest, ValueParameterizedTestsAreNotSupportedOnThisPlatform) {}
|
||||
|
||||
#endif // GTEST_HAS_PARAM_TEST
|
||||
} // namespace
|
||||
|
|
|
|||
|
|
@ -26,8 +26,6 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
|
||||
// This sample shows how to test code relying on some global flag variables.
|
||||
// Combine() helps with generating all possible combinations of such flags,
|
||||
|
|
@ -35,10 +33,8 @@
|
|||
|
||||
// Use class definitions to test from this header.
|
||||
#include "prime_tables.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_COMBINE
|
||||
namespace {
|
||||
|
||||
// Suppose we want to introduce a new, improved implementation of PrimeTable
|
||||
// which combines speed of PrecalcPrimeTable and versatility of
|
||||
|
|
@ -51,24 +47,25 @@ class HybridPrimeTable : public PrimeTable {
|
|||
public:
|
||||
HybridPrimeTable(bool force_on_the_fly, int max_precalculated)
|
||||
: on_the_fly_impl_(new OnTheFlyPrimeTable),
|
||||
precalc_impl_(force_on_the_fly ? NULL :
|
||||
new PreCalculatedPrimeTable(max_precalculated)),
|
||||
precalc_impl_(force_on_the_fly
|
||||
? nullptr
|
||||
: new PreCalculatedPrimeTable(max_precalculated)),
|
||||
max_precalculated_(max_precalculated) {}
|
||||
virtual ~HybridPrimeTable() {
|
||||
~HybridPrimeTable() override {
|
||||
delete on_the_fly_impl_;
|
||||
delete precalc_impl_;
|
||||
}
|
||||
|
||||
virtual bool IsPrime(int n) const {
|
||||
if (precalc_impl_ != NULL && n < max_precalculated_)
|
||||
bool IsPrime(int n) const override {
|
||||
if (precalc_impl_ != nullptr && n < max_precalculated_)
|
||||
return precalc_impl_->IsPrime(n);
|
||||
else
|
||||
return on_the_fly_impl_->IsPrime(n);
|
||||
}
|
||||
|
||||
virtual int GetNextPrime(int p) const {
|
||||
int GetNextPrime(int p) const override {
|
||||
int next_prime = -1;
|
||||
if (precalc_impl_ != NULL && p < max_precalculated_)
|
||||
if (precalc_impl_ != nullptr && p < max_precalculated_)
|
||||
next_prime = precalc_impl_->GetNextPrime(p);
|
||||
|
||||
return next_prime != -1 ? next_prime : on_the_fly_impl_->GetNextPrime(p);
|
||||
|
|
@ -80,34 +77,27 @@ class HybridPrimeTable : public PrimeTable {
|
|||
int max_precalculated_;
|
||||
};
|
||||
|
||||
using ::testing::TestWithParam;
|
||||
using ::testing::Bool;
|
||||
using ::testing::Values;
|
||||
using ::testing::Combine;
|
||||
using ::testing::TestWithParam;
|
||||
using ::testing::Values;
|
||||
|
||||
// To test all code paths for HybridPrimeTable we must test it with numbers
|
||||
// both within and outside PreCalculatedPrimeTable's capacity and also with
|
||||
// PreCalculatedPrimeTable disabled. We do this by defining fixture which will
|
||||
// accept different combinations of parameters for instantiating a
|
||||
// HybridPrimeTable instance.
|
||||
class PrimeTableTest : public TestWithParam< ::testing::tuple<bool, int> > {
|
||||
class PrimeTableTest : public TestWithParam< ::std::tuple<bool, int> > {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
// This can be written as
|
||||
//
|
||||
// bool force_on_the_fly;
|
||||
// int max_precalculated;
|
||||
// tie(force_on_the_fly, max_precalculated) = GetParam();
|
||||
//
|
||||
// once the Google C++ Style Guide allows use of ::std::tr1::tie.
|
||||
//
|
||||
bool force_on_the_fly = ::testing::get<0>(GetParam());
|
||||
int max_precalculated = ::testing::get<1>(GetParam());
|
||||
void SetUp() override {
|
||||
bool force_on_the_fly;
|
||||
int max_precalculated;
|
||||
std::tie(force_on_the_fly, max_precalculated) = GetParam();
|
||||
table_ = new HybridPrimeTable(force_on_the_fly, max_precalculated);
|
||||
}
|
||||
virtual void TearDown() {
|
||||
void TearDown() override {
|
||||
delete table_;
|
||||
table_ = NULL;
|
||||
table_ = nullptr;
|
||||
}
|
||||
HybridPrimeTable* table_;
|
||||
};
|
||||
|
|
@ -156,18 +146,7 @@ TEST_P(PrimeTableTest, CanGetNextPrime) {
|
|||
// will put some of the tested numbers beyond the capability of the
|
||||
// PrecalcPrimeTable instance and some inside it (10). Combine will produce all
|
||||
// possible combinations.
|
||||
INSTANTIATE_TEST_CASE_P(MeaningfulTestParameters,
|
||||
PrimeTableTest,
|
||||
Combine(Bool(), Values(1, 10)));
|
||||
INSTANTIATE_TEST_SUITE_P(MeaningfulTestParameters, PrimeTableTest,
|
||||
Combine(Bool(), Values(1, 10)));
|
||||
|
||||
#else
|
||||
|
||||
// Google Test may not support Combine() with some compilers. If we
|
||||
// use conditional compilation to compile out all code referring to
|
||||
// the gtest_main library, MSVC linker will not link that library at
|
||||
// all and consequently complain about missing entry point defined in
|
||||
// that library (fatal error LNK1561: entry point must be
|
||||
// defined). This dummy test keeps gtest_main linked in.
|
||||
TEST(DummyTest, CombineIsNotSupportedOnThisPlatform) {}
|
||||
|
||||
#endif // GTEST_HAS_COMBINE
|
||||
} // namespace
|
||||
|
|
|
|||
|
|
@ -25,12 +25,10 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
|
||||
// This sample shows how to use Google Test listener API to implement
|
||||
// an alternative console output and how to use the UnitTest reflection API
|
||||
// to enumerate test cases and tests and to inspect their results.
|
||||
// to enumerate test suites and tests and to inspect their results.
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
|
|
@ -39,52 +37,44 @@
|
|||
using ::testing::EmptyTestEventListener;
|
||||
using ::testing::InitGoogleTest;
|
||||
using ::testing::Test;
|
||||
using ::testing::TestCase;
|
||||
using ::testing::TestEventListeners;
|
||||
using ::testing::TestInfo;
|
||||
using ::testing::TestPartResult;
|
||||
using ::testing::TestSuite;
|
||||
using ::testing::UnitTest;
|
||||
|
||||
namespace {
|
||||
|
||||
// Provides alternative output mode which produces minimal amount of
|
||||
// information about tests.
|
||||
class TersePrinter : public EmptyTestEventListener {
|
||||
private:
|
||||
// Called before any test activity starts.
|
||||
virtual void OnTestProgramStart(const UnitTest& /* unit_test */) {}
|
||||
void OnTestProgramStart(const UnitTest& /* unit_test */) override {}
|
||||
|
||||
// Called after all test activities have ended.
|
||||
virtual void OnTestProgramEnd(const UnitTest& unit_test) {
|
||||
void OnTestProgramEnd(const UnitTest& unit_test) override {
|
||||
fprintf(stdout, "TEST %s\n", unit_test.Passed() ? "PASSED" : "FAILED");
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// Called before a test starts.
|
||||
virtual void OnTestStart(const TestInfo& test_info) {
|
||||
fprintf(stdout,
|
||||
"*** Test %s.%s starting.\n",
|
||||
test_info.test_case_name(),
|
||||
void OnTestStart(const TestInfo& test_info) override {
|
||||
fprintf(stdout, "*** Test %s.%s starting.\n", test_info.test_suite_name(),
|
||||
test_info.name());
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// Called after a failed assertion or a SUCCEED() invocation.
|
||||
virtual void OnTestPartResult(const TestPartResult& test_part_result) {
|
||||
fprintf(stdout,
|
||||
"%s in %s:%d\n%s\n",
|
||||
void OnTestPartResult(const TestPartResult& test_part_result) override {
|
||||
fprintf(stdout, "%s in %s:%d\n%s\n",
|
||||
test_part_result.failed() ? "*** Failure" : "Success",
|
||||
test_part_result.file_name(),
|
||||
test_part_result.line_number(),
|
||||
test_part_result.file_name(), test_part_result.line_number(),
|
||||
test_part_result.summary());
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
// Called after a test ends.
|
||||
virtual void OnTestEnd(const TestInfo& test_info) {
|
||||
fprintf(stdout,
|
||||
"*** Test %s.%s ending.\n",
|
||||
test_info.test_case_name(),
|
||||
void OnTestEnd(const TestInfo& test_info) override {
|
||||
fprintf(stdout, "*** Test %s.%s ending.\n", test_info.test_suite_name(),
|
||||
test_info.name());
|
||||
fflush(stdout);
|
||||
}
|
||||
|
|
@ -102,17 +92,17 @@ TEST(CustomOutputTest, Fails) {
|
|||
EXPECT_EQ(1, 2)
|
||||
<< "This test fails in order to demonstrate alternative failure messages";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int main(int argc, char** argv) {
|
||||
InitGoogleTest(&argc, argv);
|
||||
|
||||
bool terse_output = false;
|
||||
if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 )
|
||||
if (argc > 1 && strcmp(argv[1], "--terse_output") == 0)
|
||||
terse_output = true;
|
||||
else
|
||||
printf("%s\n", "Run this program with --terse_output to change the way "
|
||||
printf("%s\n",
|
||||
"Run this program with --terse_output to change the way "
|
||||
"it prints its output.");
|
||||
|
||||
UnitTest& unit_test = *UnitTest::GetInstance();
|
||||
|
|
@ -139,10 +129,10 @@ int main(int argc, char **argv) {
|
|||
// This is an example of using the UnitTest reflection API to inspect test
|
||||
// results. Here we discount failures from the tests we expected to fail.
|
||||
int unexpectedly_failed_tests = 0;
|
||||
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
|
||||
const TestCase& test_case = *unit_test.GetTestCase(i);
|
||||
for (int j = 0; j < test_case.total_test_count(); ++j) {
|
||||
const TestInfo& test_info = *test_case.GetTestInfo(j);
|
||||
for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {
|
||||
const testing::TestSuite& test_suite = *unit_test.GetTestSuite(i);
|
||||
for (int j = 0; j < test_suite.total_test_count(); ++j) {
|
||||
const TestInfo& test_info = *test_suite.GetTestInfo(j);
|
||||
// Counts failed tests that were not meant to fail (those without
|
||||
// 'Fails' in the name).
|
||||
if (test_info.result()->Failed() &&
|
||||
|
|
@ -153,8 +143,7 @@ int main(int argc, char **argv) {
|
|||
}
|
||||
|
||||
// Test that were meant to fail should not affect the test program outcome.
|
||||
if (unexpectedly_failed_tests == 0)
|
||||
ret_val = 0;
|
||||
if (unexpectedly_failed_tests == 0) ret_val = 0;
|
||||
|
||||
return ret_val;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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'
|
||||
|
|
@ -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
|
||||
http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide 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()
|
||||
|
|
@ -1,730 +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.
|
||||
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
|
||||
|
||||
// Makes sure this header is not included before gtest.h.
|
||||
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
# error Do not include gtest_pred_impl.h directly. Include gtest.h instead.
|
||||
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
|
||||
|
||||
// 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 <typename Pred""" % DEFS
|
||||
|
||||
impl += Iter(n, """,
|
||||
typename T%s""")
|
||||
|
||||
impl += """>
|
||||
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 " << 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 """
|
||||
|
||||
#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 <iostream>
|
||||
|
||||
#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 to circumvent a bug in
|
||||
// gcc 2.95.3, which sometimes has problem with the above template
|
||||
// function.
|
||||
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:
|
||||
virtual void SetUp() {
|
||||
expected_to_finish_ = true;
|
||||
finished_ = false;""" % DEFS
|
||||
|
||||
tests += """
|
||||
""" + Iter(n, 'n%s_ = ') + """0;
|
||||
}
|
||||
"""
|
||||
|
||||
tests += """
|
||||
virtual void TearDown() {
|
||||
// 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 iff the test function is expected to run to finish.
|
||||
static bool expected_to_finish_;
|
||||
|
||||
// true iff 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 iff the assertion is a *_PRED_FORMAT*.
|
||||
use_assert: true iff the assertion is a ASSERT_*.
|
||||
expect_failure: true iff the assertion is expected to fail.
|
||||
use_functor: true iff the first argument of the assertion is
|
||||
a functor (as opposed to a function)
|
||||
use_user_type: true iff 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()
|
||||
|
|
@ -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=<dir> overrides the installation prefix
|
||||
--exec-prefix=<dir> overrides the executable installation prefix
|
||||
--libdir=<dir> overrides the library installation prefix
|
||||
--includedir=<dir> 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
|
||||
|
|
@ -1,855 +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.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
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, e:
|
||||
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(file(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 = file(output_file_path, 'w')
|
||||
output_file.write('// This file was GENERATED by command:\n')
|
||||
output_file.write('// %s %s\n' %
|
||||
(os.path.basename(__file__), os.path.basename(file_path)))
|
||||
output_file.write('// DO NOT EDIT BY HAND!!!\n\n')
|
||||
output_file.write(output_str)
|
||||
output_file.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
|
|
@ -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()
|
||||
|
|
@ -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 $@
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,78 +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.
|
||||
|
||||
"""upload_gtest.py v0.1.0 -- uploads a Google Test patch for review.
|
||||
|
||||
This simple wrapper passes all command line flags and
|
||||
--cc=googletestframework@googlegroups.com to upload.py.
|
||||
|
||||
USAGE: upload_gtest.py [options for upload.py]
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
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()
|
||||
|
|
@ -26,10 +26,9 @@
|
|||
// 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.
|
||||
|
||||
//
|
||||
// Author: mheule@google.com (Markus Heule)
|
||||
//
|
||||
// Google C++ Testing Framework (Google Test)
|
||||
// Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// Sometimes it's desirable to build Google Test by compiling a single file.
|
||||
// This file serves this purpose.
|
||||
|
|
@ -39,10 +38,12 @@
|
|||
#include "gtest/gtest.h"
|
||||
|
||||
// The following lines pull in the real gtest *.cc files.
|
||||
#include "src/gtest.cc"
|
||||
#include "src/gtest-assertion-result.cc"
|
||||
#include "src/gtest-death-test.cc"
|
||||
#include "src/gtest-filepath.cc"
|
||||
#include "src/gtest-matchers.cc"
|
||||
#include "src/gtest-port.cc"
|
||||
#include "src/gtest-printers.cc"
|
||||
#include "src/gtest-test-part.cc"
|
||||
#include "src/gtest-typed-test.cc"
|
||||
#include "src/gtest.cc"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
// Copyright 2008, Google Inc.
|
||||
// Copyright 2005, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
|
|
@ -26,43 +26,52 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: preston.a.jackson@gmail.com (Preston Jackson)
|
||||
//
|
||||
// Google Test - FrameworkSample
|
||||
// widget_test.cc
|
||||
//
|
||||
|
||||
// This is a simple test file for the Widget class in the Widget.framework
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This file defines the AssertionResult type.
|
||||
|
||||
#include "gtest/gtest-assertion-result.h"
|
||||
|
||||
#include <string>
|
||||
#include "gtest/gtest.h"
|
||||
#include <utility>
|
||||
|
||||
#include <Widget/widget.h>
|
||||
#include "gtest/gtest-message.h"
|
||||
|
||||
// This test verifies that the constructor sets the internal state of the
|
||||
// Widget class correctly.
|
||||
TEST(WidgetInitializerTest, TestConstructor) {
|
||||
Widget widget(1.0f, "name");
|
||||
EXPECT_FLOAT_EQ(1.0f, widget.GetFloatValue());
|
||||
EXPECT_EQ(std::string("name"), widget.GetStringValue());
|
||||
namespace testing {
|
||||
|
||||
// AssertionResult constructors.
|
||||
// Used in EXPECT_TRUE/FALSE(assertion_result).
|
||||
AssertionResult::AssertionResult(const AssertionResult& other)
|
||||
: success_(other.success_),
|
||||
message_(other.message_.get() != nullptr
|
||||
? new ::std::string(*other.message_)
|
||||
: static_cast< ::std::string*>(nullptr)) {}
|
||||
|
||||
// Swaps two AssertionResults.
|
||||
void AssertionResult::swap(AssertionResult& other) {
|
||||
using std::swap;
|
||||
swap(success_, other.success_);
|
||||
swap(message_, other.message_);
|
||||
}
|
||||
|
||||
// This test verifies the conversion of the float and string values to int and
|
||||
// char*, respectively.
|
||||
TEST(WidgetInitializerTest, TestConversion) {
|
||||
Widget widget(1.0f, "name");
|
||||
EXPECT_EQ(1, widget.GetIntValue());
|
||||
|
||||
size_t max_size = 128;
|
||||
char buffer[max_size];
|
||||
widget.GetCharPtrValue(buffer, max_size);
|
||||
EXPECT_STREQ("name", buffer);
|
||||
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
|
||||
AssertionResult AssertionResult::operator!() const {
|
||||
AssertionResult negation(!success_);
|
||||
if (message_.get() != nullptr) negation << *message_;
|
||||
return negation;
|
||||
}
|
||||
|
||||
// Use the Google Test main that is linked into the framework. It does something
|
||||
// like this:
|
||||
// int main(int argc, char** argv) {
|
||||
// testing::InitGoogleTest(&argc, argv);
|
||||
// return RUN_ALL_TESTS();
|
||||
// }
|
||||
// Makes a successful assertion result.
|
||||
AssertionResult AssertionSuccess() { return AssertionResult(true); }
|
||||
|
||||
// Makes a failed assertion result.
|
||||
AssertionResult AssertionFailure() { return AssertionResult(false); }
|
||||
|
||||
// Makes a failed assertion result with the given failure message.
|
||||
// Deprecated; use AssertionFailure() << message.
|
||||
AssertionResult AssertionFailure(const Message& message) {
|
||||
return AssertionFailure() << message;
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -26,40 +26,37 @@
|
|||
// 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.
|
||||
//
|
||||
// Authors: keith.ray@gmail.com (Keith Ray)
|
||||
|
||||
#include "gtest/gtest-message.h"
|
||||
#include "gtest/internal/gtest-filepath.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
# include <windows.h>
|
||||
#elif GTEST_OS_WINDOWS
|
||||
# include <direct.h>
|
||||
# include <io.h>
|
||||
#elif GTEST_OS_SYMBIAN
|
||||
// Symbian OpenC has PATH_MAX in sys/syslimits.h
|
||||
# include <sys/syslimits.h>
|
||||
#else
|
||||
# include <limits.h>
|
||||
# include <climits> // Some Linux distributions define PATH_MAX here.
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
#include "gtest/gtest-message.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
# define GTEST_PATH_MAX_ _MAX_PATH
|
||||
#elif defined(PATH_MAX)
|
||||
# define GTEST_PATH_MAX_ PATH_MAX
|
||||
#elif defined(_XOPEN_PATH_MAX)
|
||||
# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
#include <windows.h>
|
||||
#elif GTEST_OS_WINDOWS
|
||||
#include <direct.h>
|
||||
#include <io.h>
|
||||
#else
|
||||
# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
#include <limits.h>
|
||||
|
||||
#include <climits> // Some Linux distributions define PATH_MAX here.
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
#include "gtest/internal/gtest-string.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
#define GTEST_PATH_MAX_ _MAX_PATH
|
||||
#elif defined(PATH_MAX)
|
||||
#define GTEST_PATH_MAX_ PATH_MAX
|
||||
#elif defined(_XOPEN_PATH_MAX)
|
||||
#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
|
||||
#else
|
||||
#define GTEST_PATH_MAX_ _POSIX_PATH_MAX
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
|
|
@ -71,16 +68,16 @@ namespace internal {
|
|||
const char kPathSeparator = '\\';
|
||||
const char kAlternatePathSeparator = '/';
|
||||
const char kAlternatePathSeparatorString[] = "/";
|
||||
# if GTEST_OS_WINDOWS_MOBILE
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
// Windows CE doesn't have a current directory. You should not use
|
||||
// the current directory in tests on Windows CE, but this at least
|
||||
// provides a reasonable fallback.
|
||||
const char kCurrentDirectoryString[] = "\\";
|
||||
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
|
||||
const DWORD kInvalidFileAttributes = 0xffffffff;
|
||||
# else
|
||||
#else
|
||||
const char kCurrentDirectoryString[] = ".\\";
|
||||
# endif // GTEST_OS_WINDOWS_MOBILE
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
#else
|
||||
const char kPathSeparator = '/';
|
||||
const char kCurrentDirectoryString[] = "./";
|
||||
|
|
@ -97,23 +94,25 @@ static bool IsPathSeparator(char c) {
|
|||
|
||||
// Returns the current working directory, or "" if unsuccessful.
|
||||
FilePath FilePath::GetCurrentDir() {
|
||||
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
|
||||
// Windows CE doesn't have a current directory, so we just return
|
||||
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \
|
||||
GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \
|
||||
GTEST_OS_XTENSA
|
||||
// These platforms do not have a current directory, so we just return
|
||||
// something reasonable.
|
||||
return FilePath(kCurrentDirectoryString);
|
||||
#elif GTEST_OS_WINDOWS
|
||||
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
|
||||
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
|
||||
char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
|
||||
return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
|
||||
#else
|
||||
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
|
||||
char cwd[GTEST_PATH_MAX_ + 1] = {'\0'};
|
||||
char* result = getcwd(cwd, sizeof(cwd));
|
||||
# if GTEST_OS_NACL
|
||||
#if GTEST_OS_NACL
|
||||
// getcwd will likely fail in NaCl due to the sandbox, so return something
|
||||
// reasonable. The user may have provided a shim implementation for getcwd,
|
||||
// however, so fallback only when failure is detected.
|
||||
return FilePath(result == NULL ? kCurrentDirectoryString : cwd);
|
||||
# endif // GTEST_OS_NACL
|
||||
return FilePath(result == NULL ? "" : cwd);
|
||||
return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
|
||||
#endif // GTEST_OS_NACL
|
||||
return FilePath(result == nullptr ? "" : cwd);
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
}
|
||||
|
||||
|
|
@ -124,13 +123,13 @@ FilePath FilePath::GetCurrentDir() {
|
|||
FilePath FilePath::RemoveExtension(const char* extension) const {
|
||||
const std::string dot_extension = std::string(".") + extension;
|
||||
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
|
||||
return FilePath(pathname_.substr(
|
||||
0, pathname_.length() - dot_extension.length()));
|
||||
return FilePath(
|
||||
pathname_.substr(0, pathname_.length() - dot_extension.length()));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Returns a pointer to the last occurence of a valid path separator in
|
||||
// Returns a pointer to the last occurrence of a valid path separator in
|
||||
// the FilePath. On Windows, for example, both '/' and '\' are valid path
|
||||
// separators. Returns NULL if no path separator was found.
|
||||
const char* FilePath::FindLastPathSeparator() const {
|
||||
|
|
@ -138,8 +137,8 @@ const char* FilePath::FindLastPathSeparator() const {
|
|||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
|
||||
// Comparing two pointers of which only one is NULL is undefined.
|
||||
if (last_alt_sep != NULL &&
|
||||
(last_sep == NULL || last_alt_sep > last_sep)) {
|
||||
if (last_alt_sep != nullptr &&
|
||||
(last_sep == nullptr || last_alt_sep > last_sep)) {
|
||||
return last_alt_sep;
|
||||
}
|
||||
#endif
|
||||
|
|
@ -167,7 +166,7 @@ FilePath FilePath::RemoveFileName() const {
|
|||
const char* const last_sep = FindLastPathSeparator();
|
||||
std::string dir;
|
||||
if (last_sep) {
|
||||
dir = std::string(c_str(), last_sep + 1 - c_str());
|
||||
dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));
|
||||
} else {
|
||||
dir = kCurrentDirectoryString;
|
||||
}
|
||||
|
|
@ -181,15 +180,14 @@ FilePath FilePath::RemoveFileName() const {
|
|||
// than zero (e.g., 12), returns "dir/test_12.xml".
|
||||
// On Windows platform, uses \ as the separator rather than /.
|
||||
FilePath FilePath::MakeFileName(const FilePath& directory,
|
||||
const FilePath& base_name,
|
||||
int number,
|
||||
const FilePath& base_name, int number,
|
||||
const char* extension) {
|
||||
std::string file;
|
||||
if (number == 0) {
|
||||
file = base_name.string() + "." + extension;
|
||||
} else {
|
||||
file = base_name.string() + "_" + StreamableToString(number)
|
||||
+ "." + extension;
|
||||
file =
|
||||
base_name.string() + "_" + StreamableToString(number) + "." + extension;
|
||||
}
|
||||
return ConcatPaths(directory, FilePath(file));
|
||||
}
|
||||
|
|
@ -198,8 +196,7 @@ FilePath FilePath::MakeFileName(const FilePath& directory,
|
|||
// On Windows, uses \ as the separator rather than /.
|
||||
FilePath FilePath::ConcatPaths(const FilePath& directory,
|
||||
const FilePath& relative_path) {
|
||||
if (directory.IsEmpty())
|
||||
return relative_path;
|
||||
if (directory.IsEmpty()) return relative_path;
|
||||
const FilePath dir(directory.RemoveTrailingPathSeparator());
|
||||
return FilePath(dir.string() + kPathSeparator + relative_path.string());
|
||||
}
|
||||
|
|
@ -210,10 +207,10 @@ bool FilePath::FileOrDirectoryExists() const {
|
|||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
|
||||
const DWORD attributes = GetFileAttributes(unicode);
|
||||
delete [] unicode;
|
||||
delete[] unicode;
|
||||
return attributes != kInvalidFileAttributes;
|
||||
#else
|
||||
posix::StatStruct file_stat;
|
||||
posix::StatStruct file_stat{};
|
||||
return posix::Stat(pathname_.c_str(), &file_stat) == 0;
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
}
|
||||
|
|
@ -225,8 +222,8 @@ bool FilePath::DirectoryExists() const {
|
|||
#if GTEST_OS_WINDOWS
|
||||
// Don't strip off trailing separator if path is a root directory on
|
||||
// Windows (like "C:\\").
|
||||
const FilePath& path(IsRootDirectory() ? *this :
|
||||
RemoveTrailingPathSeparator());
|
||||
const FilePath& path(IsRootDirectory() ? *this
|
||||
: RemoveTrailingPathSeparator());
|
||||
#else
|
||||
const FilePath& path(*this);
|
||||
#endif
|
||||
|
|
@ -234,15 +231,15 @@ bool FilePath::DirectoryExists() const {
|
|||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
|
||||
const DWORD attributes = GetFileAttributes(unicode);
|
||||
delete [] unicode;
|
||||
delete[] unicode;
|
||||
if ((attributes != kInvalidFileAttributes) &&
|
||||
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
|
||||
result = true;
|
||||
}
|
||||
#else
|
||||
posix::StatStruct file_stat;
|
||||
result = posix::Stat(path.c_str(), &file_stat) == 0 &&
|
||||
posix::IsDir(file_stat);
|
||||
posix::StatStruct file_stat{};
|
||||
result =
|
||||
posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
return result;
|
||||
|
|
@ -252,9 +249,6 @@ bool FilePath::DirectoryExists() const {
|
|||
// root directory per disk drive.)
|
||||
bool FilePath::IsRootDirectory() const {
|
||||
#if GTEST_OS_WINDOWS
|
||||
// TODO(wan@google.com): on Windows a network share like
|
||||
// \\server\share can be a root directory, although it cannot be the
|
||||
// current directory. Handle this properly.
|
||||
return pathname_.length() == 3 && IsAbsolutePath();
|
||||
#else
|
||||
return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
|
||||
|
|
@ -266,10 +260,9 @@ bool FilePath::IsAbsolutePath() const {
|
|||
const char* const name = pathname_.c_str();
|
||||
#if GTEST_OS_WINDOWS
|
||||
return pathname_.length() >= 3 &&
|
||||
((name[0] >= 'a' && name[0] <= 'z') ||
|
||||
(name[0] >= 'A' && name[0] <= 'Z')) &&
|
||||
name[1] == ':' &&
|
||||
IsPathSeparator(name[2]);
|
||||
((name[0] >= 'a' && name[0] <= 'z') ||
|
||||
(name[0] >= 'A' && name[0] <= 'Z')) &&
|
||||
name[1] == ':' && IsPathSeparator(name[2]);
|
||||
#else
|
||||
return IsPathSeparator(name[0]);
|
||||
#endif
|
||||
|
|
@ -326,10 +319,13 @@ bool FilePath::CreateFolder() const {
|
|||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
FilePath removed_sep(this->RemoveTrailingPathSeparator());
|
||||
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
|
||||
int result = CreateDirectory(unicode, NULL) ? 0 : -1;
|
||||
delete [] unicode;
|
||||
int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
|
||||
delete[] unicode;
|
||||
#elif GTEST_OS_WINDOWS
|
||||
int result = _mkdir(pathname_.c_str());
|
||||
#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA
|
||||
// do nothing
|
||||
int result = 0;
|
||||
#else
|
||||
int result = mkdir(pathname_.c_str(), 0777);
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
|
@ -344,43 +340,27 @@ bool FilePath::CreateFolder() const {
|
|||
// name, otherwise return the name string unmodified.
|
||||
// On Windows platform, uses \ as the separator, other platforms use /.
|
||||
FilePath FilePath::RemoveTrailingPathSeparator() const {
|
||||
return IsDirectory()
|
||||
? FilePath(pathname_.substr(0, pathname_.length() - 1))
|
||||
: *this;
|
||||
return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))
|
||||
: *this;
|
||||
}
|
||||
|
||||
// Removes any redundant separators that might be in the pathname.
|
||||
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
|
||||
// redundancies that might be in a pathname involving "." or "..".
|
||||
// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
|
||||
void FilePath::Normalize() {
|
||||
if (pathname_.c_str() == NULL) {
|
||||
pathname_ = "";
|
||||
return;
|
||||
}
|
||||
const char* src = pathname_.c_str();
|
||||
char* const dest = new char[pathname_.length() + 1];
|
||||
char* dest_ptr = dest;
|
||||
memset(dest_ptr, 0, pathname_.length() + 1);
|
||||
auto out = pathname_.begin();
|
||||
|
||||
while (*src != '\0') {
|
||||
*dest_ptr = *src;
|
||||
if (!IsPathSeparator(*src)) {
|
||||
src++;
|
||||
for (const char character : pathname_) {
|
||||
if (!IsPathSeparator(character)) {
|
||||
*(out++) = character;
|
||||
} else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {
|
||||
*(out++) = kPathSeparator;
|
||||
} else {
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
if (*dest_ptr == kAlternatePathSeparator) {
|
||||
*dest_ptr = kPathSeparator;
|
||||
}
|
||||
#endif
|
||||
while (IsPathSeparator(*src))
|
||||
src++;
|
||||
continue;
|
||||
}
|
||||
dest_ptr++;
|
||||
}
|
||||
*dest_ptr = '\0';
|
||||
pathname_ = dest;
|
||||
delete[] dest;
|
||||
|
||||
pathname_.erase(out, pathname_.end());
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
|
|
|||
|
|
@ -27,50 +27,42 @@
|
|||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Utility functions and classes used by the Google C++ testing framework.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
// Utility functions and classes used by the Google C++ testing framework.//
|
||||
// This file contains purely Google Test's internal implementation. Please
|
||||
// DO NOT #INCLUDE IT IN A USER PROGRAM.
|
||||
|
||||
#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
|
||||
#define GTEST_SRC_GTEST_INTERNAL_INL_H_
|
||||
|
||||
// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
|
||||
// part of Google Test's implementation; otherwise it's undefined.
|
||||
#if !GTEST_IMPLEMENTATION_
|
||||
// If this file is included from the user's code, just say no.
|
||||
# error "gtest-internal-inl.h is part of Google Test's internal implementation."
|
||||
# error "It must not be included except by Google Test itself."
|
||||
#endif // GTEST_IMPLEMENTATION_
|
||||
#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
|
||||
#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
|
||||
|
||||
#ifndef _WIN32_WCE
|
||||
# include <errno.h>
|
||||
#include <errno.h>
|
||||
#endif // !_WIN32_WCE
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
|
||||
#include <string.h> // For memmove.
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
#if GTEST_CAN_STREAM_RESULTS_
|
||||
# include <arpa/inet.h> // NOLINT
|
||||
# include <netdb.h> // NOLINT
|
||||
#include <arpa/inet.h> // NOLINT
|
||||
#include <netdb.h> // NOLINT
|
||||
#endif
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
# include <windows.h> // NOLINT
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
#include <windows.h> // NOLINT
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
#include "gtest/gtest.h" // NOLINT
|
||||
#include "gtest/gtest-spi.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace testing {
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
// Declares the flags.
|
||||
//
|
||||
|
|
@ -79,40 +71,24 @@ namespace testing {
|
|||
// declare it here as opposed to in gtest.h.
|
||||
GTEST_DECLARE_bool_(death_test_use_fork);
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// The value of GetTestTypeId() as seen from within the Google Test
|
||||
// library. This is solely for testing GetTestTypeId().
|
||||
GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
|
||||
|
||||
// Names of the flags (needed for parsing Google Test flags).
|
||||
const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
|
||||
const char kBreakOnFailureFlag[] = "break_on_failure";
|
||||
const char kCatchExceptionsFlag[] = "catch_exceptions";
|
||||
const char kColorFlag[] = "color";
|
||||
const char kFilterFlag[] = "filter";
|
||||
const char kListTestsFlag[] = "list_tests";
|
||||
const char kOutputFlag[] = "output";
|
||||
const char kPrintTimeFlag[] = "print_time";
|
||||
const char kRandomSeedFlag[] = "random_seed";
|
||||
const char kRepeatFlag[] = "repeat";
|
||||
const char kShuffleFlag[] = "shuffle";
|
||||
const char kStackTraceDepthFlag[] = "stack_trace_depth";
|
||||
const char kStreamResultToFlag[] = "stream_result_to";
|
||||
const char kThrowOnFailureFlag[] = "throw_on_failure";
|
||||
const char kFlagfileFlag[] = "flagfile";
|
||||
|
||||
// A valid random seed must be in [1, kMaxRandomSeed].
|
||||
const int kMaxRandomSeed = 99999;
|
||||
|
||||
// g_help_flag is true iff the --help flag or an equivalent form is
|
||||
// specified on the command line.
|
||||
// g_help_flag is true if and only if the --help flag or an equivalent form
|
||||
// is specified on the command line.
|
||||
GTEST_API_ extern bool g_help_flag;
|
||||
|
||||
// Returns the current time in milliseconds.
|
||||
GTEST_API_ TimeInMillis GetTimeInMillis();
|
||||
|
||||
// Returns true iff Google Test should use colors in the output.
|
||||
// Returns true if and only if Google Test should use colors in the output.
|
||||
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
|
||||
|
||||
// Formats the given time in milliseconds as seconds.
|
||||
|
|
@ -128,21 +104,21 @@ GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
|
|||
//
|
||||
// On success, stores the value of the flag in *value, and returns
|
||||
// true. On failure, returns false without changing *value.
|
||||
GTEST_API_ bool ParseInt32Flag(
|
||||
const char* str, const char* flag, Int32* value);
|
||||
GTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);
|
||||
|
||||
// Returns a random seed in range [1, kMaxRandomSeed] based on the
|
||||
// given --gtest_random_seed flag value.
|
||||
inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
|
||||
const unsigned int raw_seed = (random_seed_flag == 0) ?
|
||||
static_cast<unsigned int>(GetTimeInMillis()) :
|
||||
static_cast<unsigned int>(random_seed_flag);
|
||||
inline int GetRandomSeedFromFlag(int32_t random_seed_flag) {
|
||||
const unsigned int raw_seed =
|
||||
(random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())
|
||||
: static_cast<unsigned int>(random_seed_flag);
|
||||
|
||||
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that
|
||||
// it's easy to type.
|
||||
const int normalized_seed =
|
||||
static_cast<int>((raw_seed - 1U) %
|
||||
static_cast<unsigned int>(kMaxRandomSeed)) + 1;
|
||||
static_cast<unsigned int>(kMaxRandomSeed)) +
|
||||
1;
|
||||
return normalized_seed;
|
||||
}
|
||||
|
||||
|
|
@ -163,44 +139,54 @@ class GTestFlagSaver {
|
|||
public:
|
||||
// The c'tor.
|
||||
GTestFlagSaver() {
|
||||
also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
|
||||
break_on_failure_ = GTEST_FLAG(break_on_failure);
|
||||
catch_exceptions_ = GTEST_FLAG(catch_exceptions);
|
||||
color_ = GTEST_FLAG(color);
|
||||
death_test_style_ = GTEST_FLAG(death_test_style);
|
||||
death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
|
||||
filter_ = GTEST_FLAG(filter);
|
||||
internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
|
||||
list_tests_ = GTEST_FLAG(list_tests);
|
||||
output_ = GTEST_FLAG(output);
|
||||
print_time_ = GTEST_FLAG(print_time);
|
||||
random_seed_ = GTEST_FLAG(random_seed);
|
||||
repeat_ = GTEST_FLAG(repeat);
|
||||
shuffle_ = GTEST_FLAG(shuffle);
|
||||
stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
|
||||
stream_result_to_ = GTEST_FLAG(stream_result_to);
|
||||
throw_on_failure_ = GTEST_FLAG(throw_on_failure);
|
||||
also_run_disabled_tests_ = GTEST_FLAG_GET(also_run_disabled_tests);
|
||||
break_on_failure_ = GTEST_FLAG_GET(break_on_failure);
|
||||
catch_exceptions_ = GTEST_FLAG_GET(catch_exceptions);
|
||||
color_ = GTEST_FLAG_GET(color);
|
||||
death_test_style_ = GTEST_FLAG_GET(death_test_style);
|
||||
death_test_use_fork_ = GTEST_FLAG_GET(death_test_use_fork);
|
||||
fail_fast_ = GTEST_FLAG_GET(fail_fast);
|
||||
filter_ = GTEST_FLAG_GET(filter);
|
||||
internal_run_death_test_ = GTEST_FLAG_GET(internal_run_death_test);
|
||||
list_tests_ = GTEST_FLAG_GET(list_tests);
|
||||
output_ = GTEST_FLAG_GET(output);
|
||||
brief_ = GTEST_FLAG_GET(brief);
|
||||
print_time_ = GTEST_FLAG_GET(print_time);
|
||||
print_utf8_ = GTEST_FLAG_GET(print_utf8);
|
||||
random_seed_ = GTEST_FLAG_GET(random_seed);
|
||||
repeat_ = GTEST_FLAG_GET(repeat);
|
||||
recreate_environments_when_repeating_ =
|
||||
GTEST_FLAG_GET(recreate_environments_when_repeating);
|
||||
shuffle_ = GTEST_FLAG_GET(shuffle);
|
||||
stack_trace_depth_ = GTEST_FLAG_GET(stack_trace_depth);
|
||||
stream_result_to_ = GTEST_FLAG_GET(stream_result_to);
|
||||
throw_on_failure_ = GTEST_FLAG_GET(throw_on_failure);
|
||||
}
|
||||
|
||||
// The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
|
||||
~GTestFlagSaver() {
|
||||
GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
|
||||
GTEST_FLAG(break_on_failure) = break_on_failure_;
|
||||
GTEST_FLAG(catch_exceptions) = catch_exceptions_;
|
||||
GTEST_FLAG(color) = color_;
|
||||
GTEST_FLAG(death_test_style) = death_test_style_;
|
||||
GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
|
||||
GTEST_FLAG(filter) = filter_;
|
||||
GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
|
||||
GTEST_FLAG(list_tests) = list_tests_;
|
||||
GTEST_FLAG(output) = output_;
|
||||
GTEST_FLAG(print_time) = print_time_;
|
||||
GTEST_FLAG(random_seed) = random_seed_;
|
||||
GTEST_FLAG(repeat) = repeat_;
|
||||
GTEST_FLAG(shuffle) = shuffle_;
|
||||
GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
|
||||
GTEST_FLAG(stream_result_to) = stream_result_to_;
|
||||
GTEST_FLAG(throw_on_failure) = throw_on_failure_;
|
||||
GTEST_FLAG_SET(also_run_disabled_tests, also_run_disabled_tests_);
|
||||
GTEST_FLAG_SET(break_on_failure, break_on_failure_);
|
||||
GTEST_FLAG_SET(catch_exceptions, catch_exceptions_);
|
||||
GTEST_FLAG_SET(color, color_);
|
||||
GTEST_FLAG_SET(death_test_style, death_test_style_);
|
||||
GTEST_FLAG_SET(death_test_use_fork, death_test_use_fork_);
|
||||
GTEST_FLAG_SET(filter, filter_);
|
||||
GTEST_FLAG_SET(fail_fast, fail_fast_);
|
||||
GTEST_FLAG_SET(internal_run_death_test, internal_run_death_test_);
|
||||
GTEST_FLAG_SET(list_tests, list_tests_);
|
||||
GTEST_FLAG_SET(output, output_);
|
||||
GTEST_FLAG_SET(brief, brief_);
|
||||
GTEST_FLAG_SET(print_time, print_time_);
|
||||
GTEST_FLAG_SET(print_utf8, print_utf8_);
|
||||
GTEST_FLAG_SET(random_seed, random_seed_);
|
||||
GTEST_FLAG_SET(repeat, repeat_);
|
||||
GTEST_FLAG_SET(recreate_environments_when_repeating,
|
||||
recreate_environments_when_repeating_);
|
||||
GTEST_FLAG_SET(shuffle, shuffle_);
|
||||
GTEST_FLAG_SET(stack_trace_depth, stack_trace_depth_);
|
||||
GTEST_FLAG_SET(stream_result_to, stream_result_to_);
|
||||
GTEST_FLAG_SET(throw_on_failure, throw_on_failure_);
|
||||
}
|
||||
|
||||
private:
|
||||
|
|
@ -211,15 +197,19 @@ class GTestFlagSaver {
|
|||
std::string color_;
|
||||
std::string death_test_style_;
|
||||
bool death_test_use_fork_;
|
||||
bool fail_fast_;
|
||||
std::string filter_;
|
||||
std::string internal_run_death_test_;
|
||||
bool list_tests_;
|
||||
std::string output_;
|
||||
bool brief_;
|
||||
bool print_time_;
|
||||
internal::Int32 random_seed_;
|
||||
internal::Int32 repeat_;
|
||||
bool print_utf8_;
|
||||
int32_t random_seed_;
|
||||
int32_t repeat_;
|
||||
bool recreate_environments_when_repeating_;
|
||||
bool shuffle_;
|
||||
internal::Int32 stack_trace_depth_;
|
||||
int32_t stack_trace_depth_;
|
||||
std::string stream_result_to_;
|
||||
bool throw_on_failure_;
|
||||
} GTEST_ATTRIBUTE_UNUSED_;
|
||||
|
|
@ -230,11 +220,11 @@ class GTestFlagSaver {
|
|||
// If the code_point is not a valid Unicode code point
|
||||
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
|
||||
// to "(Invalid Unicode 0xXXXXXXXX)".
|
||||
GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
|
||||
GTEST_API_ std::string CodePointToUtf8(uint32_t code_point);
|
||||
|
||||
// Converts a wide string to a narrow string in UTF-8 encoding.
|
||||
// The wide string is assumed to have the following encoding:
|
||||
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
|
||||
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)
|
||||
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
|
||||
// Parameter str points to a null-terminated wide string.
|
||||
// Parameter num_chars may additionally limit the number
|
||||
|
|
@ -263,17 +253,17 @@ GTEST_API_ bool ShouldShard(const char* total_shards_str,
|
|||
const char* shard_index_str,
|
||||
bool in_subprocess_for_death_test);
|
||||
|
||||
// Parses the environment variable var as an Int32. If it is unset,
|
||||
// returns default_val. If it is not an Int32, prints an error and
|
||||
// Parses the environment variable var as a 32-bit integer. If it is unset,
|
||||
// returns default_val. If it is not a 32-bit integer, prints an error and
|
||||
// and aborts.
|
||||
GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
|
||||
GTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);
|
||||
|
||||
// Given the total number of shards, the shard index, and the test id,
|
||||
// returns true iff the test should be run on this shard. The test id is
|
||||
// some arbitrary but unique non-negative integer assigned to each test
|
||||
// returns true if and only if the test should be run on this shard. The test id
|
||||
// is some arbitrary but unique non-negative integer assigned to each test
|
||||
// method. Assumes that 0 <= shard_index < total_shards.
|
||||
GTEST_API_ bool ShouldRunTestOnShard(
|
||||
int total_shards, int shard_index, int test_id);
|
||||
GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,
|
||||
int test_id);
|
||||
|
||||
// STL container utilities.
|
||||
|
||||
|
|
@ -284,9 +274,8 @@ inline int CountIf(const Container& c, Predicate predicate) {
|
|||
// Implemented as an explicit loop since std::count_if() in libCstd on
|
||||
// Solaris has a non-standard signature.
|
||||
int count = 0;
|
||||
for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
|
||||
if (predicate(*it))
|
||||
++count;
|
||||
for (auto it = c.begin(); it != c.end(); ++it) {
|
||||
if (predicate(*it)) ++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
|
@ -301,7 +290,8 @@ void ForEach(const Container& c, Functor functor) {
|
|||
// in range [0, v.size()).
|
||||
template <typename E>
|
||||
inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
|
||||
return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
|
||||
return (i < 0 || i >= static_cast<int>(v.size())) ? default_value
|
||||
: v[static_cast<size_t>(i)];
|
||||
}
|
||||
|
||||
// Performs an in-place shuffle of a range of the vector's elements.
|
||||
|
|
@ -323,8 +313,11 @@ void ShuffleRange(internal::Random* random, int begin, int end,
|
|||
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
|
||||
for (int range_width = end - begin; range_width >= 2; range_width--) {
|
||||
const int last_in_range = begin + range_width - 1;
|
||||
const int selected = begin + random->Generate(range_width);
|
||||
std::swap((*v)[selected], (*v)[last_in_range]);
|
||||
const int selected =
|
||||
begin +
|
||||
static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));
|
||||
std::swap((*v)[static_cast<size_t>(selected)],
|
||||
(*v)[static_cast<size_t>(last_in_range)]);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -351,7 +344,7 @@ class TestPropertyKeyIs {
|
|||
// TestPropertyKeyIs has NO default constructor.
|
||||
explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
|
||||
|
||||
// Returns true iff the test name of test property matches on key_.
|
||||
// Returns true if and only if the test name of test property matches on key_.
|
||||
bool operator()(const TestProperty& test_property) const {
|
||||
return test_property.key() == key_;
|
||||
}
|
||||
|
|
@ -384,17 +377,10 @@ class GTEST_API_ UnitTestOptions {
|
|||
|
||||
// Functions for processing the gtest_filter flag.
|
||||
|
||||
// Returns true iff the wildcard pattern matches the string. The
|
||||
// first ':' or '\0' character in pattern marks the end of it.
|
||||
//
|
||||
// This recursive algorithm isn't very efficient, but is clear and
|
||||
// works well enough for matching test names, which are short.
|
||||
static bool PatternMatchesString(const char *pattern, const char *str);
|
||||
|
||||
// Returns true iff the user-specified filter matches the test case
|
||||
// name and the test name.
|
||||
static bool FilterMatchesTest(const std::string &test_case_name,
|
||||
const std::string &test_name);
|
||||
// Returns true if and only if the user-specified filter matches the test
|
||||
// suite name and the test name.
|
||||
static bool FilterMatchesTest(const std::string& test_suite_name,
|
||||
const std::string& test_name);
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
// Function for supporting the gtest_catch_exception flag.
|
||||
|
|
@ -426,7 +412,7 @@ class OsStackTraceGetterInterface {
|
|||
// in the trace.
|
||||
// skip_count - the number of top frames to be skipped; doesn't count
|
||||
// against max_depth.
|
||||
virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
|
||||
virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;
|
||||
|
||||
// UponLeavingGTest() should be called immediately before Google Test calls
|
||||
// user code. It saves some information about the current stack that
|
||||
|
|
@ -438,7 +424,9 @@ class OsStackTraceGetterInterface {
|
|||
static const char* const kElidedFramesMarker;
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
|
||||
OsStackTraceGetterInterface(const OsStackTraceGetterInterface&) = delete;
|
||||
OsStackTraceGetterInterface& operator=(const OsStackTraceGetterInterface&) =
|
||||
delete;
|
||||
};
|
||||
|
||||
// A working implementation of the OsStackTraceGetterInterface interface.
|
||||
|
|
@ -446,11 +434,22 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface {
|
|||
public:
|
||||
OsStackTraceGetter() {}
|
||||
|
||||
virtual string CurrentStackTrace(int max_depth, int skip_count);
|
||||
virtual void UponLeavingGTest();
|
||||
std::string CurrentStackTrace(int max_depth, int skip_count) override;
|
||||
void UponLeavingGTest() override;
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
|
||||
#if GTEST_HAS_ABSL
|
||||
Mutex mutex_; // Protects all internal state.
|
||||
|
||||
// We save the stack frame below the frame that calls user code.
|
||||
// We do this because the address of the frame immediately below
|
||||
// the user code changes between the call to UponLeavingGTest()
|
||||
// and any calls to the stack trace code from within the user code.
|
||||
void* caller_frame_ = nullptr;
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
OsStackTraceGetter(const OsStackTraceGetter&) = delete;
|
||||
OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete;
|
||||
};
|
||||
|
||||
// Information about a Google Test trace point.
|
||||
|
|
@ -463,17 +462,20 @@ struct TraceInfo {
|
|||
// This is the default global test part result reporter used in UnitTestImpl.
|
||||
// This class should only be used by UnitTestImpl.
|
||||
class DefaultGlobalTestPartResultReporter
|
||||
: public TestPartResultReporterInterface {
|
||||
: public TestPartResultReporterInterface {
|
||||
public:
|
||||
explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
|
||||
// Implements the TestPartResultReporterInterface. Reports the test part
|
||||
// result in the current test.
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
void ReportTestPartResult(const TestPartResult& result) override;
|
||||
|
||||
private:
|
||||
UnitTestImpl* const unit_test_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
|
||||
DefaultGlobalTestPartResultReporter(
|
||||
const DefaultGlobalTestPartResultReporter&) = delete;
|
||||
DefaultGlobalTestPartResultReporter& operator=(
|
||||
const DefaultGlobalTestPartResultReporter&) = delete;
|
||||
};
|
||||
|
||||
// This is the default per thread test part result reporter used in
|
||||
|
|
@ -484,12 +486,15 @@ class DefaultPerThreadTestPartResultReporter
|
|||
explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
|
||||
// Implements the TestPartResultReporterInterface. The implementation just
|
||||
// delegates to the current global test part result reporter of *unit_test_.
|
||||
virtual void ReportTestPartResult(const TestPartResult& result);
|
||||
void ReportTestPartResult(const TestPartResult& result) override;
|
||||
|
||||
private:
|
||||
UnitTestImpl* const unit_test_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
|
||||
DefaultPerThreadTestPartResultReporter(
|
||||
const DefaultPerThreadTestPartResultReporter&) = delete;
|
||||
DefaultPerThreadTestPartResultReporter& operator=(
|
||||
const DefaultPerThreadTestPartResultReporter&) = delete;
|
||||
};
|
||||
|
||||
// The private implementation of the UnitTest class. We don't protect
|
||||
|
|
@ -522,22 +527,25 @@ class GTEST_API_ UnitTestImpl {
|
|||
void SetTestPartResultReporterForCurrentThread(
|
||||
TestPartResultReporterInterface* reporter);
|
||||
|
||||
// Gets the number of successful test cases.
|
||||
int successful_test_case_count() const;
|
||||
// Gets the number of successful test suites.
|
||||
int successful_test_suite_count() const;
|
||||
|
||||
// Gets the number of failed test cases.
|
||||
int failed_test_case_count() const;
|
||||
// Gets the number of failed test suites.
|
||||
int failed_test_suite_count() const;
|
||||
|
||||
// Gets the number of all test cases.
|
||||
int total_test_case_count() const;
|
||||
// Gets the number of all test suites.
|
||||
int total_test_suite_count() const;
|
||||
|
||||
// Gets the number of all test cases that contain at least one test
|
||||
// Gets the number of all test suites that contain at least one test
|
||||
// that should run.
|
||||
int test_case_to_run_count() const;
|
||||
int test_suite_to_run_count() const;
|
||||
|
||||
// Gets the number of successful tests.
|
||||
int successful_test_count() const;
|
||||
|
||||
// Gets the number of skipped tests.
|
||||
int skipped_test_count() const;
|
||||
|
||||
// Gets the number of failed tests.
|
||||
int failed_test_count() const;
|
||||
|
||||
|
|
@ -563,27 +571,33 @@ class GTEST_API_ UnitTestImpl {
|
|||
// Gets the elapsed time, in milliseconds.
|
||||
TimeInMillis elapsed_time() const { return elapsed_time_; }
|
||||
|
||||
// Returns true iff the unit test passed (i.e. all test cases passed).
|
||||
// Returns true if and only if the unit test passed (i.e. all test suites
|
||||
// passed).
|
||||
bool Passed() const { return !Failed(); }
|
||||
|
||||
// Returns true iff the unit test failed (i.e. some test case failed
|
||||
// or something outside of all tests failed).
|
||||
// Returns true if and only if the unit test failed (i.e. some test suite
|
||||
// failed or something outside of all tests failed).
|
||||
bool Failed() const {
|
||||
return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
|
||||
return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();
|
||||
}
|
||||
|
||||
// Gets the i-th test case among all the test cases. i can range from 0 to
|
||||
// total_test_case_count() - 1. If i is not in that range, returns NULL.
|
||||
const TestCase* GetTestCase(int i) const {
|
||||
const int index = GetElementOr(test_case_indices_, i, -1);
|
||||
return index < 0 ? NULL : test_cases_[i];
|
||||
// Gets the i-th test suite among all the test suites. i can range from 0 to
|
||||
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
|
||||
const TestSuite* GetTestSuite(int i) const {
|
||||
const int index = GetElementOr(test_suite_indices_, i, -1);
|
||||
return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];
|
||||
}
|
||||
|
||||
// Gets the i-th test case among all the test cases. i can range from 0 to
|
||||
// total_test_case_count() - 1. If i is not in that range, returns NULL.
|
||||
TestCase* GetMutableTestCase(int i) {
|
||||
const int index = GetElementOr(test_case_indices_, i, -1);
|
||||
return index < 0 ? NULL : test_cases_[index];
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
// Gets the i-th test suite among all the test suites. i can range from 0 to
|
||||
// total_test_suite_count() - 1. If i is not in that range, returns NULL.
|
||||
TestSuite* GetMutableSuiteCase(int i) {
|
||||
const int index = GetElementOr(test_suite_indices_, i, -1);
|
||||
return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];
|
||||
}
|
||||
|
||||
// Provides access to the event listener list.
|
||||
|
|
@ -618,33 +632,43 @@ class GTEST_API_ UnitTestImpl {
|
|||
// For example, if Foo() calls Bar(), which in turn calls
|
||||
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
|
||||
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
|
||||
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
|
||||
std::string CurrentOsStackTraceExceptTop(int skip_count)
|
||||
GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_;
|
||||
|
||||
// Finds and returns a TestCase with the given name. If one doesn't
|
||||
// Finds and returns a TestSuite with the given name. If one doesn't
|
||||
// exist, creates one and returns it.
|
||||
//
|
||||
// Arguments:
|
||||
//
|
||||
// test_case_name: name of the test case
|
||||
// type_param: the name of the test's type parameter, or NULL if
|
||||
// this is not a typed or a type-parameterized test.
|
||||
// set_up_tc: pointer to the function that sets up the test case
|
||||
// tear_down_tc: pointer to the function that tears down the test case
|
||||
TestCase* GetTestCase(const char* test_case_name,
|
||||
const char* type_param,
|
||||
Test::SetUpTestCaseFunc set_up_tc,
|
||||
Test::TearDownTestCaseFunc tear_down_tc);
|
||||
// test_suite_name: name of the test suite
|
||||
// type_param: the name of the test's type parameter, or NULL if
|
||||
// this is not a typed or a type-parameterized test.
|
||||
// set_up_tc: pointer to the function that sets up the test suite
|
||||
// tear_down_tc: pointer to the function that tears down the test suite
|
||||
TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,
|
||||
internal::SetUpTestSuiteFunc set_up_tc,
|
||||
internal::TearDownTestSuiteFunc tear_down_tc);
|
||||
|
||||
// Legacy API is deprecated but still available
|
||||
#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
TestCase* GetTestCase(const char* test_case_name, const char* type_param,
|
||||
internal::SetUpTestSuiteFunc set_up_tc,
|
||||
internal::TearDownTestSuiteFunc tear_down_tc) {
|
||||
return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);
|
||||
}
|
||||
#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
|
||||
|
||||
// Adds a TestInfo to the unit test.
|
||||
//
|
||||
// Arguments:
|
||||
//
|
||||
// set_up_tc: pointer to the function that sets up the test case
|
||||
// tear_down_tc: pointer to the function that tears down the test case
|
||||
// set_up_tc: pointer to the function that sets up the test suite
|
||||
// tear_down_tc: pointer to the function that tears down the test suite
|
||||
// test_info: the TestInfo object
|
||||
void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
|
||||
Test::TearDownTestCaseFunc tear_down_tc,
|
||||
void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,
|
||||
internal::TearDownTestSuiteFunc tear_down_tc,
|
||||
TestInfo* test_info) {
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
// In order to support thread-safe death tests, we need to
|
||||
// remember the original working directory when the test program
|
||||
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
|
||||
|
|
@ -657,24 +681,33 @@ class GTEST_API_ UnitTestImpl {
|
|||
GTEST_CHECK_(!original_working_dir_.IsEmpty())
|
||||
<< "Failed to get the current working directory.";
|
||||
}
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
GetTestCase(test_info->test_case_name(),
|
||||
test_info->type_param(),
|
||||
set_up_tc,
|
||||
tear_down_tc)->AddTestInfo(test_info);
|
||||
GetTestSuite(test_info->test_suite_name(), test_info->type_param(),
|
||||
set_up_tc, tear_down_tc)
|
||||
->AddTestInfo(test_info);
|
||||
}
|
||||
|
||||
#if GTEST_HAS_PARAM_TEST
|
||||
// Returns ParameterizedTestCaseRegistry object used to keep track of
|
||||
// Returns ParameterizedTestSuiteRegistry object used to keep track of
|
||||
// value-parameterized tests and instantiate and register them.
|
||||
internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
|
||||
internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {
|
||||
return parameterized_test_registry_;
|
||||
}
|
||||
#endif // GTEST_HAS_PARAM_TEST
|
||||
|
||||
// Sets the TestCase object for the test that's currently running.
|
||||
void set_current_test_case(TestCase* a_current_test_case) {
|
||||
current_test_case_ = a_current_test_case;
|
||||
std::set<std::string>* ignored_parameterized_test_suites() {
|
||||
return &ignored_parameterized_test_suites_;
|
||||
}
|
||||
|
||||
// Returns TypeParameterizedTestSuiteRegistry object used to keep track of
|
||||
// type-parameterized tests and instantiations of them.
|
||||
internal::TypeParameterizedTestSuiteRegistry&
|
||||
type_parameterized_test_registry() {
|
||||
return type_parameterized_test_registry_;
|
||||
}
|
||||
|
||||
// Sets the TestSuite object for the test that's currently running.
|
||||
void set_current_test_suite(TestSuite* a_current_test_suite) {
|
||||
current_test_suite_ = a_current_test_suite;
|
||||
}
|
||||
|
||||
// Sets the TestInfo object for the test that's currently running. If
|
||||
|
|
@ -685,7 +718,7 @@ class GTEST_API_ UnitTestImpl {
|
|||
}
|
||||
|
||||
// Registers all parameterized tests defined using TEST_P and
|
||||
// INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
|
||||
// INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter
|
||||
// combination. This method can be called more then once; it has guards
|
||||
// protecting from registering the tests more then once. If
|
||||
// value-parameterized tests are disabled, RegisterParameterizedTests is
|
||||
|
|
@ -700,28 +733,23 @@ class GTEST_API_ UnitTestImpl {
|
|||
|
||||
// Clears the results of all tests, except the ad hoc tests.
|
||||
void ClearNonAdHocTestResult() {
|
||||
ForEach(test_cases_, TestCase::ClearTestCaseResult);
|
||||
ForEach(test_suites_, TestSuite::ClearTestSuiteResult);
|
||||
}
|
||||
|
||||
// Clears the results of ad-hoc test assertions.
|
||||
void ClearAdHocTestResult() {
|
||||
ad_hoc_test_result_.Clear();
|
||||
}
|
||||
void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }
|
||||
|
||||
// Adds a TestProperty to the current TestResult object when invoked in a
|
||||
// context of a test or a test case, or to the global property set. If the
|
||||
// context of a test or a test suite, or to the global property set. If the
|
||||
// result already contains a property with the same key, the value will be
|
||||
// updated.
|
||||
void RecordProperty(const TestProperty& test_property);
|
||||
|
||||
enum ReactionToSharding {
|
||||
HONOR_SHARDING_PROTOCOL,
|
||||
IGNORE_SHARDING_PROTOCOL
|
||||
};
|
||||
enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };
|
||||
|
||||
// Matches the full name of each test against the user-specified
|
||||
// filter to decide whether the test should run, then records the
|
||||
// result in each TestCase and TestInfo object.
|
||||
// result in each TestSuite and TestInfo object.
|
||||
// If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
|
||||
// based on sharding variables in the environment.
|
||||
// Returns the number of tests that should run.
|
||||
|
|
@ -730,7 +758,7 @@ class GTEST_API_ UnitTestImpl {
|
|||
// Prints the names of the tests matching the user-specified filter flag.
|
||||
void ListTestsMatchingFilter();
|
||||
|
||||
const TestCase* current_test_case() const { return current_test_case_; }
|
||||
const TestSuite* current_test_suite() const { return current_test_suite_; }
|
||||
TestInfo* current_test_info() { return current_test_info_; }
|
||||
const TestInfo* current_test_info() const { return current_test_info_; }
|
||||
|
||||
|
|
@ -791,11 +819,11 @@ class GTEST_API_ UnitTestImpl {
|
|||
// Gets the random number generator.
|
||||
internal::Random* random() { return &random_; }
|
||||
|
||||
// Shuffles all test cases, and the tests within each test case,
|
||||
// Shuffles all test suites, and the tests within each test suite,
|
||||
// making sure that death tests are still run first.
|
||||
void ShuffleTests();
|
||||
|
||||
// Restores the test cases and tests to their order before the first shuffle.
|
||||
// Restores the test suites and tests to their order before the first shuffle.
|
||||
void UnshuffleTests();
|
||||
|
||||
// Returns the value of GTEST_FLAG(catch_exceptions) at the moment
|
||||
|
|
@ -835,33 +863,37 @@ class GTEST_API_ UnitTestImpl {
|
|||
// before/after the tests are run.
|
||||
std::vector<Environment*> environments_;
|
||||
|
||||
// The vector of TestCases in their original order. It owns the
|
||||
// The vector of TestSuites in their original order. It owns the
|
||||
// elements in the vector.
|
||||
std::vector<TestCase*> test_cases_;
|
||||
std::vector<TestSuite*> test_suites_;
|
||||
|
||||
// Provides a level of indirection for the test case list to allow
|
||||
// easy shuffling and restoring the test case order. The i-th
|
||||
// element of this vector is the index of the i-th test case in the
|
||||
// Provides a level of indirection for the test suite list to allow
|
||||
// easy shuffling and restoring the test suite order. The i-th
|
||||
// element of this vector is the index of the i-th test suite in the
|
||||
// shuffled order.
|
||||
std::vector<int> test_case_indices_;
|
||||
std::vector<int> test_suite_indices_;
|
||||
|
||||
#if GTEST_HAS_PARAM_TEST
|
||||
// ParameterizedTestRegistry object used to register value-parameterized
|
||||
// tests.
|
||||
internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
|
||||
internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;
|
||||
internal::TypeParameterizedTestSuiteRegistry
|
||||
type_parameterized_test_registry_;
|
||||
|
||||
// The set holding the name of parameterized
|
||||
// test suites that may go uninstantiated.
|
||||
std::set<std::string> ignored_parameterized_test_suites_;
|
||||
|
||||
// Indicates whether RegisterParameterizedTests() has been called already.
|
||||
bool parameterized_tests_registered_;
|
||||
#endif // GTEST_HAS_PARAM_TEST
|
||||
|
||||
// Index of the last death test case registered. Initially -1.
|
||||
int last_death_test_case_;
|
||||
// Index of the last death test suite registered. Initially -1.
|
||||
int last_death_test_suite_;
|
||||
|
||||
// This points to the TestCase for the currently running test. It
|
||||
// changes as Google Test goes through one test case after another.
|
||||
// This points to the TestSuite for the currently running test. It
|
||||
// changes as Google Test goes through one test suite after another.
|
||||
// When no test is running, this is set to NULL and Google Test
|
||||
// stores assertion results in ad_hoc_test_result_. Initially NULL.
|
||||
TestCase* current_test_case_;
|
||||
TestSuite* current_test_suite_;
|
||||
|
||||
// This points to the TestInfo for the currently running test. It
|
||||
// changes as Google Test goes through one test after another. When
|
||||
|
|
@ -889,7 +921,7 @@ class GTEST_API_ UnitTestImpl {
|
|||
// desired.
|
||||
OsStackTraceGetterInterface* os_stack_trace_getter_;
|
||||
|
||||
// True iff PostFlagParsingInit() has been called.
|
||||
// True if and only if PostFlagParsingInit() has been called.
|
||||
bool post_flag_parse_init_performed_;
|
||||
|
||||
// The random number seed used at the beginning of the test run.
|
||||
|
|
@ -908,8 +940,8 @@ class GTEST_API_ UnitTestImpl {
|
|||
#if GTEST_HAS_DEATH_TEST
|
||||
// The decomposed components of the gtest_internal_run_death_test flag,
|
||||
// parsed when RUN_ALL_TESTS is called.
|
||||
internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
|
||||
internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
|
||||
std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
|
||||
std::unique_ptr<internal::DeathTestFactory> death_test_factory_;
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
// A per-thread stack of traces created by the SCOPED_TRACE() macro.
|
||||
|
|
@ -919,7 +951,8 @@ class GTEST_API_ UnitTestImpl {
|
|||
// starts.
|
||||
bool catch_exceptions_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
|
||||
UnitTestImpl(const UnitTestImpl&) = delete;
|
||||
UnitTestImpl& operator=(const UnitTestImpl&) = delete;
|
||||
}; // class UnitTestImpl
|
||||
|
||||
// Convenience function for accessing the global UnitTest
|
||||
|
|
@ -942,8 +975,9 @@ GTEST_API_ bool IsValidEscape(char ch);
|
|||
GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
|
||||
GTEST_API_ bool ValidateRegex(const char* regex);
|
||||
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
|
||||
GTEST_API_ bool MatchRepetitionAndRegexAtHead(
|
||||
bool escaped, char ch, char repeat, const char* regex, const char* str);
|
||||
GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,
|
||||
char repeat, const char* regex,
|
||||
const char* str);
|
||||
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
|
||||
|
||||
#endif // GTEST_USES_SIMPLE_RE
|
||||
|
|
@ -976,24 +1010,11 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
|
|||
char* end;
|
||||
// BiggestConvertible is the largest integer type that system-provided
|
||||
// string-to-number conversion routines can return.
|
||||
using BiggestConvertible = unsigned long long; // NOLINT
|
||||
|
||||
# if GTEST_OS_WINDOWS && !defined(__GNUC__)
|
||||
|
||||
// MSVC and C++ Builder define __int64 instead of the standard long long.
|
||||
typedef unsigned __int64 BiggestConvertible;
|
||||
const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
|
||||
|
||||
# else
|
||||
|
||||
typedef unsigned long long BiggestConvertible; // NOLINT
|
||||
const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
|
||||
|
||||
# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
|
||||
|
||||
const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT
|
||||
const bool parse_success = *end == '\0' && errno == 0;
|
||||
|
||||
// TODO(vladl@google.com): Convert this to compile time assertion when it is
|
||||
// available.
|
||||
GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
|
||||
|
||||
const Integer result = static_cast<Integer>(parsed);
|
||||
|
|
@ -1032,7 +1053,7 @@ class TestResultAccessor {
|
|||
#if GTEST_CAN_STREAM_RESULTS_
|
||||
|
||||
// Streams test results to the given port on the given host machine.
|
||||
class GTEST_API_ StreamingListener : public EmptyTestEventListener {
|
||||
class StreamingListener : public EmptyTestEventListener {
|
||||
public:
|
||||
// Abstract base class for writing strings to a socket.
|
||||
class AbstractSocketWriter {
|
||||
|
|
@ -1040,40 +1061,36 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener {
|
|||
virtual ~AbstractSocketWriter() {}
|
||||
|
||||
// Sends a string to the socket.
|
||||
virtual void Send(const string& message) = 0;
|
||||
virtual void Send(const std::string& message) = 0;
|
||||
|
||||
// Closes the socket.
|
||||
virtual void CloseConnection() {}
|
||||
|
||||
// Sends a string and a newline to the socket.
|
||||
void SendLn(const string& message) {
|
||||
Send(message + "\n");
|
||||
}
|
||||
void SendLn(const std::string& message) { Send(message + "\n"); }
|
||||
};
|
||||
|
||||
// Concrete class for actually writing strings to a socket.
|
||||
class SocketWriter : public AbstractSocketWriter {
|
||||
public:
|
||||
SocketWriter(const string& host, const string& port)
|
||||
SocketWriter(const std::string& host, const std::string& port)
|
||||
: sockfd_(-1), host_name_(host), port_num_(port) {
|
||||
MakeConnection();
|
||||
}
|
||||
|
||||
virtual ~SocketWriter() {
|
||||
if (sockfd_ != -1)
|
||||
CloseConnection();
|
||||
~SocketWriter() override {
|
||||
if (sockfd_ != -1) CloseConnection();
|
||||
}
|
||||
|
||||
// Sends a string to the socket.
|
||||
virtual void Send(const string& message) {
|
||||
void Send(const std::string& message) override {
|
||||
GTEST_CHECK_(sockfd_ != -1)
|
||||
<< "Send() can be called only when there is a connection.";
|
||||
|
||||
const int len = static_cast<int>(message.length());
|
||||
if (write(sockfd_, message.c_str(), len) != len) {
|
||||
GTEST_LOG_(WARNING)
|
||||
<< "stream_result_to: failed to stream to "
|
||||
<< host_name_ << ":" << port_num_;
|
||||
const auto len = static_cast<size_t>(message.length());
|
||||
if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {
|
||||
GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to "
|
||||
<< host_name_ << ":" << port_num_;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1082,7 +1099,7 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener {
|
|||
void MakeConnection();
|
||||
|
||||
// Closes the socket.
|
||||
void CloseConnection() {
|
||||
void CloseConnection() override {
|
||||
GTEST_CHECK_(sockfd_ != -1)
|
||||
<< "CloseConnection() can be called only when there is a connection.";
|
||||
|
||||
|
|
@ -1091,26 +1108,31 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener {
|
|||
}
|
||||
|
||||
int sockfd_; // socket file descriptor
|
||||
const string host_name_;
|
||||
const string port_num_;
|
||||
const std::string host_name_;
|
||||
const std::string port_num_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
|
||||
SocketWriter(const SocketWriter&) = delete;
|
||||
SocketWriter& operator=(const SocketWriter&) = delete;
|
||||
}; // class SocketWriter
|
||||
|
||||
// Escapes '=', '&', '%', and '\n' characters in str as "%xx".
|
||||
static string UrlEncode(const char* str);
|
||||
static std::string UrlEncode(const char* str);
|
||||
|
||||
StreamingListener(const string& host, const string& port)
|
||||
: socket_writer_(new SocketWriter(host, port)) { Start(); }
|
||||
StreamingListener(const std::string& host, const std::string& port)
|
||||
: socket_writer_(new SocketWriter(host, port)) {
|
||||
Start();
|
||||
}
|
||||
|
||||
explicit StreamingListener(AbstractSocketWriter* socket_writer)
|
||||
: socket_writer_(socket_writer) { Start(); }
|
||||
: socket_writer_(socket_writer) {
|
||||
Start();
|
||||
}
|
||||
|
||||
void OnTestProgramStart(const UnitTest& /* unit_test */) {
|
||||
void OnTestProgramStart(const UnitTest& /* unit_test */) override {
|
||||
SendLn("event=TestProgramStart");
|
||||
}
|
||||
|
||||
void OnTestProgramEnd(const UnitTest& unit_test) {
|
||||
void OnTestProgramEnd(const UnitTest& unit_test) override {
|
||||
// Note that Google Test current only report elapsed time for each
|
||||
// test iteration, not for the entire test program.
|
||||
SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
|
||||
|
|
@ -1119,42 +1141,46 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener {
|
|||
socket_writer_->CloseConnection();
|
||||
}
|
||||
|
||||
void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
|
||||
void OnTestIterationStart(const UnitTest& /* unit_test */,
|
||||
int iteration) override {
|
||||
SendLn("event=TestIterationStart&iteration=" +
|
||||
StreamableToString(iteration));
|
||||
}
|
||||
|
||||
void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
|
||||
SendLn("event=TestIterationEnd&passed=" +
|
||||
FormatBool(unit_test.Passed()) + "&elapsed_time=" +
|
||||
StreamableToString(unit_test.elapsed_time()) + "ms");
|
||||
void OnTestIterationEnd(const UnitTest& unit_test,
|
||||
int /* iteration */) override {
|
||||
SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) +
|
||||
"&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) +
|
||||
"ms");
|
||||
}
|
||||
|
||||
void OnTestCaseStart(const TestCase& test_case) {
|
||||
SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
|
||||
// Note that "event=TestCaseStart" is a wire format and has to remain
|
||||
// "case" for compatibility
|
||||
void OnTestSuiteStart(const TestSuite& test_suite) override {
|
||||
SendLn(std::string("event=TestCaseStart&name=") + test_suite.name());
|
||||
}
|
||||
|
||||
void OnTestCaseEnd(const TestCase& test_case) {
|
||||
SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
|
||||
+ "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
|
||||
+ "ms");
|
||||
// Note that "event=TestCaseEnd" is a wire format and has to remain
|
||||
// "case" for compatibility
|
||||
void OnTestSuiteEnd(const TestSuite& test_suite) override {
|
||||
SendLn("event=TestCaseEnd&passed=" + FormatBool(test_suite.Passed()) +
|
||||
"&elapsed_time=" + StreamableToString(test_suite.elapsed_time()) +
|
||||
"ms");
|
||||
}
|
||||
|
||||
void OnTestStart(const TestInfo& test_info) {
|
||||
void OnTestStart(const TestInfo& test_info) override {
|
||||
SendLn(std::string("event=TestStart&name=") + test_info.name());
|
||||
}
|
||||
|
||||
void OnTestEnd(const TestInfo& test_info) {
|
||||
void OnTestEnd(const TestInfo& test_info) override {
|
||||
SendLn("event=TestEnd&passed=" +
|
||||
FormatBool((test_info.result())->Passed()) +
|
||||
"&elapsed_time=" +
|
||||
FormatBool((test_info.result())->Passed()) + "&elapsed_time=" +
|
||||
StreamableToString((test_info.result())->elapsed_time()) + "ms");
|
||||
}
|
||||
|
||||
void OnTestPartResult(const TestPartResult& test_part_result) {
|
||||
void OnTestPartResult(const TestPartResult& test_part_result) override {
|
||||
const char* file_name = test_part_result.file_name();
|
||||
if (file_name == NULL)
|
||||
file_name = "";
|
||||
if (file_name == nullptr) file_name = "";
|
||||
SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
|
||||
"&line=" + StreamableToString(test_part_result.line_number()) +
|
||||
"&message=" + UrlEncode(test_part_result.message()));
|
||||
|
|
@ -1162,17 +1188,18 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener {
|
|||
|
||||
private:
|
||||
// Sends the given message and a newline to the socket.
|
||||
void SendLn(const string& message) { socket_writer_->SendLn(message); }
|
||||
void SendLn(const std::string& message) { socket_writer_->SendLn(message); }
|
||||
|
||||
// Called at the start of streaming to notify the receiver what
|
||||
// protocol we are using.
|
||||
void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
|
||||
|
||||
string FormatBool(bool value) { return value ? "1" : "0"; }
|
||||
std::string FormatBool(bool value) { return value ? "1" : "0"; }
|
||||
|
||||
const scoped_ptr<AbstractSocketWriter> socket_writer_;
|
||||
const std::unique_ptr<AbstractSocketWriter> socket_writer_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
|
||||
StreamingListener(const StreamingListener&) = delete;
|
||||
StreamingListener& operator=(const StreamingListener&) = delete;
|
||||
}; // class StreamingListener
|
||||
|
||||
#endif // GTEST_CAN_STREAM_RESULTS_
|
||||
|
|
@ -1180,4 +1207,6 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener {
|
|||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_
|
||||
|
|
|
|||
98
Engine/lib/assimp/contrib/gtest/src/gtest-matchers.cc
Normal file
98
Engine/lib/assimp/contrib/gtest/src/gtest-matchers.cc
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
// 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.
|
||||
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
//
|
||||
// This file implements just enough of the matcher interface to allow
|
||||
// EXPECT_DEATH and friends to accept a matcher argument.
|
||||
|
||||
#include "gtest/gtest-matchers.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "gtest/internal/gtest-internal.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// Constructs a matcher that matches a const std::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a const std::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const std::string&>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a std::string whose value is equal to
|
||||
// s.
|
||||
Matcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a std::string whose value is equal to
|
||||
// s.
|
||||
Matcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }
|
||||
|
||||
#if GTEST_INTERNAL_HAS_STRING_VIEW
|
||||
// Constructs a matcher that matches a const StringView& whose value is
|
||||
// equal to s.
|
||||
Matcher<const internal::StringView&>::Matcher(const std::string& s) {
|
||||
*this = Eq(s);
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a const StringView& whose value is
|
||||
// equal to s.
|
||||
Matcher<const internal::StringView&>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a const StringView& whose value is
|
||||
// equal to s.
|
||||
Matcher<const internal::StringView&>::Matcher(internal::StringView s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a StringView whose value is equal to
|
||||
// s.
|
||||
Matcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a StringView whose value is equal to
|
||||
// s.
|
||||
Matcher<internal::StringView>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a StringView whose value is equal to
|
||||
// s.
|
||||
Matcher<internal::StringView>::Matcher(internal::StringView s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
#endif // GTEST_INTERNAL_HAS_STRING_VIEW
|
||||
|
||||
} // namespace testing
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -26,10 +26,8 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
// Google Test - The Google C++ Testing Framework
|
||||
// Google Test - The Google C++ Testing and Mocking Framework
|
||||
//
|
||||
// This file implements a universal value printer that can print a
|
||||
// value of any type T:
|
||||
|
|
@ -43,12 +41,18 @@
|
|||
// defines Foo.
|
||||
|
||||
#include "gtest/gtest-printers.h"
|
||||
#include <ctype.h>
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cwchar>
|
||||
#include <ostream> // NOLINT
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "src/gtest-internal-inl.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
|
|
@ -59,6 +63,7 @@ using ::std::ostream;
|
|||
// Prints a segment of bytes in the given object.
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
|
||||
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
|
||||
size_t count, ostream* os) {
|
||||
|
|
@ -89,22 +94,31 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
|
|||
// If the object size is bigger than kThreshold, we'll have to omit
|
||||
// some details by printing only the first and the last kChunkSize
|
||||
// bytes.
|
||||
// TODO(wan): let the user control the threshold using a flag.
|
||||
if (count < kThreshold) {
|
||||
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
|
||||
} else {
|
||||
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
|
||||
*os << " ... ";
|
||||
// Rounds up to 2-byte boundary.
|
||||
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
|
||||
const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
|
||||
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
|
||||
}
|
||||
*os << ">";
|
||||
}
|
||||
|
||||
// Helpers for widening a character to char32_t. Since the standard does not
|
||||
// specify if char / wchar_t is signed or unsigned, it is important to first
|
||||
// convert it to the unsigned type of the same width before widening it to
|
||||
// char32_t.
|
||||
template <typename CharType>
|
||||
char32_t ToChar32(CharType in) {
|
||||
return static_cast<char32_t>(
|
||||
static_cast<typename std::make_unsigned<CharType>::type>(in));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace internal2 {
|
||||
namespace internal {
|
||||
|
||||
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
|
||||
// given object. The delegation simplifies the implementation, which
|
||||
|
|
@ -116,35 +130,25 @@ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
|
|||
PrintBytesInObjectToImpl(obj_bytes, count, os);
|
||||
}
|
||||
|
||||
} // namespace internal2
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Depending on the value of a char (or wchar_t), we print it in one
|
||||
// of three formats:
|
||||
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
|
||||
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
|
||||
// - as a hexadecimal escape sequence (e.g. '\x7F'), or
|
||||
// - as a special escape sequence (e.g. '\r', '\n').
|
||||
enum CharFormat {
|
||||
kAsIs,
|
||||
kHexEscape,
|
||||
kSpecialEscape
|
||||
};
|
||||
enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
|
||||
|
||||
// Returns true if c is a printable ASCII character. We test the
|
||||
// value of c directly instead of calling isprint(), which is buggy on
|
||||
// Windows Mobile.
|
||||
inline bool IsPrintableAscii(wchar_t c) {
|
||||
return 0x20 <= c && c <= 0x7E;
|
||||
}
|
||||
inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
|
||||
|
||||
// Prints a wide or narrow char c as a character literal without the
|
||||
// quotes, escaping it when necessary; returns how c was formatted.
|
||||
// The template argument UnsignedChar is the unsigned version of Char,
|
||||
// which is the type of c.
|
||||
template <typename UnsignedChar, typename Char>
|
||||
// Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
|
||||
// character literal without the quotes, escaping it when necessary; returns how
|
||||
// c was formatted.
|
||||
template <typename Char>
|
||||
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
|
||||
switch (static_cast<wchar_t>(c)) {
|
||||
const char32_t u_c = ToChar32(c);
|
||||
switch (u_c) {
|
||||
case L'\0':
|
||||
*os << "\\0";
|
||||
break;
|
||||
|
|
@ -176,20 +180,22 @@ static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
|
|||
*os << "\\v";
|
||||
break;
|
||||
default:
|
||||
if (IsPrintableAscii(c)) {
|
||||
if (IsPrintableAscii(u_c)) {
|
||||
*os << static_cast<char>(c);
|
||||
return kAsIs;
|
||||
} else {
|
||||
*os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
|
||||
ostream::fmtflags flags = os->flags();
|
||||
*os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
|
||||
os->flags(flags);
|
||||
return kHexEscape;
|
||||
}
|
||||
}
|
||||
return kSpecialEscape;
|
||||
}
|
||||
|
||||
// Prints a wchar_t c as if it's part of a string literal, escaping it when
|
||||
// Prints a char32_t c as if it's part of a string literal, escaping it when
|
||||
// necessary; returns how c was formatted.
|
||||
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
|
||||
static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
|
||||
switch (c) {
|
||||
case L'\'':
|
||||
*os << "'";
|
||||
|
|
@ -198,93 +204,170 @@ static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
|
|||
*os << "\\\"";
|
||||
return kSpecialEscape;
|
||||
default:
|
||||
return PrintAsCharLiteralTo<wchar_t>(c, os);
|
||||
return PrintAsCharLiteralTo(c, os);
|
||||
}
|
||||
}
|
||||
|
||||
static const char* GetCharWidthPrefix(char) { return ""; }
|
||||
|
||||
static const char* GetCharWidthPrefix(signed char) { return ""; }
|
||||
|
||||
static const char* GetCharWidthPrefix(unsigned char) { return ""; }
|
||||
|
||||
#ifdef __cpp_char8_t
|
||||
static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
|
||||
#endif
|
||||
|
||||
static const char* GetCharWidthPrefix(char16_t) { return "u"; }
|
||||
|
||||
static const char* GetCharWidthPrefix(char32_t) { return "U"; }
|
||||
|
||||
static const char* GetCharWidthPrefix(wchar_t) { return "L"; }
|
||||
|
||||
// Prints a char c as if it's part of a string literal, escaping it when
|
||||
// necessary; returns how c was formatted.
|
||||
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
|
||||
return PrintAsStringLiteralTo(
|
||||
static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
|
||||
return PrintAsStringLiteralTo(ToChar32(c), os);
|
||||
}
|
||||
|
||||
// Prints a wide or narrow character c and its code. '\0' is printed
|
||||
// as "'\\0'", other unprintable characters are also properly escaped
|
||||
// using the standard C++ escape sequence. The template argument
|
||||
// UnsignedChar is the unsigned version of Char, which is the type of c.
|
||||
template <typename UnsignedChar, typename Char>
|
||||
#ifdef __cpp_char8_t
|
||||
static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
|
||||
return PrintAsStringLiteralTo(ToChar32(c), os);
|
||||
}
|
||||
#endif
|
||||
|
||||
static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
|
||||
return PrintAsStringLiteralTo(ToChar32(c), os);
|
||||
}
|
||||
|
||||
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
|
||||
return PrintAsStringLiteralTo(ToChar32(c), os);
|
||||
}
|
||||
|
||||
// Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
|
||||
// and its code. '\0' is printed as "'\\0'", other unprintable characters are
|
||||
// also properly escaped using the standard C++ escape sequence.
|
||||
template <typename Char>
|
||||
void PrintCharAndCodeTo(Char c, ostream* os) {
|
||||
// First, print c as a literal in the most readable form we can find.
|
||||
*os << ((sizeof(c) > 1) ? "L'" : "'");
|
||||
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
|
||||
*os << GetCharWidthPrefix(c) << "'";
|
||||
const CharFormat format = PrintAsCharLiteralTo(c, os);
|
||||
*os << "'";
|
||||
|
||||
// To aid user debugging, we also print c's code in decimal, unless
|
||||
// it's 0 (in which case c was printed as '\\0', making the code
|
||||
// obvious).
|
||||
if (c == 0)
|
||||
return;
|
||||
if (c == 0) return;
|
||||
*os << " (" << static_cast<int>(c);
|
||||
|
||||
// For more convenience, we print c's code again in hexidecimal,
|
||||
// For more convenience, we print c's code again in hexadecimal,
|
||||
// unless c was already printed in the form '\x##' or the code is in
|
||||
// [1, 9].
|
||||
if (format == kHexEscape || (1 <= c && c <= 9)) {
|
||||
// Do nothing.
|
||||
} else {
|
||||
*os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
|
||||
*os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
|
||||
}
|
||||
*os << ")";
|
||||
}
|
||||
|
||||
void PrintTo(unsigned char c, ::std::ostream* os) {
|
||||
PrintCharAndCodeTo<unsigned char>(c, os);
|
||||
}
|
||||
void PrintTo(signed char c, ::std::ostream* os) {
|
||||
PrintCharAndCodeTo<unsigned char>(c, os);
|
||||
}
|
||||
void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
|
||||
void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
|
||||
|
||||
// Prints a wchar_t as a symbol if it is printable or as its internal
|
||||
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
|
||||
void PrintTo(wchar_t wc, ostream* os) {
|
||||
PrintCharAndCodeTo<wchar_t>(wc, os);
|
||||
void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
|
||||
|
||||
// TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
|
||||
void PrintTo(char32_t c, ::std::ostream* os) {
|
||||
*os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
|
||||
<< static_cast<uint32_t>(c);
|
||||
}
|
||||
|
||||
// gcc/clang __{u,}int128_t
|
||||
#if defined(__SIZEOF_INT128__)
|
||||
void PrintTo(__uint128_t v, ::std::ostream* os) {
|
||||
if (v == 0) {
|
||||
*os << "0";
|
||||
return;
|
||||
}
|
||||
|
||||
// Buffer large enough for ceil(log10(2^128))==39 and the null terminator
|
||||
char buf[40];
|
||||
char* p = buf + sizeof(buf);
|
||||
|
||||
// Some configurations have a __uint128_t, but no support for built in
|
||||
// division. Do manual long division instead.
|
||||
|
||||
uint64_t high = static_cast<uint64_t>(v >> 64);
|
||||
uint64_t low = static_cast<uint64_t>(v);
|
||||
|
||||
*--p = 0;
|
||||
while (high != 0 || low != 0) {
|
||||
uint64_t high_mod = high % 10;
|
||||
high = high / 10;
|
||||
// This is the long division algorithm specialized for a divisor of 10 and
|
||||
// only two elements.
|
||||
// Notable values:
|
||||
// 2^64 / 10 == 1844674407370955161
|
||||
// 2^64 % 10 == 6
|
||||
const uint64_t carry = 6 * high_mod + low % 10;
|
||||
low = low / 10 + high_mod * 1844674407370955161 + carry / 10;
|
||||
|
||||
char digit = static_cast<char>(carry % 10);
|
||||
*--p = '0' + digit;
|
||||
}
|
||||
*os << p;
|
||||
}
|
||||
void PrintTo(__int128_t v, ::std::ostream* os) {
|
||||
__uint128_t uv = static_cast<__uint128_t>(v);
|
||||
if (v < 0) {
|
||||
*os << "-";
|
||||
uv = -uv;
|
||||
}
|
||||
PrintTo(uv, os);
|
||||
}
|
||||
#endif // __SIZEOF_INT128__
|
||||
|
||||
// Prints the given array of characters to the ostream. CharType must be either
|
||||
// char or wchar_t.
|
||||
// char, char8_t, char16_t, char32_t, or wchar_t.
|
||||
// The array starts at begin, the length is len, it may include '\0' characters
|
||||
// and may not be NUL-terminated.
|
||||
template <typename CharType>
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
|
||||
static void PrintCharsAsStringTo(
|
||||
const CharType* begin, size_t len, ostream* os) {
|
||||
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
|
||||
*os << kQuoteBegin;
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat
|
||||
PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {
|
||||
const char* const quote_prefix = GetCharWidthPrefix(*begin);
|
||||
*os << quote_prefix << "\"";
|
||||
bool is_previous_hex = false;
|
||||
CharFormat print_format = kAsIs;
|
||||
for (size_t index = 0; index < len; ++index) {
|
||||
const CharType cur = begin[index];
|
||||
if (is_previous_hex && IsXDigit(cur)) {
|
||||
// Previous character is of '\x..' form and this character can be
|
||||
// interpreted as another hexadecimal digit in its number. Break string to
|
||||
// disambiguate.
|
||||
*os << "\" " << kQuoteBegin;
|
||||
*os << "\" " << quote_prefix << "\"";
|
||||
}
|
||||
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
|
||||
// Remember if any characters required hex escaping.
|
||||
if (is_previous_hex) {
|
||||
print_format = kHexEscape;
|
||||
}
|
||||
}
|
||||
*os << "\"";
|
||||
return print_format;
|
||||
}
|
||||
|
||||
// Prints a (const) char/wchar_t array of 'len' elements, starting at address
|
||||
// 'begin'. CharType must be either char or wchar_t.
|
||||
template <typename CharType>
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
|
||||
static void UniversalPrintCharArray(
|
||||
const CharType* begin, size_t len, ostream* os) {
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
|
||||
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void
|
||||
UniversalPrintCharArray(const CharType* begin, size_t len,
|
||||
ostream* os) {
|
||||
// The code
|
||||
// const char kFoo[] = "foo";
|
||||
// generates an array of 4, not 3, elements, with the last one being '\0'.
|
||||
|
|
@ -310,22 +393,57 @@ void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
|
|||
UniversalPrintCharArray(begin, len, os);
|
||||
}
|
||||
|
||||
#ifdef __cpp_char8_t
|
||||
// Prints a (const) char8_t array of 'len' elements, starting at address
|
||||
// 'begin'.
|
||||
void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
|
||||
UniversalPrintCharArray(begin, len, os);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Prints a (const) char16_t array of 'len' elements, starting at address
|
||||
// 'begin'.
|
||||
void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
|
||||
UniversalPrintCharArray(begin, len, os);
|
||||
}
|
||||
|
||||
// Prints a (const) char32_t array of 'len' elements, starting at address
|
||||
// 'begin'.
|
||||
void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
|
||||
UniversalPrintCharArray(begin, len, os);
|
||||
}
|
||||
|
||||
// Prints a (const) wchar_t array of 'len' elements, starting at address
|
||||
// 'begin'.
|
||||
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
|
||||
UniversalPrintCharArray(begin, len, os);
|
||||
}
|
||||
|
||||
// Prints the given C string to the ostream.
|
||||
void PrintTo(const char* s, ostream* os) {
|
||||
if (s == NULL) {
|
||||
namespace {
|
||||
|
||||
// Prints a null-terminated C-style string to the ostream.
|
||||
template <typename Char>
|
||||
void PrintCStringTo(const Char* s, ostream* os) {
|
||||
if (s == nullptr) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
*os << ImplicitCast_<const void*>(s) << " pointing to ";
|
||||
PrintCharsAsStringTo(s, strlen(s), os);
|
||||
PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
|
||||
}
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
|
||||
|
||||
#ifdef __cpp_char8_t
|
||||
void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
|
||||
#endif
|
||||
|
||||
void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
|
||||
|
||||
void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
|
||||
|
||||
// MSVC compiler can be configured to define whar_t as a typedef
|
||||
// of unsigned short. Defining an overload for const wchar_t* in that case
|
||||
// would cause pointers to unsigned shorts be printed as wide strings,
|
||||
|
|
@ -334,33 +452,95 @@ void PrintTo(const char* s, ostream* os) {
|
|||
// wchar_t is implemented as a native type.
|
||||
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
|
||||
// Prints the given wide C string to the ostream.
|
||||
void PrintTo(const wchar_t* s, ostream* os) {
|
||||
if (s == NULL) {
|
||||
*os << "NULL";
|
||||
} else {
|
||||
*os << ImplicitCast_<const void*>(s) << " pointing to ";
|
||||
PrintCharsAsStringTo(s, std::wcslen(s), os);
|
||||
}
|
||||
}
|
||||
void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
|
||||
#endif // wchar_t is native
|
||||
|
||||
// Prints a ::string object.
|
||||
#if GTEST_HAS_GLOBAL_STRING
|
||||
void PrintStringTo(const ::string& s, ostream* os) {
|
||||
PrintCharsAsStringTo(s.data(), s.size(), os);
|
||||
namespace {
|
||||
|
||||
bool ContainsUnprintableControlCodes(const char* str, size_t length) {
|
||||
const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
|
||||
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
unsigned char ch = *s++;
|
||||
if (std::iscntrl(ch)) {
|
||||
switch (ch) {
|
||||
case '\t':
|
||||
case '\n':
|
||||
case '\r':
|
||||
break;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t <= 0xbf; }
|
||||
|
||||
bool IsValidUTF8(const char* str, size_t length) {
|
||||
const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
|
||||
|
||||
for (size_t i = 0; i < length;) {
|
||||
unsigned char lead = s[i++];
|
||||
|
||||
if (lead <= 0x7f) {
|
||||
continue; // single-byte character (ASCII) 0..7F
|
||||
}
|
||||
if (lead < 0xc2) {
|
||||
return false; // trail byte or non-shortest form
|
||||
} else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
|
||||
++i; // 2-byte character
|
||||
} else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
|
||||
IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
|
||||
// check for non-shortest form and surrogate
|
||||
(lead != 0xe0 || s[i] >= 0xa0) &&
|
||||
(lead != 0xed || s[i] < 0xa0)) {
|
||||
i += 2; // 3-byte character
|
||||
} else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
|
||||
IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
|
||||
IsUTF8TrailByte(s[i + 2]) &&
|
||||
// check for non-shortest form
|
||||
(lead != 0xf0 || s[i] >= 0x90) &&
|
||||
(lead != 0xf4 || s[i] < 0x90)) {
|
||||
i += 3; // 4-byte character
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
|
||||
if (!ContainsUnprintableControlCodes(str, length) &&
|
||||
IsValidUTF8(str, length)) {
|
||||
*os << "\n As Text: \"" << str << "\"";
|
||||
}
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
void PrintStringTo(const ::std::string& s, ostream* os) {
|
||||
if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
|
||||
if (GTEST_FLAG_GET(print_utf8)) {
|
||||
ConditionalPrintAsText(s.data(), s.size(), os);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __cpp_char8_t
|
||||
void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
|
||||
PrintCharsAsStringTo(s.data(), s.size(), os);
|
||||
}
|
||||
#endif
|
||||
|
||||
void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
|
||||
PrintCharsAsStringTo(s.data(), s.size(), os);
|
||||
}
|
||||
|
||||
// Prints a ::wstring object.
|
||||
#if GTEST_HAS_GLOBAL_WSTRING
|
||||
void PrintWideStringTo(const ::wstring& s, ostream* os) {
|
||||
void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
|
||||
PrintCharsAsStringTo(s.data(), s.size(), os);
|
||||
}
|
||||
#endif // GTEST_HAS_GLOBAL_WSTRING
|
||||
|
||||
#if GTEST_HAS_STD_WSTRING
|
||||
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
|
||||
|
|
|
|||
|
|
@ -26,21 +26,14 @@
|
|||
// 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.
|
||||
|
||||
//
|
||||
// Author: mheule@google.com (Markus Heule)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
// The Google C++ Testing and Mocking Framework (Google Test)
|
||||
|
||||
#include "gtest/gtest-test-part.h"
|
||||
|
||||
// Indicates that this translation unit is part of Google Test's
|
||||
// implementation. It must come before gtest-internal-inl.h is
|
||||
// included, or there will be a compiler error. This trick exists to
|
||||
// prevent the accidental inclusion of gtest-internal-inl.h in the
|
||||
// user's code.
|
||||
#define GTEST_IMPLEMENTATION_ 1
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
#include "src/gtest-internal-inl.h"
|
||||
#undef GTEST_IMPLEMENTATION_
|
||||
|
||||
namespace testing {
|
||||
|
||||
|
|
@ -50,18 +43,21 @@ using internal::GetUnitTestImpl;
|
|||
// in it.
|
||||
std::string TestPartResult::ExtractSummary(const char* message) {
|
||||
const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
|
||||
return stack_trace == NULL ? message :
|
||||
std::string(message, stack_trace);
|
||||
return stack_trace == nullptr ? message : std::string(message, stack_trace);
|
||||
}
|
||||
|
||||
// Prints a TestPartResult object.
|
||||
std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
|
||||
return os
|
||||
<< result.file_name() << ":" << result.line_number() << ": "
|
||||
<< (result.type() == TestPartResult::kSuccess ? "Success" :
|
||||
result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
|
||||
"Non-fatal failure") << ":\n"
|
||||
<< result.message() << std::endl;
|
||||
return os << internal::FormatFileLocation(result.file_name(),
|
||||
result.line_number())
|
||||
<< " "
|
||||
<< (result.type() == TestPartResult::kSuccess ? "Success"
|
||||
: result.type() == TestPartResult::kSkip ? "Skipped"
|
||||
: result.type() == TestPartResult::kFatalFailure
|
||||
? "Fatal failure"
|
||||
: "Non-fatal failure")
|
||||
<< ":\n"
|
||||
<< result.message() << std::endl;
|
||||
}
|
||||
|
||||
// Appends a TestPartResult to the array.
|
||||
|
|
@ -76,7 +72,7 @@ const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
|
|||
internal::posix::Abort();
|
||||
}
|
||||
|
||||
return array_[index];
|
||||
return array_[static_cast<size_t>(index)];
|
||||
}
|
||||
|
||||
// Returns the number of TestPartResult objects in the array.
|
||||
|
|
@ -88,8 +84,8 @@ namespace internal {
|
|||
|
||||
HasNewFatalFailureHelper::HasNewFatalFailureHelper()
|
||||
: has_new_fatal_failure_(false),
|
||||
original_reporter_(GetUnitTestImpl()->
|
||||
GetTestPartResultReporterForCurrentThread()) {
|
||||
original_reporter_(
|
||||
GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {
|
||||
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
|
||||
}
|
||||
|
||||
|
|
@ -100,8 +96,7 @@ HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
|
|||
|
||||
void HasNewFatalFailureHelper::ReportTestPartResult(
|
||||
const TestPartResult& result) {
|
||||
if (result.fatally_failed())
|
||||
has_new_fatal_failure_ = true;
|
||||
if (result.fatally_failed()) has_new_fatal_failure_ = true;
|
||||
original_reporter_->ReportTestPartResult(result);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,29 +26,25 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include "gtest/gtest-typed-test.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// Skips to the first non-space char in str. Returns an empty string if str
|
||||
// contains only whitespace characters.
|
||||
static const char* SkipSpaces(const char* str) {
|
||||
while (IsSpace(*str))
|
||||
str++;
|
||||
while (IsSpace(*str)) str++;
|
||||
return str;
|
||||
}
|
||||
|
||||
static std::vector<std::string> SplitIntoTestNames(const char* src) {
|
||||
std::vector<std::string> name_vec;
|
||||
src = SkipSpaces(src);
|
||||
for (; src != NULL; src = SkipComma(src)) {
|
||||
for (; src != nullptr; src = SkipComma(src)) {
|
||||
name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));
|
||||
}
|
||||
return name_vec;
|
||||
|
|
@ -57,8 +53,11 @@ static std::vector<std::string> SplitIntoTestNames(const char* src) {
|
|||
// Verifies that registered_tests match the test names in
|
||||
// registered_tests_; returns registered_tests if successful, or
|
||||
// aborts the program otherwise.
|
||||
const char* TypedTestCasePState::VerifyRegisteredTestNames(
|
||||
const char* file, int line, const char* registered_tests) {
|
||||
const char* TypedTestSuitePState::VerifyRegisteredTestNames(
|
||||
const char* test_suite_name, const char* file, int line,
|
||||
const char* registered_tests) {
|
||||
RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));
|
||||
|
||||
typedef RegisteredTestsMap::const_iterator RegisteredTestIter;
|
||||
registered_ = true;
|
||||
|
||||
|
|
@ -75,27 +74,16 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames(
|
|||
continue;
|
||||
}
|
||||
|
||||
bool found = false;
|
||||
for (RegisteredTestIter it = registered_tests_.begin();
|
||||
it != registered_tests_.end();
|
||||
++it) {
|
||||
if (name == it->first) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (found) {
|
||||
if (registered_tests_.count(name) != 0) {
|
||||
tests.insert(name);
|
||||
} else {
|
||||
errors << "No test named " << name
|
||||
<< " can be found in this test case.\n";
|
||||
<< " can be found in this test suite.\n";
|
||||
}
|
||||
}
|
||||
|
||||
for (RegisteredTestIter it = registered_tests_.begin();
|
||||
it != registered_tests_.end();
|
||||
++it) {
|
||||
it != registered_tests_.end(); ++it) {
|
||||
if (tests.count(it->first) == 0) {
|
||||
errors << "You forgot to list test " << it->first << ".\n";
|
||||
}
|
||||
|
|
@ -112,7 +100,5 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames(
|
|||
return registered_tests;
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -27,12 +27,27 @@
|
|||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <cstdio>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_OS_ESP8266 || GTEST_OS_ESP32
|
||||
#if GTEST_OS_ESP8266
|
||||
extern "C" {
|
||||
#endif
|
||||
void setup() { testing::InitGoogleTest(); }
|
||||
|
||||
void loop() { RUN_ALL_TESTS(); }
|
||||
|
||||
#if GTEST_OS_ESP8266
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
|
||||
GTEST_API_ int main(int argc, char **argv) {
|
||||
printf("Running main() from gtest_main.cc\n");
|
||||
printf("Running main() from %s\n", __FILE__);
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,93 +0,0 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// Tests that verify interaction of exceptions and death tests.
|
||||
|
||||
#include "gtest/gtest-death-test.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_DEATH_TEST
|
||||
|
||||
# if GTEST_HAS_SEH
|
||||
# include <windows.h> // For RaiseException().
|
||||
# endif
|
||||
|
||||
# include "gtest/gtest-spi.h"
|
||||
|
||||
# if GTEST_HAS_EXCEPTIONS
|
||||
|
||||
# include <exception> // For std::exception.
|
||||
|
||||
// Tests that death tests report thrown exceptions as failures and that the
|
||||
// exceptions do not escape death test macros.
|
||||
TEST(CxxExceptionDeathTest, ExceptionIsFailure) {
|
||||
try {
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, ""), "threw an exception");
|
||||
} catch (...) { // NOLINT
|
||||
FAIL() << "An exception escaped a death test macro invocation "
|
||||
<< "with catch_exceptions "
|
||||
<< (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
|
||||
}
|
||||
}
|
||||
|
||||
class TestException : public std::exception {
|
||||
public:
|
||||
virtual const char* what() const throw() { return "exceptional message"; }
|
||||
};
|
||||
|
||||
TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
|
||||
// Verifies that the exception message is quoted in the failure text.
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
|
||||
"exceptional message");
|
||||
// Verifies that the location is mentioned in the failure text.
|
||||
EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), ""),
|
||||
"gtest-death-test_ex_test.cc");
|
||||
}
|
||||
# endif // GTEST_HAS_EXCEPTIONS
|
||||
|
||||
# if GTEST_HAS_SEH
|
||||
// Tests that enabling interception of SEH exceptions with the
|
||||
// catch_exceptions flag does not interfere with SEH exceptions being
|
||||
// treated as death by death tests.
|
||||
TEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {
|
||||
EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), "")
|
||||
<< "with catch_exceptions "
|
||||
<< (testing::GTEST_FLAG(catch_exceptions) ? "enabled" : "disabled");
|
||||
}
|
||||
# endif
|
||||
|
||||
#endif // GTEST_HAS_DEATH_TEST
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
testing::GTEST_FLAG(catch_exceptions) = GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0;
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,662 +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.
|
||||
//
|
||||
// Authors: keith.ray@gmail.com (Keith Ray)
|
||||
//
|
||||
// Google Test filepath utilities
|
||||
//
|
||||
// This file tests classes and functions used internally by
|
||||
// Google Test. They are subject to change without notice.
|
||||
//
|
||||
// This file is #included from gtest_unittest.cc, to avoid changing
|
||||
// build or make-files for some existing Google Test clients. Do not
|
||||
// #include this file anywhere else!
|
||||
|
||||
#include "gtest/internal/gtest-filepath.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
// Indicates that this translation unit is part of Google Test's
|
||||
// implementation. It must come before gtest-internal-inl.h is
|
||||
// included, or there will be a compiler error. This trick is to
|
||||
// prevent a user from accidentally including gtest-internal-inl.h in
|
||||
// his code.
|
||||
#define GTEST_IMPLEMENTATION_ 1
|
||||
#include "src/gtest-internal-inl.h"
|
||||
#undef GTEST_IMPLEMENTATION_
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
# include <windows.h> // NOLINT
|
||||
#elif GTEST_OS_WINDOWS
|
||||
# include <direct.h> // NOLINT
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
namespace {
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
// TODO(wan@google.com): Move these to the POSIX adapter section in
|
||||
// gtest-port.h.
|
||||
|
||||
// Windows CE doesn't have the remove C function.
|
||||
int remove(const char* path) {
|
||||
LPCWSTR wpath = String::AnsiToUtf16(path);
|
||||
int ret = DeleteFile(wpath) ? 0 : -1;
|
||||
delete [] wpath;
|
||||
return ret;
|
||||
}
|
||||
// Windows CE doesn't have the _rmdir C function.
|
||||
int _rmdir(const char* path) {
|
||||
FilePath filepath(path);
|
||||
LPCWSTR wpath = String::AnsiToUtf16(
|
||||
filepath.RemoveTrailingPathSeparator().c_str());
|
||||
int ret = RemoveDirectory(wpath) ? 0 : -1;
|
||||
delete [] wpath;
|
||||
return ret;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
TEST(GetCurrentDirTest, ReturnsCurrentDir) {
|
||||
const FilePath original_dir = FilePath::GetCurrentDir();
|
||||
EXPECT_FALSE(original_dir.IsEmpty());
|
||||
|
||||
posix::ChDir(GTEST_PATH_SEP_);
|
||||
const FilePath cwd = FilePath::GetCurrentDir();
|
||||
posix::ChDir(original_dir.c_str());
|
||||
|
||||
# if GTEST_OS_WINDOWS
|
||||
|
||||
// Skips the ":".
|
||||
const char* const cwd_without_drive = strchr(cwd.c_str(), ':');
|
||||
ASSERT_TRUE(cwd_without_drive != NULL);
|
||||
EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);
|
||||
|
||||
# else
|
||||
|
||||
EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());
|
||||
|
||||
# endif
|
||||
}
|
||||
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
TEST(IsEmptyTest, ReturnsTrueForEmptyPath) {
|
||||
EXPECT_TRUE(FilePath("").IsEmpty());
|
||||
}
|
||||
|
||||
TEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) {
|
||||
EXPECT_FALSE(FilePath("a").IsEmpty());
|
||||
EXPECT_FALSE(FilePath(".").IsEmpty());
|
||||
EXPECT_FALSE(FilePath("a/b").IsEmpty());
|
||||
EXPECT_FALSE(FilePath("a\\b\\").IsEmpty());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "" -> ""
|
||||
TEST(RemoveDirectoryNameTest, WhenEmptyName) {
|
||||
EXPECT_EQ("", FilePath("").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ButNoDirectory) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "/afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath(GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "adir/" -> ""
|
||||
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {
|
||||
EXPECT_EQ("",
|
||||
FilePath("adir" GTEST_PATH_SEP_).RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "adir/afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldGiveFileName) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName "adir/subdir/afile" -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
|
||||
.RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
|
||||
// Tests that RemoveDirectoryName() works with the alternate separator
|
||||
// on Windows.
|
||||
|
||||
// RemoveDirectoryName("/afile") -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("afile", FilePath("/afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName("adir/") -> ""
|
||||
TEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("", FilePath("adir/").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName("adir/afile") -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("afile", FilePath("adir/afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
// RemoveDirectoryName("adir/subdir/afile") -> "afile"
|
||||
TEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {
|
||||
EXPECT_EQ("afile",
|
||||
FilePath("adir/subdir/afile").RemoveDirectoryName().string());
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// RemoveFileName "" -> "./"
|
||||
TEST(RemoveFileNameTest, EmptyName) {
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
// On Windows CE, we use the root as the current directory.
|
||||
EXPECT_EQ(GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
|
||||
#else
|
||||
EXPECT_EQ("." GTEST_PATH_SEP_, FilePath("").RemoveFileName().string());
|
||||
#endif
|
||||
}
|
||||
|
||||
// RemoveFileName "adir/" -> "adir/"
|
||||
TEST(RemoveFileNameTest, ButNoFile) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir" GTEST_PATH_SEP_).RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName "adir/afile" -> "adir/"
|
||||
TEST(RemoveFileNameTest, GivesDirName) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir" GTEST_PATH_SEP_ "afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName "adir/subdir/afile" -> "adir/subdir/"
|
||||
TEST(RemoveFileNameTest, GivesDirAndSubDirName) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
|
||||
FilePath("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_ "afile")
|
||||
.RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName "/afile" -> "/"
|
||||
TEST(RemoveFileNameTest, GivesRootDir) {
|
||||
EXPECT_EQ(GTEST_PATH_SEP_,
|
||||
FilePath(GTEST_PATH_SEP_ "afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
|
||||
// Tests that RemoveFileName() works with the alternate separator on
|
||||
// Windows.
|
||||
|
||||
// RemoveFileName("adir/") -> "adir/"
|
||||
TEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir/").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName("adir/afile") -> "adir/"
|
||||
TEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_,
|
||||
FilePath("adir/afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName("adir/subdir/afile") -> "adir/subdir/"
|
||||
TEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) {
|
||||
EXPECT_EQ("adir" GTEST_PATH_SEP_ "subdir" GTEST_PATH_SEP_,
|
||||
FilePath("adir/subdir/afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
// RemoveFileName("/afile") -> "\"
|
||||
TEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {
|
||||
EXPECT_EQ(GTEST_PATH_SEP_, FilePath("/afile").RemoveFileName().string());
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
TEST(MakeFileNameTest, GenerateWhenNumberIsZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
|
||||
0, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo"), FilePath("bar"),
|
||||
12, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar"), 0, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar"), 12, "xml");
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar_12.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
|
||||
0, "xml");
|
||||
EXPECT_EQ("bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {
|
||||
FilePath actual = FilePath::MakeFileName(FilePath(""), FilePath("bar"),
|
||||
14, "xml");
|
||||
EXPECT_EQ("bar_14.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
|
||||
FilePath("bar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path1BeingEmpty) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath(""),
|
||||
FilePath("bar.xml"));
|
||||
EXPECT_EQ("bar.xml", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path2BeingEmpty) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo"), FilePath(""));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_, actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, BothPathBeingEmpty) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath(""),
|
||||
FilePath(""));
|
||||
EXPECT_EQ("", actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path1ContainsPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo" GTEST_PATH_SEP_ "bar"),
|
||||
FilePath("foobar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "foobar.xml",
|
||||
actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path2ContainsPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(
|
||||
FilePath("foo" GTEST_PATH_SEP_),
|
||||
FilePath("bar" GTEST_PATH_SEP_ "bar.xml"));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_ "bar.xml",
|
||||
actual.string());
|
||||
}
|
||||
|
||||
TEST(ConcatPathsTest, Path2EndsWithPathSep) {
|
||||
FilePath actual = FilePath::ConcatPaths(FilePath("foo"),
|
||||
FilePath("bar" GTEST_PATH_SEP_));
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_, actual.string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "" -> ""
|
||||
TEST(RemoveTrailingPathSeparatorTest, EmptyString) {
|
||||
EXPECT_EQ("", FilePath("").RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo" -> "foo"
|
||||
TEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {
|
||||
EXPECT_EQ("foo", FilePath("foo").RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo/" -> "foo"
|
||||
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {
|
||||
EXPECT_EQ("foo",
|
||||
FilePath("foo" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
EXPECT_EQ("foo", FilePath("foo/").RemoveTrailingPathSeparator().string());
|
||||
#endif
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo/bar/" -> "foo/bar/"
|
||||
TEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ "bar" GTEST_PATH_SEP_)
|
||||
.RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
// RemoveTrailingPathSeparator "foo/bar" -> "foo/bar"
|
||||
TEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ "bar")
|
||||
.RemoveTrailingPathSeparator().string());
|
||||
}
|
||||
|
||||
TEST(DirectoryTest, RootDirectoryExists) {
|
||||
#if GTEST_OS_WINDOWS // We are on Windows.
|
||||
char current_drive[_MAX_PATH]; // NOLINT
|
||||
current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);
|
||||
current_drive[1] = ':';
|
||||
current_drive[2] = '\\';
|
||||
current_drive[3] = '\0';
|
||||
EXPECT_TRUE(FilePath(current_drive).DirectoryExists());
|
||||
#else
|
||||
EXPECT_TRUE(FilePath("/").DirectoryExists());
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
}
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
TEST(DirectoryTest, RootOfWrongDriveDoesNotExists) {
|
||||
const int saved_drive_ = _getdrive();
|
||||
// Find a drive that doesn't exist. Start with 'Z' to avoid common ones.
|
||||
for (char drive = 'Z'; drive >= 'A'; drive--)
|
||||
if (_chdrive(drive - 'A' + 1) == -1) {
|
||||
char non_drive[_MAX_PATH]; // NOLINT
|
||||
non_drive[0] = drive;
|
||||
non_drive[1] = ':';
|
||||
non_drive[2] = '\\';
|
||||
non_drive[3] = '\0';
|
||||
EXPECT_FALSE(FilePath(non_drive).DirectoryExists());
|
||||
break;
|
||||
}
|
||||
_chdrive(saved_drive_);
|
||||
}
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
#if !GTEST_OS_WINDOWS_MOBILE
|
||||
// Windows CE _does_ consider an empty directory to exist.
|
||||
TEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {
|
||||
EXPECT_FALSE(FilePath("").DirectoryExists());
|
||||
}
|
||||
#endif // !GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
TEST(DirectoryTest, CurrentDirectoryExists) {
|
||||
#if GTEST_OS_WINDOWS // We are on Windows.
|
||||
# ifndef _WIN32_CE // Windows CE doesn't have a current directory.
|
||||
|
||||
EXPECT_TRUE(FilePath(".").DirectoryExists());
|
||||
EXPECT_TRUE(FilePath(".\\").DirectoryExists());
|
||||
|
||||
# endif // _WIN32_CE
|
||||
#else
|
||||
EXPECT_TRUE(FilePath(".").DirectoryExists());
|
||||
EXPECT_TRUE(FilePath("./").DirectoryExists());
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
}
|
||||
|
||||
// "foo/bar" == foo//bar" == "foo///bar"
|
||||
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsInMidstring) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_ "bar",
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_
|
||||
GTEST_PATH_SEP_ "bar").string());
|
||||
}
|
||||
|
||||
// "/bar" == //bar" == "///bar"
|
||||
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringStart) {
|
||||
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
|
||||
FilePath(GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
|
||||
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
|
||||
EXPECT_EQ(GTEST_PATH_SEP_ "bar",
|
||||
FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ "bar").string());
|
||||
}
|
||||
|
||||
// "foo/" == foo//" == "foo///"
|
||||
TEST(NormalizeTest, MultipleConsecutiveSepaparatorsAtStringEnd) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_).string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());
|
||||
}
|
||||
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
|
||||
// Tests that separators at the end of the string are normalized
|
||||
// regardless of their combination (e.g. "foo\" =="foo/\" ==
|
||||
// "foo\\/").
|
||||
TEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo/").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo" GTEST_PATH_SEP_ "/").string());
|
||||
EXPECT_EQ("foo" GTEST_PATH_SEP_,
|
||||
FilePath("foo//" GTEST_PATH_SEP_).string());
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
TEST(AssignmentOperatorTest, DefaultAssignedToNonDefault) {
|
||||
FilePath default_path;
|
||||
FilePath non_default_path("path");
|
||||
non_default_path = default_path;
|
||||
EXPECT_EQ("", non_default_path.string());
|
||||
EXPECT_EQ("", default_path.string()); // RHS var is unchanged.
|
||||
}
|
||||
|
||||
TEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) {
|
||||
FilePath non_default_path("path");
|
||||
FilePath default_path;
|
||||
default_path = non_default_path;
|
||||
EXPECT_EQ("path", default_path.string());
|
||||
EXPECT_EQ("path", non_default_path.string()); // RHS var is unchanged.
|
||||
}
|
||||
|
||||
TEST(AssignmentOperatorTest, ConstAssignedToNonConst) {
|
||||
const FilePath const_default_path("const_path");
|
||||
FilePath non_default_path("path");
|
||||
non_default_path = const_default_path;
|
||||
EXPECT_EQ("const_path", non_default_path.string());
|
||||
}
|
||||
|
||||
class DirectoryCreationTest : public Test {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
testdata_path_.Set(FilePath(
|
||||
TempDir() + GetCurrentExecutableName().string() +
|
||||
"_directory_creation" GTEST_PATH_SEP_ "test" GTEST_PATH_SEP_));
|
||||
testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());
|
||||
|
||||
unique_file0_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
|
||||
0, "txt"));
|
||||
unique_file1_.Set(FilePath::MakeFileName(testdata_path_, FilePath("unique"),
|
||||
1, "txt"));
|
||||
|
||||
remove(testdata_file_.c_str());
|
||||
remove(unique_file0_.c_str());
|
||||
remove(unique_file1_.c_str());
|
||||
posix::RmDir(testdata_path_.c_str());
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
remove(testdata_file_.c_str());
|
||||
remove(unique_file0_.c_str());
|
||||
remove(unique_file1_.c_str());
|
||||
posix::RmDir(testdata_path_.c_str());
|
||||
}
|
||||
|
||||
void CreateTextFile(const char* filename) {
|
||||
FILE* f = posix::FOpen(filename, "w");
|
||||
fprintf(f, "text\n");
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
// Strings representing a directory and a file, with identical paths
|
||||
// except for the trailing separator character that distinquishes
|
||||
// a directory named 'test' from a file named 'test'. Example names:
|
||||
FilePath testdata_path_; // "/tmp/directory_creation/test/"
|
||||
FilePath testdata_file_; // "/tmp/directory_creation/test"
|
||||
FilePath unique_file0_; // "/tmp/directory_creation/test/unique.txt"
|
||||
FilePath unique_file1_; // "/tmp/directory_creation/test/unique_1.txt"
|
||||
};
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {
|
||||
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
|
||||
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
|
||||
EXPECT_TRUE(testdata_path_.DirectoryExists());
|
||||
}
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {
|
||||
EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();
|
||||
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
|
||||
// Call 'create' again... should still succeed.
|
||||
EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());
|
||||
}
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {
|
||||
FilePath file_path(FilePath::GenerateUniqueFileName(testdata_path_,
|
||||
FilePath("unique"), "txt"));
|
||||
EXPECT_EQ(unique_file0_.string(), file_path.string());
|
||||
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file not there
|
||||
|
||||
testdata_path_.CreateDirectoriesRecursively();
|
||||
EXPECT_FALSE(file_path.FileOrDirectoryExists()); // file still not there
|
||||
CreateTextFile(file_path.c_str());
|
||||
EXPECT_TRUE(file_path.FileOrDirectoryExists());
|
||||
|
||||
FilePath file_path2(FilePath::GenerateUniqueFileName(testdata_path_,
|
||||
FilePath("unique"), "txt"));
|
||||
EXPECT_EQ(unique_file1_.string(), file_path2.string());
|
||||
EXPECT_FALSE(file_path2.FileOrDirectoryExists()); // file not there
|
||||
CreateTextFile(file_path2.c_str());
|
||||
EXPECT_TRUE(file_path2.FileOrDirectoryExists());
|
||||
}
|
||||
|
||||
TEST_F(DirectoryCreationTest, CreateDirectoriesFail) {
|
||||
// force a failure by putting a file where we will try to create a directory.
|
||||
CreateTextFile(testdata_file_.c_str());
|
||||
EXPECT_TRUE(testdata_file_.FileOrDirectoryExists());
|
||||
EXPECT_FALSE(testdata_file_.DirectoryExists());
|
||||
EXPECT_FALSE(testdata_file_.CreateDirectoriesRecursively());
|
||||
}
|
||||
|
||||
TEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) {
|
||||
const FilePath test_detail_xml("test_detail.xml");
|
||||
EXPECT_FALSE(test_detail_xml.CreateDirectoriesRecursively());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, DefaultConstructor) {
|
||||
FilePath fp;
|
||||
EXPECT_EQ("", fp.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, CharAndCopyConstructors) {
|
||||
const FilePath fp("spicy");
|
||||
EXPECT_EQ("spicy", fp.string());
|
||||
|
||||
const FilePath fp_copy(fp);
|
||||
EXPECT_EQ("spicy", fp_copy.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, StringConstructor) {
|
||||
const FilePath fp(std::string("cider"));
|
||||
EXPECT_EQ("cider", fp.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, Set) {
|
||||
const FilePath apple("apple");
|
||||
FilePath mac("mac");
|
||||
mac.Set(apple); // Implement Set() since overloading operator= is forbidden.
|
||||
EXPECT_EQ("apple", mac.string());
|
||||
EXPECT_EQ("apple", apple.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, ToString) {
|
||||
const FilePath file("drink");
|
||||
EXPECT_EQ("drink", file.string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, RemoveExtension) {
|
||||
EXPECT_EQ("app", FilePath("app.cc").RemoveExtension("cc").string());
|
||||
EXPECT_EQ("app", FilePath("app.exe").RemoveExtension("exe").string());
|
||||
EXPECT_EQ("APP", FilePath("APP.EXE").RemoveExtension("exe").string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) {
|
||||
EXPECT_EQ("app", FilePath("app").RemoveExtension("exe").string());
|
||||
}
|
||||
|
||||
TEST(FilePathTest, IsDirectory) {
|
||||
EXPECT_FALSE(FilePath("cola").IsDirectory());
|
||||
EXPECT_TRUE(FilePath("koala" GTEST_PATH_SEP_).IsDirectory());
|
||||
#if GTEST_HAS_ALT_PATH_SEP_
|
||||
EXPECT_TRUE(FilePath("koala/").IsDirectory());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(FilePathTest, IsAbsolutePath) {
|
||||
EXPECT_FALSE(FilePath("is" GTEST_PATH_SEP_ "relative").IsAbsolutePath());
|
||||
EXPECT_FALSE(FilePath("").IsAbsolutePath());
|
||||
#if GTEST_OS_WINDOWS
|
||||
EXPECT_TRUE(FilePath("c:\\" GTEST_PATH_SEP_ "is_not"
|
||||
GTEST_PATH_SEP_ "relative").IsAbsolutePath());
|
||||
EXPECT_FALSE(FilePath("c:foo" GTEST_PATH_SEP_ "bar").IsAbsolutePath());
|
||||
EXPECT_TRUE(FilePath("c:/" GTEST_PATH_SEP_ "is_not"
|
||||
GTEST_PATH_SEP_ "relative").IsAbsolutePath());
|
||||
#else
|
||||
EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ "is_not" GTEST_PATH_SEP_ "relative")
|
||||
.IsAbsolutePath());
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
}
|
||||
|
||||
TEST(FilePathTest, IsRootDirectory) {
|
||||
#if GTEST_OS_WINDOWS
|
||||
EXPECT_TRUE(FilePath("a:\\").IsRootDirectory());
|
||||
EXPECT_TRUE(FilePath("Z:/").IsRootDirectory());
|
||||
EXPECT_TRUE(FilePath("e://").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("b:").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("b:a").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("8:/").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("c|/").IsRootDirectory());
|
||||
#else
|
||||
EXPECT_TRUE(FilePath("/").IsRootDirectory());
|
||||
EXPECT_TRUE(FilePath("//").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("\\").IsRootDirectory());
|
||||
EXPECT_FALSE(FilePath("/x").IsRootDirectory());
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
|
@ -1,154 +0,0 @@
|
|||
// Copyright 2003, 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.
|
||||
//
|
||||
// Authors: Dan Egnor (egnor@google.com)
|
||||
// Ported to Windows: Vadim Berman (vadimb@google.com)
|
||||
|
||||
#include "gtest/internal/gtest-linked_ptr.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using testing::Message;
|
||||
using testing::internal::linked_ptr;
|
||||
|
||||
int num;
|
||||
Message* history = NULL;
|
||||
|
||||
// Class which tracks allocation/deallocation
|
||||
class A {
|
||||
public:
|
||||
A(): mynum(num++) { *history << "A" << mynum << " ctor\n"; }
|
||||
virtual ~A() { *history << "A" << mynum << " dtor\n"; }
|
||||
virtual void Use() { *history << "A" << mynum << " use\n"; }
|
||||
protected:
|
||||
int mynum;
|
||||
};
|
||||
|
||||
// Subclass
|
||||
class B : public A {
|
||||
public:
|
||||
B() { *history << "B" << mynum << " ctor\n"; }
|
||||
~B() { *history << "B" << mynum << " dtor\n"; }
|
||||
virtual void Use() { *history << "B" << mynum << " use\n"; }
|
||||
};
|
||||
|
||||
class LinkedPtrTest : public testing::Test {
|
||||
public:
|
||||
LinkedPtrTest() {
|
||||
num = 0;
|
||||
history = new Message;
|
||||
}
|
||||
|
||||
virtual ~LinkedPtrTest() {
|
||||
delete history;
|
||||
history = NULL;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LinkedPtrTest, GeneralTest) {
|
||||
{
|
||||
linked_ptr<A> a0, a1, a2;
|
||||
// Use explicit function call notation here to suppress self-assign warning.
|
||||
a0.operator=(a0);
|
||||
a1 = a2;
|
||||
ASSERT_EQ(a0.get(), static_cast<A*>(NULL));
|
||||
ASSERT_EQ(a1.get(), static_cast<A*>(NULL));
|
||||
ASSERT_EQ(a2.get(), static_cast<A*>(NULL));
|
||||
ASSERT_TRUE(a0 == NULL);
|
||||
ASSERT_TRUE(a1 == NULL);
|
||||
ASSERT_TRUE(a2 == NULL);
|
||||
|
||||
{
|
||||
linked_ptr<A> a3(new A);
|
||||
a0 = a3;
|
||||
ASSERT_TRUE(a0 == a3);
|
||||
ASSERT_TRUE(a0 != NULL);
|
||||
ASSERT_TRUE(a0.get() == a3);
|
||||
ASSERT_TRUE(a0 == a3.get());
|
||||
linked_ptr<A> a4(a0);
|
||||
a1 = a4;
|
||||
linked_ptr<A> a5(new A);
|
||||
ASSERT_TRUE(a5.get() != a3);
|
||||
ASSERT_TRUE(a5 != a3.get());
|
||||
a2 = a5;
|
||||
linked_ptr<B> b0(new B);
|
||||
linked_ptr<A> a6(b0);
|
||||
ASSERT_TRUE(b0 == a6);
|
||||
ASSERT_TRUE(a6 == b0);
|
||||
ASSERT_TRUE(b0 != NULL);
|
||||
a5 = b0;
|
||||
a5 = b0;
|
||||
a3->Use();
|
||||
a4->Use();
|
||||
a5->Use();
|
||||
a6->Use();
|
||||
b0->Use();
|
||||
(*b0).Use();
|
||||
b0.get()->Use();
|
||||
}
|
||||
|
||||
a0->Use();
|
||||
a1->Use();
|
||||
a2->Use();
|
||||
|
||||
a1 = a2;
|
||||
a2.reset(new A);
|
||||
a0.reset();
|
||||
|
||||
linked_ptr<A> a7;
|
||||
}
|
||||
|
||||
ASSERT_STREQ(
|
||||
"A0 ctor\n"
|
||||
"A1 ctor\n"
|
||||
"A2 ctor\n"
|
||||
"B2 ctor\n"
|
||||
"A0 use\n"
|
||||
"A0 use\n"
|
||||
"B2 use\n"
|
||||
"B2 use\n"
|
||||
"B2 use\n"
|
||||
"B2 use\n"
|
||||
"B2 use\n"
|
||||
"B2 dtor\n"
|
||||
"A2 dtor\n"
|
||||
"A0 use\n"
|
||||
"A0 use\n"
|
||||
"A1 use\n"
|
||||
"A3 ctor\n"
|
||||
"A0 dtor\n"
|
||||
"A3 dtor\n"
|
||||
"A1 dtor\n",
|
||||
history->GetString().c_str());
|
||||
}
|
||||
|
||||
} // Unnamed namespace
|
||||
|
|
@ -1,311 +0,0 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This file verifies Google Test event listeners receive events at the
|
||||
// right times.
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include <vector>
|
||||
|
||||
using ::testing::AddGlobalTestEnvironment;
|
||||
using ::testing::Environment;
|
||||
using ::testing::InitGoogleTest;
|
||||
using ::testing::Test;
|
||||
using ::testing::TestCase;
|
||||
using ::testing::TestEventListener;
|
||||
using ::testing::TestInfo;
|
||||
using ::testing::TestPartResult;
|
||||
using ::testing::UnitTest;
|
||||
|
||||
// Used by tests to register their events.
|
||||
std::vector<std::string>* g_events = NULL;
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
class EventRecordingListener : public TestEventListener {
|
||||
public:
|
||||
explicit EventRecordingListener(const char* name) : name_(name) {}
|
||||
|
||||
protected:
|
||||
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {
|
||||
g_events->push_back(GetFullMethodName("OnTestProgramStart"));
|
||||
}
|
||||
|
||||
virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
|
||||
int iteration) {
|
||||
Message message;
|
||||
message << GetFullMethodName("OnTestIterationStart")
|
||||
<< "(" << iteration << ")";
|
||||
g_events->push_back(message.GetString());
|
||||
}
|
||||
|
||||
virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {
|
||||
g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpStart"));
|
||||
}
|
||||
|
||||
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {
|
||||
g_events->push_back(GetFullMethodName("OnEnvironmentsSetUpEnd"));
|
||||
}
|
||||
|
||||
virtual void OnTestCaseStart(const TestCase& /*test_case*/) {
|
||||
g_events->push_back(GetFullMethodName("OnTestCaseStart"));
|
||||
}
|
||||
|
||||
virtual void OnTestStart(const TestInfo& /*test_info*/) {
|
||||
g_events->push_back(GetFullMethodName("OnTestStart"));
|
||||
}
|
||||
|
||||
virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {
|
||||
g_events->push_back(GetFullMethodName("OnTestPartResult"));
|
||||
}
|
||||
|
||||
virtual void OnTestEnd(const TestInfo& /*test_info*/) {
|
||||
g_events->push_back(GetFullMethodName("OnTestEnd"));
|
||||
}
|
||||
|
||||
virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {
|
||||
g_events->push_back(GetFullMethodName("OnTestCaseEnd"));
|
||||
}
|
||||
|
||||
virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {
|
||||
g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownStart"));
|
||||
}
|
||||
|
||||
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {
|
||||
g_events->push_back(GetFullMethodName("OnEnvironmentsTearDownEnd"));
|
||||
}
|
||||
|
||||
virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
|
||||
int iteration) {
|
||||
Message message;
|
||||
message << GetFullMethodName("OnTestIterationEnd")
|
||||
<< "(" << iteration << ")";
|
||||
g_events->push_back(message.GetString());
|
||||
}
|
||||
|
||||
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {
|
||||
g_events->push_back(GetFullMethodName("OnTestProgramEnd"));
|
||||
}
|
||||
|
||||
private:
|
||||
std::string GetFullMethodName(const char* name) {
|
||||
return name_ + "." + name;
|
||||
}
|
||||
|
||||
std::string name_;
|
||||
};
|
||||
|
||||
class EnvironmentInvocationCatcher : public Environment {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
g_events->push_back("Environment::SetUp");
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
g_events->push_back("Environment::TearDown");
|
||||
}
|
||||
};
|
||||
|
||||
class ListenerTest : public Test {
|
||||
protected:
|
||||
static void SetUpTestCase() {
|
||||
g_events->push_back("ListenerTest::SetUpTestCase");
|
||||
}
|
||||
|
||||
static void TearDownTestCase() {
|
||||
g_events->push_back("ListenerTest::TearDownTestCase");
|
||||
}
|
||||
|
||||
virtual void SetUp() {
|
||||
g_events->push_back("ListenerTest::SetUp");
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
g_events->push_back("ListenerTest::TearDown");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(ListenerTest, DoesFoo) {
|
||||
// Test execution order within a test case is not guaranteed so we are not
|
||||
// recording the test name.
|
||||
g_events->push_back("ListenerTest::* Test Body");
|
||||
SUCCEED(); // Triggers OnTestPartResult.
|
||||
}
|
||||
|
||||
TEST_F(ListenerTest, DoesBar) {
|
||||
g_events->push_back("ListenerTest::* Test Body");
|
||||
SUCCEED(); // Triggers OnTestPartResult.
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace testing
|
||||
|
||||
using ::testing::internal::EnvironmentInvocationCatcher;
|
||||
using ::testing::internal::EventRecordingListener;
|
||||
|
||||
void VerifyResults(const std::vector<std::string>& data,
|
||||
const char* const* expected_data,
|
||||
size_t expected_data_size) {
|
||||
const size_t actual_size = data.size();
|
||||
// If the following assertion fails, a new entry will be appended to
|
||||
// data. Hence we save data.size() first.
|
||||
EXPECT_EQ(expected_data_size, actual_size);
|
||||
|
||||
// Compares the common prefix.
|
||||
const size_t shorter_size = expected_data_size <= actual_size ?
|
||||
expected_data_size : actual_size;
|
||||
size_t i = 0;
|
||||
for (; i < shorter_size; ++i) {
|
||||
ASSERT_STREQ(expected_data[i], data[i].c_str())
|
||||
<< "at position " << i;
|
||||
}
|
||||
|
||||
// Prints extra elements in the actual data.
|
||||
for (; i < actual_size; ++i) {
|
||||
printf(" Actual event #%lu: %s\n",
|
||||
static_cast<unsigned long>(i), data[i].c_str());
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
std::vector<std::string> events;
|
||||
g_events = &events;
|
||||
InitGoogleTest(&argc, argv);
|
||||
|
||||
UnitTest::GetInstance()->listeners().Append(
|
||||
new EventRecordingListener("1st"));
|
||||
UnitTest::GetInstance()->listeners().Append(
|
||||
new EventRecordingListener("2nd"));
|
||||
|
||||
AddGlobalTestEnvironment(new EnvironmentInvocationCatcher);
|
||||
|
||||
GTEST_CHECK_(events.size() == 0)
|
||||
<< "AddGlobalTestEnvironment should not generate any events itself.";
|
||||
|
||||
::testing::GTEST_FLAG(repeat) = 2;
|
||||
int ret_val = RUN_ALL_TESTS();
|
||||
|
||||
const char* const expected_events[] = {
|
||||
"1st.OnTestProgramStart",
|
||||
"2nd.OnTestProgramStart",
|
||||
"1st.OnTestIterationStart(0)",
|
||||
"2nd.OnTestIterationStart(0)",
|
||||
"1st.OnEnvironmentsSetUpStart",
|
||||
"2nd.OnEnvironmentsSetUpStart",
|
||||
"Environment::SetUp",
|
||||
"2nd.OnEnvironmentsSetUpEnd",
|
||||
"1st.OnEnvironmentsSetUpEnd",
|
||||
"1st.OnTestCaseStart",
|
||||
"2nd.OnTestCaseStart",
|
||||
"ListenerTest::SetUpTestCase",
|
||||
"1st.OnTestStart",
|
||||
"2nd.OnTestStart",
|
||||
"ListenerTest::SetUp",
|
||||
"ListenerTest::* Test Body",
|
||||
"1st.OnTestPartResult",
|
||||
"2nd.OnTestPartResult",
|
||||
"ListenerTest::TearDown",
|
||||
"2nd.OnTestEnd",
|
||||
"1st.OnTestEnd",
|
||||
"1st.OnTestStart",
|
||||
"2nd.OnTestStart",
|
||||
"ListenerTest::SetUp",
|
||||
"ListenerTest::* Test Body",
|
||||
"1st.OnTestPartResult",
|
||||
"2nd.OnTestPartResult",
|
||||
"ListenerTest::TearDown",
|
||||
"2nd.OnTestEnd",
|
||||
"1st.OnTestEnd",
|
||||
"ListenerTest::TearDownTestCase",
|
||||
"2nd.OnTestCaseEnd",
|
||||
"1st.OnTestCaseEnd",
|
||||
"1st.OnEnvironmentsTearDownStart",
|
||||
"2nd.OnEnvironmentsTearDownStart",
|
||||
"Environment::TearDown",
|
||||
"2nd.OnEnvironmentsTearDownEnd",
|
||||
"1st.OnEnvironmentsTearDownEnd",
|
||||
"2nd.OnTestIterationEnd(0)",
|
||||
"1st.OnTestIterationEnd(0)",
|
||||
"1st.OnTestIterationStart(1)",
|
||||
"2nd.OnTestIterationStart(1)",
|
||||
"1st.OnEnvironmentsSetUpStart",
|
||||
"2nd.OnEnvironmentsSetUpStart",
|
||||
"Environment::SetUp",
|
||||
"2nd.OnEnvironmentsSetUpEnd",
|
||||
"1st.OnEnvironmentsSetUpEnd",
|
||||
"1st.OnTestCaseStart",
|
||||
"2nd.OnTestCaseStart",
|
||||
"ListenerTest::SetUpTestCase",
|
||||
"1st.OnTestStart",
|
||||
"2nd.OnTestStart",
|
||||
"ListenerTest::SetUp",
|
||||
"ListenerTest::* Test Body",
|
||||
"1st.OnTestPartResult",
|
||||
"2nd.OnTestPartResult",
|
||||
"ListenerTest::TearDown",
|
||||
"2nd.OnTestEnd",
|
||||
"1st.OnTestEnd",
|
||||
"1st.OnTestStart",
|
||||
"2nd.OnTestStart",
|
||||
"ListenerTest::SetUp",
|
||||
"ListenerTest::* Test Body",
|
||||
"1st.OnTestPartResult",
|
||||
"2nd.OnTestPartResult",
|
||||
"ListenerTest::TearDown",
|
||||
"2nd.OnTestEnd",
|
||||
"1st.OnTestEnd",
|
||||
"ListenerTest::TearDownTestCase",
|
||||
"2nd.OnTestCaseEnd",
|
||||
"1st.OnTestCaseEnd",
|
||||
"1st.OnEnvironmentsTearDownStart",
|
||||
"2nd.OnEnvironmentsTearDownStart",
|
||||
"Environment::TearDown",
|
||||
"2nd.OnEnvironmentsTearDownEnd",
|
||||
"1st.OnEnvironmentsTearDownEnd",
|
||||
"2nd.OnTestIterationEnd(1)",
|
||||
"1st.OnTestIterationEnd(1)",
|
||||
"2nd.OnTestProgramEnd",
|
||||
"1st.OnTestProgramEnd"
|
||||
};
|
||||
VerifyResults(events,
|
||||
expected_events,
|
||||
sizeof(expected_events)/sizeof(expected_events[0]));
|
||||
|
||||
// We need to check manually for ad hoc test failures that happen after
|
||||
// RUN_ALL_TESTS finishes.
|
||||
if (UnitTest::GetInstance()->Failed())
|
||||
ret_val = 1;
|
||||
|
||||
return ret_val;
|
||||
}
|
||||
|
|
@ -1,159 +0,0 @@
|
|||
// Copyright 2005, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
// Tests for the Message class.
|
||||
|
||||
#include "gtest/gtest-message.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using ::testing::Message;
|
||||
|
||||
// Tests the testing::Message class
|
||||
|
||||
// Tests the default constructor.
|
||||
TEST(MessageTest, DefaultConstructor) {
|
||||
const Message msg;
|
||||
EXPECT_EQ("", msg.GetString());
|
||||
}
|
||||
|
||||
// Tests the copy constructor.
|
||||
TEST(MessageTest, CopyConstructor) {
|
||||
const Message msg1("Hello");
|
||||
const Message msg2(msg1);
|
||||
EXPECT_EQ("Hello", msg2.GetString());
|
||||
}
|
||||
|
||||
// Tests constructing a Message from a C-string.
|
||||
TEST(MessageTest, ConstructsFromCString) {
|
||||
Message msg("Hello");
|
||||
EXPECT_EQ("Hello", msg.GetString());
|
||||
}
|
||||
|
||||
// Tests streaming a float.
|
||||
TEST(MessageTest, StreamsFloat) {
|
||||
const std::string s = (Message() << 1.23456F << " " << 2.34567F).GetString();
|
||||
// Both numbers should be printed with enough precision.
|
||||
EXPECT_PRED_FORMAT2(testing::IsSubstring, "1.234560", s.c_str());
|
||||
EXPECT_PRED_FORMAT2(testing::IsSubstring, " 2.345669", s.c_str());
|
||||
}
|
||||
|
||||
// Tests streaming a double.
|
||||
TEST(MessageTest, StreamsDouble) {
|
||||
const std::string s = (Message() << 1260570880.4555497 << " "
|
||||
<< 1260572265.1954534).GetString();
|
||||
// Both numbers should be printed with enough precision.
|
||||
EXPECT_PRED_FORMAT2(testing::IsSubstring, "1260570880.45", s.c_str());
|
||||
EXPECT_PRED_FORMAT2(testing::IsSubstring, " 1260572265.19", s.c_str());
|
||||
}
|
||||
|
||||
// Tests streaming a non-char pointer.
|
||||
TEST(MessageTest, StreamsPointer) {
|
||||
int n = 0;
|
||||
int* p = &n;
|
||||
EXPECT_NE("(null)", (Message() << p).GetString());
|
||||
}
|
||||
|
||||
// Tests streaming a NULL non-char pointer.
|
||||
TEST(MessageTest, StreamsNullPointer) {
|
||||
int* p = NULL;
|
||||
EXPECT_EQ("(null)", (Message() << p).GetString());
|
||||
}
|
||||
|
||||
// Tests streaming a C string.
|
||||
TEST(MessageTest, StreamsCString) {
|
||||
EXPECT_EQ("Foo", (Message() << "Foo").GetString());
|
||||
}
|
||||
|
||||
// Tests streaming a NULL C string.
|
||||
TEST(MessageTest, StreamsNullCString) {
|
||||
char* p = NULL;
|
||||
EXPECT_EQ("(null)", (Message() << p).GetString());
|
||||
}
|
||||
|
||||
// Tests streaming std::string.
|
||||
TEST(MessageTest, StreamsString) {
|
||||
const ::std::string str("Hello");
|
||||
EXPECT_EQ("Hello", (Message() << str).GetString());
|
||||
}
|
||||
|
||||
// Tests that we can output strings containing embedded NULs.
|
||||
TEST(MessageTest, StreamsStringWithEmbeddedNUL) {
|
||||
const char char_array_with_nul[] =
|
||||
"Here's a NUL\0 and some more string";
|
||||
const ::std::string string_with_nul(char_array_with_nul,
|
||||
sizeof(char_array_with_nul) - 1);
|
||||
EXPECT_EQ("Here's a NUL\\0 and some more string",
|
||||
(Message() << string_with_nul).GetString());
|
||||
}
|
||||
|
||||
// Tests streaming a NUL char.
|
||||
TEST(MessageTest, StreamsNULChar) {
|
||||
EXPECT_EQ("\\0", (Message() << '\0').GetString());
|
||||
}
|
||||
|
||||
// Tests streaming int.
|
||||
TEST(MessageTest, StreamsInt) {
|
||||
EXPECT_EQ("123", (Message() << 123).GetString());
|
||||
}
|
||||
|
||||
// Tests that basic IO manipulators (endl, ends, and flush) can be
|
||||
// streamed to Message.
|
||||
TEST(MessageTest, StreamsBasicIoManip) {
|
||||
EXPECT_EQ("Line 1.\nA NUL char \\0 in line 2.",
|
||||
(Message() << "Line 1." << std::endl
|
||||
<< "A NUL char " << std::ends << std::flush
|
||||
<< " in line 2.").GetString());
|
||||
}
|
||||
|
||||
// Tests Message::GetString()
|
||||
TEST(MessageTest, GetString) {
|
||||
Message msg;
|
||||
msg << 1 << " lamb";
|
||||
EXPECT_EQ("1 lamb", msg.GetString());
|
||||
}
|
||||
|
||||
// Tests streaming a Message object to an ostream.
|
||||
TEST(MessageTest, StreamsToOStream) {
|
||||
Message msg("Hello");
|
||||
::std::stringstream ss;
|
||||
ss << msg;
|
||||
EXPECT_EQ("Hello", testing::internal::StringStreamToString(&ss));
|
||||
}
|
||||
|
||||
// Tests that a Message object doesn't take up too much stack space.
|
||||
TEST(MessageTest, DoesNotTakeUpMuchStackSpace) {
|
||||
EXPECT_LE(sizeof(Message), 16U);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
|
@ -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.
|
||||
//
|
||||
// Authors: keith.ray@gmail.com (Keith Ray)
|
||||
//
|
||||
// Google Test UnitTestOptions tests
|
||||
//
|
||||
// This file tests classes and functions used internally by
|
||||
// Google Test. They are subject to change without notice.
|
||||
//
|
||||
// This file is #included from gtest.cc, to avoid changing build or
|
||||
// make-files on Windows and other platforms. Do not #include this file
|
||||
// anywhere else!
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
# include <windows.h>
|
||||
#elif GTEST_OS_WINDOWS
|
||||
# include <direct.h>
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
// Indicates that this translation unit is part of Google Test's
|
||||
// implementation. It must come before gtest-internal-inl.h is
|
||||
// included, or there will be a compiler error. This trick is to
|
||||
// prevent a user from accidentally including gtest-internal-inl.h in
|
||||
// his code.
|
||||
#define GTEST_IMPLEMENTATION_ 1
|
||||
#include "src/gtest-internal-inl.h"
|
||||
#undef GTEST_IMPLEMENTATION_
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
namespace {
|
||||
|
||||
// Turns the given relative path into an absolute path.
|
||||
FilePath GetAbsolutePathOf(const FilePath& relative_path) {
|
||||
return FilePath::ConcatPaths(FilePath::GetCurrentDir(), relative_path);
|
||||
}
|
||||
|
||||
// Testing UnitTestOptions::GetOutputFormat/GetOutputFile.
|
||||
|
||||
TEST(XmlOutputTest, GetOutputFormatDefault) {
|
||||
GTEST_FLAG(output) = "";
|
||||
EXPECT_STREQ("", UnitTestOptions::GetOutputFormat().c_str());
|
||||
}
|
||||
|
||||
TEST(XmlOutputTest, GetOutputFormat) {
|
||||
GTEST_FLAG(output) = "xml:filename";
|
||||
EXPECT_STREQ("xml", UnitTestOptions::GetOutputFormat().c_str());
|
||||
}
|
||||
|
||||
TEST(XmlOutputTest, GetOutputFileDefault) {
|
||||
GTEST_FLAG(output) = "";
|
||||
EXPECT_EQ(GetAbsolutePathOf(FilePath("test_detail.xml")).string(),
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile());
|
||||
}
|
||||
|
||||
TEST(XmlOutputTest, GetOutputFileSingleFile) {
|
||||
GTEST_FLAG(output) = "xml:filename.abc";
|
||||
EXPECT_EQ(GetAbsolutePathOf(FilePath("filename.abc")).string(),
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile());
|
||||
}
|
||||
|
||||
TEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {
|
||||
GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_;
|
||||
const std::string expected_output_file =
|
||||
GetAbsolutePathOf(
|
||||
FilePath(std::string("path") + GTEST_PATH_SEP_ +
|
||||
GetCurrentExecutableName().string() + ".xml")).string();
|
||||
const std::string& output_file =
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile();
|
||||
#if GTEST_OS_WINDOWS
|
||||
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
|
||||
#else
|
||||
EXPECT_EQ(expected_output_file, output_file.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST(OutputFileHelpersTest, GetCurrentExecutableName) {
|
||||
const std::string exe_str = GetCurrentExecutableName().string();
|
||||
#if GTEST_OS_WINDOWS
|
||||
const bool success =
|
||||
_strcmpi("gtest-options_test", exe_str.c_str()) == 0 ||
|
||||
_strcmpi("gtest-options-ex_test", exe_str.c_str()) == 0 ||
|
||||
_strcmpi("gtest_all_test", exe_str.c_str()) == 0 ||
|
||||
_strcmpi("gtest_dll_test", exe_str.c_str()) == 0;
|
||||
#else
|
||||
// TODO(wan@google.com): remove the hard-coded "lt-" prefix when
|
||||
// Chandler Carruth's libtool replacement is ready.
|
||||
const bool success =
|
||||
exe_str == "gtest-options_test" ||
|
||||
exe_str == "gtest_all_test" ||
|
||||
exe_str == "lt-gtest_all_test" ||
|
||||
exe_str == "gtest_dll_test";
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
if (!success)
|
||||
FAIL() << "GetCurrentExecutableName() returns " << exe_str;
|
||||
}
|
||||
|
||||
class XmlOutputChangeDirTest : public Test {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
original_working_dir_ = FilePath::GetCurrentDir();
|
||||
posix::ChDir("..");
|
||||
// This will make the test fail if run from the root directory.
|
||||
EXPECT_NE(original_working_dir_.string(),
|
||||
FilePath::GetCurrentDir().string());
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
posix::ChDir(original_working_dir_.string().c_str());
|
||||
}
|
||||
|
||||
FilePath original_working_dir_;
|
||||
};
|
||||
|
||||
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {
|
||||
GTEST_FLAG(output) = "";
|
||||
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
|
||||
FilePath("test_detail.xml")).string(),
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile());
|
||||
}
|
||||
|
||||
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {
|
||||
GTEST_FLAG(output) = "xml";
|
||||
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
|
||||
FilePath("test_detail.xml")).string(),
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile());
|
||||
}
|
||||
|
||||
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {
|
||||
GTEST_FLAG(output) = "xml:filename.abc";
|
||||
EXPECT_EQ(FilePath::ConcatPaths(original_working_dir_,
|
||||
FilePath("filename.abc")).string(),
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile());
|
||||
}
|
||||
|
||||
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {
|
||||
GTEST_FLAG(output) = "xml:path" GTEST_PATH_SEP_;
|
||||
const std::string expected_output_file =
|
||||
FilePath::ConcatPaths(
|
||||
original_working_dir_,
|
||||
FilePath(std::string("path") + GTEST_PATH_SEP_ +
|
||||
GetCurrentExecutableName().string() + ".xml")).string();
|
||||
const std::string& output_file =
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile();
|
||||
#if GTEST_OS_WINDOWS
|
||||
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
|
||||
#else
|
||||
EXPECT_EQ(expected_output_file, output_file.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {
|
||||
#if GTEST_OS_WINDOWS
|
||||
GTEST_FLAG(output) = "xml:c:\\tmp\\filename.abc";
|
||||
EXPECT_EQ(FilePath("c:\\tmp\\filename.abc").string(),
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile());
|
||||
#else
|
||||
GTEST_FLAG(output) ="xml:/tmp/filename.abc";
|
||||
EXPECT_EQ(FilePath("/tmp/filename.abc").string(),
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile());
|
||||
#endif
|
||||
}
|
||||
|
||||
TEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {
|
||||
#if GTEST_OS_WINDOWS
|
||||
const std::string path = "c:\\tmp\\";
|
||||
#else
|
||||
const std::string path = "/tmp/";
|
||||
#endif
|
||||
|
||||
GTEST_FLAG(output) = "xml:" + path;
|
||||
const std::string expected_output_file =
|
||||
path + GetCurrentExecutableName().string() + ".xml";
|
||||
const std::string& output_file =
|
||||
UnitTestOptions::GetAbsolutePathToOutputFile();
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());
|
||||
#else
|
||||
EXPECT_EQ(expected_output_file, output_file.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
|
@ -1,65 +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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// Tests for Google Test itself. This verifies that the basic constructs of
|
||||
// Google Test work.
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#include "test/gtest-param-test_test.h"
|
||||
|
||||
#if GTEST_HAS_PARAM_TEST
|
||||
|
||||
using ::testing::Values;
|
||||
using ::testing::internal::ParamGenerator;
|
||||
|
||||
// Tests that generators defined in a different translation unit
|
||||
// are functional. The test using extern_gen is defined
|
||||
// in gtest-param-test_test.cc.
|
||||
ParamGenerator<int> extern_gen = Values(33);
|
||||
|
||||
// Tests that a parameterized test case can be defined in one translation unit
|
||||
// and instantiated in another. The test is defined in gtest-param-test_test.cc
|
||||
// and ExternalInstantiationTest fixture class is defined in
|
||||
// gtest-param-test_test.h.
|
||||
INSTANTIATE_TEST_CASE_P(MultiplesOf33,
|
||||
ExternalInstantiationTest,
|
||||
Values(33, 66));
|
||||
|
||||
// Tests that a parameterized test case can be instantiated
|
||||
// in multiple translation units. Another instantiation is defined
|
||||
// in gtest-param-test_test.cc and InstantiationInMultipleTranslaionUnitsTest
|
||||
// fixture is defined in gtest-param-test_test.h
|
||||
INSTANTIATE_TEST_CASE_P(Sequence2,
|
||||
InstantiationInMultipleTranslaionUnitsTest,
|
||||
Values(42*3, 42*4, 42*5));
|
||||
|
||||
#endif // GTEST_HAS_PARAM_TEST
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,57 +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.
|
||||
//
|
||||
// Authors: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This header file provides classes and functions used internally
|
||||
// for testing Google Test itself.
|
||||
|
||||
#ifndef GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
#define GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_PARAM_TEST
|
||||
|
||||
// Test fixture for testing definition and instantiation of a test
|
||||
// in separate translation units.
|
||||
class ExternalInstantiationTest : public ::testing::TestWithParam<int> {
|
||||
};
|
||||
|
||||
// Test fixture for testing instantiation of a test in multiple
|
||||
// translation units.
|
||||
class InstantiationInMultipleTranslaionUnitsTest
|
||||
: public ::testing::TestWithParam<int> {
|
||||
};
|
||||
|
||||
#endif // GTEST_HAS_PARAM_TEST
|
||||
|
||||
#endif // GTEST_TEST_GTEST_PARAM_TEST_TEST_H_
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,208 +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.
|
||||
//
|
||||
// Author: mheule@google.com (Markus Heule)
|
||||
//
|
||||
|
||||
#include "gtest/gtest-test-part.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
using testing::Message;
|
||||
using testing::Test;
|
||||
using testing::TestPartResult;
|
||||
using testing::TestPartResultArray;
|
||||
|
||||
namespace {
|
||||
|
||||
// Tests the TestPartResult class.
|
||||
|
||||
// The test fixture for testing TestPartResult.
|
||||
class TestPartResultTest : public Test {
|
||||
protected:
|
||||
TestPartResultTest()
|
||||
: r1_(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"),
|
||||
r2_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure!"),
|
||||
r3_(TestPartResult::kFatalFailure, NULL, -1, "Failure!") {}
|
||||
|
||||
TestPartResult r1_, r2_, r3_;
|
||||
};
|
||||
|
||||
|
||||
TEST_F(TestPartResultTest, ConstructorWorks) {
|
||||
Message message;
|
||||
message << "something is terribly wrong";
|
||||
message << static_cast<const char*>(testing::internal::kStackTraceMarker);
|
||||
message << "some unimportant stack trace";
|
||||
|
||||
const TestPartResult result(TestPartResult::kNonFatalFailure,
|
||||
"some_file.cc",
|
||||
42,
|
||||
message.GetString().c_str());
|
||||
|
||||
EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type());
|
||||
EXPECT_STREQ("some_file.cc", result.file_name());
|
||||
EXPECT_EQ(42, result.line_number());
|
||||
EXPECT_STREQ(message.GetString().c_str(), result.message());
|
||||
EXPECT_STREQ("something is terribly wrong", result.summary());
|
||||
}
|
||||
|
||||
TEST_F(TestPartResultTest, ResultAccessorsWork) {
|
||||
const TestPartResult success(TestPartResult::kSuccess,
|
||||
"file.cc",
|
||||
42,
|
||||
"message");
|
||||
EXPECT_TRUE(success.passed());
|
||||
EXPECT_FALSE(success.failed());
|
||||
EXPECT_FALSE(success.nonfatally_failed());
|
||||
EXPECT_FALSE(success.fatally_failed());
|
||||
|
||||
const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure,
|
||||
"file.cc",
|
||||
42,
|
||||
"message");
|
||||
EXPECT_FALSE(nonfatal_failure.passed());
|
||||
EXPECT_TRUE(nonfatal_failure.failed());
|
||||
EXPECT_TRUE(nonfatal_failure.nonfatally_failed());
|
||||
EXPECT_FALSE(nonfatal_failure.fatally_failed());
|
||||
|
||||
const TestPartResult fatal_failure(TestPartResult::kFatalFailure,
|
||||
"file.cc",
|
||||
42,
|
||||
"message");
|
||||
EXPECT_FALSE(fatal_failure.passed());
|
||||
EXPECT_TRUE(fatal_failure.failed());
|
||||
EXPECT_FALSE(fatal_failure.nonfatally_failed());
|
||||
EXPECT_TRUE(fatal_failure.fatally_failed());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::type().
|
||||
TEST_F(TestPartResultTest, type) {
|
||||
EXPECT_EQ(TestPartResult::kSuccess, r1_.type());
|
||||
EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type());
|
||||
EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::file_name().
|
||||
TEST_F(TestPartResultTest, file_name) {
|
||||
EXPECT_STREQ("foo/bar.cc", r1_.file_name());
|
||||
EXPECT_STREQ(NULL, r3_.file_name());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::line_number().
|
||||
TEST_F(TestPartResultTest, line_number) {
|
||||
EXPECT_EQ(10, r1_.line_number());
|
||||
EXPECT_EQ(-1, r2_.line_number());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::message().
|
||||
TEST_F(TestPartResultTest, message) {
|
||||
EXPECT_STREQ("Success!", r1_.message());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::passed().
|
||||
TEST_F(TestPartResultTest, Passed) {
|
||||
EXPECT_TRUE(r1_.passed());
|
||||
EXPECT_FALSE(r2_.passed());
|
||||
EXPECT_FALSE(r3_.passed());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::failed().
|
||||
TEST_F(TestPartResultTest, Failed) {
|
||||
EXPECT_FALSE(r1_.failed());
|
||||
EXPECT_TRUE(r2_.failed());
|
||||
EXPECT_TRUE(r3_.failed());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::fatally_failed().
|
||||
TEST_F(TestPartResultTest, FatallyFailed) {
|
||||
EXPECT_FALSE(r1_.fatally_failed());
|
||||
EXPECT_FALSE(r2_.fatally_failed());
|
||||
EXPECT_TRUE(r3_.fatally_failed());
|
||||
}
|
||||
|
||||
// Tests TestPartResult::nonfatally_failed().
|
||||
TEST_F(TestPartResultTest, NonfatallyFailed) {
|
||||
EXPECT_FALSE(r1_.nonfatally_failed());
|
||||
EXPECT_TRUE(r2_.nonfatally_failed());
|
||||
EXPECT_FALSE(r3_.nonfatally_failed());
|
||||
}
|
||||
|
||||
// Tests the TestPartResultArray class.
|
||||
|
||||
class TestPartResultArrayTest : public Test {
|
||||
protected:
|
||||
TestPartResultArrayTest()
|
||||
: r1_(TestPartResult::kNonFatalFailure, "foo/bar.cc", -1, "Failure 1"),
|
||||
r2_(TestPartResult::kFatalFailure, "foo/bar.cc", -1, "Failure 2") {}
|
||||
|
||||
const TestPartResult r1_, r2_;
|
||||
};
|
||||
|
||||
// Tests that TestPartResultArray initially has size 0.
|
||||
TEST_F(TestPartResultArrayTest, InitialSizeIsZero) {
|
||||
TestPartResultArray results;
|
||||
EXPECT_EQ(0, results.size());
|
||||
}
|
||||
|
||||
// Tests that TestPartResultArray contains the given TestPartResult
|
||||
// after one Append() operation.
|
||||
TEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) {
|
||||
TestPartResultArray results;
|
||||
results.Append(r1_);
|
||||
EXPECT_EQ(1, results.size());
|
||||
EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message());
|
||||
}
|
||||
|
||||
// Tests that TestPartResultArray contains the given TestPartResults
|
||||
// after two Append() operations.
|
||||
TEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) {
|
||||
TestPartResultArray results;
|
||||
results.Append(r1_);
|
||||
results.Append(r2_);
|
||||
EXPECT_EQ(2, results.size());
|
||||
EXPECT_STREQ("Failure 1", results.GetTestPartResult(0).message());
|
||||
EXPECT_STREQ("Failure 2", results.GetTestPartResult(1).message());
|
||||
}
|
||||
|
||||
typedef TestPartResultArrayTest TestPartResultArrayDeathTest;
|
||||
|
||||
// Tests that the program dies when GetTestPartResult() is called with
|
||||
// an invalid index.
|
||||
TEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) {
|
||||
TestPartResultArray results;
|
||||
results.Append(r1_);
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(-1), "");
|
||||
EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), "");
|
||||
}
|
||||
|
||||
// TODO(mheule@google.com): Add a test for the class HasNewFatalFailureHelper.
|
||||
|
||||
} // namespace
|
||||
|
|
@ -1,320 +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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include "gtest/internal/gtest-tuple.h"
|
||||
#include <utility>
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using ::std::tr1::get;
|
||||
using ::std::tr1::make_tuple;
|
||||
using ::std::tr1::tuple;
|
||||
using ::std::tr1::tuple_element;
|
||||
using ::std::tr1::tuple_size;
|
||||
using ::testing::StaticAssertTypeEq;
|
||||
|
||||
// Tests that tuple_element<K, tuple<T0, T1, ..., TN> >::type returns TK.
|
||||
TEST(tuple_element_Test, ReturnsElementType) {
|
||||
StaticAssertTypeEq<int, tuple_element<0, tuple<int, char> >::type>();
|
||||
StaticAssertTypeEq<int&, tuple_element<1, tuple<double, int&> >::type>();
|
||||
StaticAssertTypeEq<bool, tuple_element<2, tuple<double, int, bool> >::type>();
|
||||
}
|
||||
|
||||
// Tests that tuple_size<T>::value gives the number of fields in tuple
|
||||
// type T.
|
||||
TEST(tuple_size_Test, ReturnsNumberOfFields) {
|
||||
EXPECT_EQ(0, +tuple_size<tuple<> >::value);
|
||||
EXPECT_EQ(1, +tuple_size<tuple<void*> >::value);
|
||||
EXPECT_EQ(1, +tuple_size<tuple<char> >::value);
|
||||
EXPECT_EQ(1, +(tuple_size<tuple<tuple<int, double> > >::value));
|
||||
EXPECT_EQ(2, +(tuple_size<tuple<int&, const char> >::value));
|
||||
EXPECT_EQ(3, +(tuple_size<tuple<char*, void, const bool&> >::value));
|
||||
}
|
||||
|
||||
// Tests comparing a tuple with itself.
|
||||
TEST(ComparisonTest, ComparesWithSelf) {
|
||||
const tuple<int, char, bool> a(5, 'a', false);
|
||||
|
||||
EXPECT_TRUE(a == a);
|
||||
EXPECT_FALSE(a != a);
|
||||
}
|
||||
|
||||
// Tests comparing two tuples with the same value.
|
||||
TEST(ComparisonTest, ComparesEqualTuples) {
|
||||
const tuple<int, bool> a(5, true), b(5, true);
|
||||
|
||||
EXPECT_TRUE(a == b);
|
||||
EXPECT_FALSE(a != b);
|
||||
}
|
||||
|
||||
// Tests comparing two different tuples that have no reference fields.
|
||||
TEST(ComparisonTest, ComparesUnequalTuplesWithoutReferenceFields) {
|
||||
typedef tuple<const int, char> FooTuple;
|
||||
|
||||
const FooTuple a(0, 'x');
|
||||
const FooTuple b(1, 'a');
|
||||
|
||||
EXPECT_TRUE(a != b);
|
||||
EXPECT_FALSE(a == b);
|
||||
|
||||
const FooTuple c(1, 'b');
|
||||
|
||||
EXPECT_TRUE(b != c);
|
||||
EXPECT_FALSE(b == c);
|
||||
}
|
||||
|
||||
// Tests comparing two different tuples that have reference fields.
|
||||
TEST(ComparisonTest, ComparesUnequalTuplesWithReferenceFields) {
|
||||
typedef tuple<int&, const char&> FooTuple;
|
||||
|
||||
int i = 5;
|
||||
const char ch = 'a';
|
||||
const FooTuple a(i, ch);
|
||||
|
||||
int j = 6;
|
||||
const FooTuple b(j, ch);
|
||||
|
||||
EXPECT_TRUE(a != b);
|
||||
EXPECT_FALSE(a == b);
|
||||
|
||||
j = 5;
|
||||
const char ch2 = 'b';
|
||||
const FooTuple c(j, ch2);
|
||||
|
||||
EXPECT_TRUE(b != c);
|
||||
EXPECT_FALSE(b == c);
|
||||
}
|
||||
|
||||
// Tests that a tuple field with a reference type is an alias of the
|
||||
// variable it's supposed to reference.
|
||||
TEST(ReferenceFieldTest, IsAliasOfReferencedVariable) {
|
||||
int n = 0;
|
||||
tuple<bool, int&> t(true, n);
|
||||
|
||||
n = 1;
|
||||
EXPECT_EQ(n, get<1>(t))
|
||||
<< "Changing a underlying variable should update the reference field.";
|
||||
|
||||
// Makes sure that the implementation doesn't do anything funny with
|
||||
// the & operator for the return type of get<>().
|
||||
EXPECT_EQ(&n, &(get<1>(t)))
|
||||
<< "The address of a reference field should equal the address of "
|
||||
<< "the underlying variable.";
|
||||
|
||||
get<1>(t) = 2;
|
||||
EXPECT_EQ(2, n)
|
||||
<< "Changing a reference field should update the underlying variable.";
|
||||
}
|
||||
|
||||
// Tests that tuple's default constructor default initializes each field.
|
||||
// This test needs to compile without generating warnings.
|
||||
TEST(TupleConstructorTest, DefaultConstructorDefaultInitializesEachField) {
|
||||
// The TR1 report requires that tuple's default constructor default
|
||||
// initializes each field, even if it's a primitive type. If the
|
||||
// implementation forgets to do this, this test will catch it by
|
||||
// generating warnings about using uninitialized variables (assuming
|
||||
// a decent compiler).
|
||||
|
||||
tuple<> empty;
|
||||
|
||||
tuple<int> a1, b1;
|
||||
b1 = a1;
|
||||
EXPECT_EQ(0, get<0>(b1));
|
||||
|
||||
tuple<int, double> a2, b2;
|
||||
b2 = a2;
|
||||
EXPECT_EQ(0, get<0>(b2));
|
||||
EXPECT_EQ(0.0, get<1>(b2));
|
||||
|
||||
tuple<double, char, bool*> a3, b3;
|
||||
b3 = a3;
|
||||
EXPECT_EQ(0.0, get<0>(b3));
|
||||
EXPECT_EQ('\0', get<1>(b3));
|
||||
EXPECT_TRUE(get<2>(b3) == NULL);
|
||||
|
||||
tuple<int, int, int, int, int, int, int, int, int, int> a10, b10;
|
||||
b10 = a10;
|
||||
EXPECT_EQ(0, get<0>(b10));
|
||||
EXPECT_EQ(0, get<1>(b10));
|
||||
EXPECT_EQ(0, get<2>(b10));
|
||||
EXPECT_EQ(0, get<3>(b10));
|
||||
EXPECT_EQ(0, get<4>(b10));
|
||||
EXPECT_EQ(0, get<5>(b10));
|
||||
EXPECT_EQ(0, get<6>(b10));
|
||||
EXPECT_EQ(0, get<7>(b10));
|
||||
EXPECT_EQ(0, get<8>(b10));
|
||||
EXPECT_EQ(0, get<9>(b10));
|
||||
}
|
||||
|
||||
// Tests constructing a tuple from its fields.
|
||||
TEST(TupleConstructorTest, ConstructsFromFields) {
|
||||
int n = 1;
|
||||
// Reference field.
|
||||
tuple<int&> a(n);
|
||||
EXPECT_EQ(&n, &(get<0>(a)));
|
||||
|
||||
// Non-reference fields.
|
||||
tuple<int, char> b(5, 'a');
|
||||
EXPECT_EQ(5, get<0>(b));
|
||||
EXPECT_EQ('a', get<1>(b));
|
||||
|
||||
// Const reference field.
|
||||
const int m = 2;
|
||||
tuple<bool, const int&> c(true, m);
|
||||
EXPECT_TRUE(get<0>(c));
|
||||
EXPECT_EQ(&m, &(get<1>(c)));
|
||||
}
|
||||
|
||||
// Tests tuple's copy constructor.
|
||||
TEST(TupleConstructorTest, CopyConstructor) {
|
||||
tuple<double, bool> a(0.0, true);
|
||||
tuple<double, bool> b(a);
|
||||
|
||||
EXPECT_DOUBLE_EQ(0.0, get<0>(b));
|
||||
EXPECT_TRUE(get<1>(b));
|
||||
}
|
||||
|
||||
// Tests constructing a tuple from another tuple that has a compatible
|
||||
// but different type.
|
||||
TEST(TupleConstructorTest, ConstructsFromDifferentTupleType) {
|
||||
tuple<int, int, char> a(0, 1, 'a');
|
||||
tuple<double, long, int> b(a);
|
||||
|
||||
EXPECT_DOUBLE_EQ(0.0, get<0>(b));
|
||||
EXPECT_EQ(1, get<1>(b));
|
||||
EXPECT_EQ('a', get<2>(b));
|
||||
}
|
||||
|
||||
// Tests constructing a 2-tuple from an std::pair.
|
||||
TEST(TupleConstructorTest, ConstructsFromPair) {
|
||||
::std::pair<int, char> a(1, 'a');
|
||||
tuple<int, char> b(a);
|
||||
tuple<int, const char&> c(a);
|
||||
}
|
||||
|
||||
// Tests assigning a tuple to another tuple with the same type.
|
||||
TEST(TupleAssignmentTest, AssignsToSameTupleType) {
|
||||
const tuple<int, long> a(5, 7L);
|
||||
tuple<int, long> b;
|
||||
b = a;
|
||||
EXPECT_EQ(5, get<0>(b));
|
||||
EXPECT_EQ(7L, get<1>(b));
|
||||
}
|
||||
|
||||
// Tests assigning a tuple to another tuple with a different but
|
||||
// compatible type.
|
||||
TEST(TupleAssignmentTest, AssignsToDifferentTupleType) {
|
||||
const tuple<int, long, bool> a(1, 7L, true);
|
||||
tuple<long, int, bool> b;
|
||||
b = a;
|
||||
EXPECT_EQ(1L, get<0>(b));
|
||||
EXPECT_EQ(7, get<1>(b));
|
||||
EXPECT_TRUE(get<2>(b));
|
||||
}
|
||||
|
||||
// Tests assigning an std::pair to a 2-tuple.
|
||||
TEST(TupleAssignmentTest, AssignsFromPair) {
|
||||
const ::std::pair<int, bool> a(5, true);
|
||||
tuple<int, bool> b;
|
||||
b = a;
|
||||
EXPECT_EQ(5, get<0>(b));
|
||||
EXPECT_TRUE(get<1>(b));
|
||||
|
||||
tuple<long, bool> c;
|
||||
c = a;
|
||||
EXPECT_EQ(5L, get<0>(c));
|
||||
EXPECT_TRUE(get<1>(c));
|
||||
}
|
||||
|
||||
// A fixture for testing big tuples.
|
||||
class BigTupleTest : public testing::Test {
|
||||
protected:
|
||||
typedef tuple<int, int, int, int, int, int, int, int, int, int> BigTuple;
|
||||
|
||||
BigTupleTest() :
|
||||
a_(1, 0, 0, 0, 0, 0, 0, 0, 0, 2),
|
||||
b_(1, 0, 0, 0, 0, 0, 0, 0, 0, 3) {}
|
||||
|
||||
BigTuple a_, b_;
|
||||
};
|
||||
|
||||
// Tests constructing big tuples.
|
||||
TEST_F(BigTupleTest, Construction) {
|
||||
BigTuple a;
|
||||
BigTuple b(b_);
|
||||
}
|
||||
|
||||
// Tests that get<N>(t) returns the N-th (0-based) field of tuple t.
|
||||
TEST_F(BigTupleTest, get) {
|
||||
EXPECT_EQ(1, get<0>(a_));
|
||||
EXPECT_EQ(2, get<9>(a_));
|
||||
|
||||
// Tests that get() works on a const tuple too.
|
||||
const BigTuple a(a_);
|
||||
EXPECT_EQ(1, get<0>(a));
|
||||
EXPECT_EQ(2, get<9>(a));
|
||||
}
|
||||
|
||||
// Tests comparing big tuples.
|
||||
TEST_F(BigTupleTest, Comparisons) {
|
||||
EXPECT_TRUE(a_ == a_);
|
||||
EXPECT_FALSE(a_ != a_);
|
||||
|
||||
EXPECT_TRUE(a_ != b_);
|
||||
EXPECT_FALSE(a_ == b_);
|
||||
}
|
||||
|
||||
TEST(MakeTupleTest, WorksForScalarTypes) {
|
||||
tuple<bool, int> a;
|
||||
a = make_tuple(true, 5);
|
||||
EXPECT_TRUE(get<0>(a));
|
||||
EXPECT_EQ(5, get<1>(a));
|
||||
|
||||
tuple<char, int, long> b;
|
||||
b = make_tuple('a', 'b', 5);
|
||||
EXPECT_EQ('a', get<0>(b));
|
||||
EXPECT_EQ('b', get<1>(b));
|
||||
EXPECT_EQ(5, get<2>(b));
|
||||
}
|
||||
|
||||
TEST(MakeTupleTest, WorksForPointers) {
|
||||
int a[] = { 1, 2, 3, 4 };
|
||||
const char* const str = "hi";
|
||||
int* const p = a;
|
||||
|
||||
tuple<const char*, int*> t;
|
||||
t = make_tuple(str, p);
|
||||
EXPECT_EQ(str, get<0>(t));
|
||||
EXPECT_EQ(p, get<1>(t));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
|
@ -1,45 +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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "test/gtest-typed-test_test.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
// Tests that the same type-parameterized test case can be
|
||||
// instantiated in different translation units linked together.
|
||||
// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(Vector, ContainerTest,
|
||||
testing::Types<std::vector<int> >);
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
|
@ -1,380 +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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#include "test/gtest-typed-test_test.h"
|
||||
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
using testing::Test;
|
||||
|
||||
// Used for testing that SetUpTestCase()/TearDownTestCase(), fixture
|
||||
// ctor/dtor, and SetUp()/TearDown() work correctly in typed tests and
|
||||
// type-parameterized test.
|
||||
template <typename T>
|
||||
class CommonTest : public Test {
|
||||
// For some technical reason, SetUpTestCase() and TearDownTestCase()
|
||||
// must be public.
|
||||
public:
|
||||
static void SetUpTestCase() {
|
||||
shared_ = new T(5);
|
||||
}
|
||||
|
||||
static void TearDownTestCase() {
|
||||
delete shared_;
|
||||
shared_ = NULL;
|
||||
}
|
||||
|
||||
// This 'protected:' is optional. There's no harm in making all
|
||||
// members of this fixture class template public.
|
||||
protected:
|
||||
// We used to use std::list here, but switched to std::vector since
|
||||
// MSVC's <list> doesn't compile cleanly with /W4.
|
||||
typedef std::vector<T> Vector;
|
||||
typedef std::set<int> IntSet;
|
||||
|
||||
CommonTest() : value_(1) {}
|
||||
|
||||
virtual ~CommonTest() { EXPECT_EQ(3, value_); }
|
||||
|
||||
virtual void SetUp() {
|
||||
EXPECT_EQ(1, value_);
|
||||
value_++;
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
EXPECT_EQ(2, value_);
|
||||
value_++;
|
||||
}
|
||||
|
||||
T value_;
|
||||
static T* shared_;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
T* CommonTest<T>::shared_ = NULL;
|
||||
|
||||
// This #ifdef block tests typed tests.
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
|
||||
using testing::Types;
|
||||
|
||||
// Tests that SetUpTestCase()/TearDownTestCase(), fixture ctor/dtor,
|
||||
// and SetUp()/TearDown() work correctly in typed tests
|
||||
|
||||
typedef Types<char, int> TwoTypes;
|
||||
TYPED_TEST_CASE(CommonTest, TwoTypes);
|
||||
|
||||
TYPED_TEST(CommonTest, ValuesAreCorrect) {
|
||||
// Static members of the fixture class template can be visited via
|
||||
// the TestFixture:: prefix.
|
||||
EXPECT_EQ(5, *TestFixture::shared_);
|
||||
|
||||
// Typedefs in the fixture class template can be visited via the
|
||||
// "typename TestFixture::" prefix.
|
||||
typename TestFixture::Vector empty;
|
||||
EXPECT_EQ(0U, empty.size());
|
||||
|
||||
typename TestFixture::IntSet empty2;
|
||||
EXPECT_EQ(0U, empty2.size());
|
||||
|
||||
// Non-static members of the fixture class must be visited via
|
||||
// 'this', as required by C++ for class templates.
|
||||
EXPECT_EQ(2, this->value_);
|
||||
}
|
||||
|
||||
// The second test makes sure shared_ is not deleted after the first
|
||||
// test.
|
||||
TYPED_TEST(CommonTest, ValuesAreStillCorrect) {
|
||||
// Static members of the fixture class template can also be visited
|
||||
// via 'this'.
|
||||
ASSERT_TRUE(this->shared_ != NULL);
|
||||
EXPECT_EQ(5, *this->shared_);
|
||||
|
||||
// TypeParam can be used to refer to the type parameter.
|
||||
EXPECT_EQ(static_cast<TypeParam>(2), this->value_);
|
||||
}
|
||||
|
||||
// Tests that multiple TYPED_TEST_CASE's can be defined in the same
|
||||
// translation unit.
|
||||
|
||||
template <typename T>
|
||||
class TypedTest1 : public Test {
|
||||
};
|
||||
|
||||
// Verifies that the second argument of TYPED_TEST_CASE can be a
|
||||
// single type.
|
||||
TYPED_TEST_CASE(TypedTest1, int);
|
||||
TYPED_TEST(TypedTest1, A) {}
|
||||
|
||||
template <typename T>
|
||||
class TypedTest2 : public Test {
|
||||
};
|
||||
|
||||
// Verifies that the second argument of TYPED_TEST_CASE can be a
|
||||
// Types<...> type list.
|
||||
TYPED_TEST_CASE(TypedTest2, Types<int>);
|
||||
|
||||
// This also verifies that tests from different typed test cases can
|
||||
// share the same name.
|
||||
TYPED_TEST(TypedTest2, A) {}
|
||||
|
||||
// Tests that a typed test case can be defined in a namespace.
|
||||
|
||||
namespace library1 {
|
||||
|
||||
template <typename T>
|
||||
class NumericTest : public Test {
|
||||
};
|
||||
|
||||
typedef Types<int, long> NumericTypes;
|
||||
TYPED_TEST_CASE(NumericTest, NumericTypes);
|
||||
|
||||
TYPED_TEST(NumericTest, DefaultIsZero) {
|
||||
EXPECT_EQ(0, TypeParam());
|
||||
}
|
||||
|
||||
} // namespace library1
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
// This #ifdef block tests type-parameterized tests.
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
using testing::Types;
|
||||
using testing::internal::TypedTestCasePState;
|
||||
|
||||
// Tests TypedTestCasePState.
|
||||
|
||||
class TypedTestCasePStateTest : public Test {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
state_.AddTestName("foo.cc", 0, "FooTest", "A");
|
||||
state_.AddTestName("foo.cc", 0, "FooTest", "B");
|
||||
state_.AddTestName("foo.cc", 0, "FooTest", "C");
|
||||
}
|
||||
|
||||
TypedTestCasePState state_;
|
||||
};
|
||||
|
||||
TEST_F(TypedTestCasePStateTest, SucceedsForMatchingList) {
|
||||
const char* tests = "A, B, C";
|
||||
EXPECT_EQ(tests,
|
||||
state_.VerifyRegisteredTestNames("foo.cc", 1, tests));
|
||||
}
|
||||
|
||||
// Makes sure that the order of the tests and spaces around the names
|
||||
// don't matter.
|
||||
TEST_F(TypedTestCasePStateTest, IgnoresOrderAndSpaces) {
|
||||
const char* tests = "A,C, B";
|
||||
EXPECT_EQ(tests,
|
||||
state_.VerifyRegisteredTestNames("foo.cc", 1, tests));
|
||||
}
|
||||
|
||||
typedef TypedTestCasePStateTest TypedTestCasePStateDeathTest;
|
||||
|
||||
TEST_F(TypedTestCasePStateDeathTest, DetectsDuplicates) {
|
||||
EXPECT_DEATH_IF_SUPPORTED(
|
||||
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, A, C"),
|
||||
"foo\\.cc.1.?: Test A is listed more than once\\.");
|
||||
}
|
||||
|
||||
TEST_F(TypedTestCasePStateDeathTest, DetectsExtraTest) {
|
||||
EXPECT_DEATH_IF_SUPPORTED(
|
||||
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C, D"),
|
||||
"foo\\.cc.1.?: No test named D can be found in this test case\\.");
|
||||
}
|
||||
|
||||
TEST_F(TypedTestCasePStateDeathTest, DetectsMissedTest) {
|
||||
EXPECT_DEATH_IF_SUPPORTED(
|
||||
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, C"),
|
||||
"foo\\.cc.1.?: You forgot to list test B\\.");
|
||||
}
|
||||
|
||||
// Tests that defining a test for a parameterized test case generates
|
||||
// a run-time error if the test case has been registered.
|
||||
TEST_F(TypedTestCasePStateDeathTest, DetectsTestAfterRegistration) {
|
||||
state_.VerifyRegisteredTestNames("foo.cc", 1, "A, B, C");
|
||||
EXPECT_DEATH_IF_SUPPORTED(
|
||||
state_.AddTestName("foo.cc", 2, "FooTest", "D"),
|
||||
"foo\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_CASE_P"
|
||||
"\\(FooTest, \\.\\.\\.\\)\\.");
|
||||
}
|
||||
|
||||
// Tests that SetUpTestCase()/TearDownTestCase(), fixture ctor/dtor,
|
||||
// and SetUp()/TearDown() work correctly in type-parameterized tests.
|
||||
|
||||
template <typename T>
|
||||
class DerivedTest : public CommonTest<T> {
|
||||
};
|
||||
|
||||
TYPED_TEST_CASE_P(DerivedTest);
|
||||
|
||||
TYPED_TEST_P(DerivedTest, ValuesAreCorrect) {
|
||||
// Static members of the fixture class template can be visited via
|
||||
// the TestFixture:: prefix.
|
||||
EXPECT_EQ(5, *TestFixture::shared_);
|
||||
|
||||
// Non-static members of the fixture class must be visited via
|
||||
// 'this', as required by C++ for class templates.
|
||||
EXPECT_EQ(2, this->value_);
|
||||
}
|
||||
|
||||
// The second test makes sure shared_ is not deleted after the first
|
||||
// test.
|
||||
TYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) {
|
||||
// Static members of the fixture class template can also be visited
|
||||
// via 'this'.
|
||||
ASSERT_TRUE(this->shared_ != NULL);
|
||||
EXPECT_EQ(5, *this->shared_);
|
||||
EXPECT_EQ(2, this->value_);
|
||||
}
|
||||
|
||||
REGISTER_TYPED_TEST_CASE_P(DerivedTest,
|
||||
ValuesAreCorrect, ValuesAreStillCorrect);
|
||||
|
||||
typedef Types<short, long> MyTwoTypes;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(My, DerivedTest, MyTwoTypes);
|
||||
|
||||
// Tests that multiple TYPED_TEST_CASE_P's can be defined in the same
|
||||
// translation unit.
|
||||
|
||||
template <typename T>
|
||||
class TypedTestP1 : public Test {
|
||||
};
|
||||
|
||||
TYPED_TEST_CASE_P(TypedTestP1);
|
||||
|
||||
// For testing that the code between TYPED_TEST_CASE_P() and
|
||||
// TYPED_TEST_P() is not enclosed in a namespace.
|
||||
typedef int IntAfterTypedTestCaseP;
|
||||
|
||||
TYPED_TEST_P(TypedTestP1, A) {}
|
||||
TYPED_TEST_P(TypedTestP1, B) {}
|
||||
|
||||
// For testing that the code between TYPED_TEST_P() and
|
||||
// REGISTER_TYPED_TEST_CASE_P() is not enclosed in a namespace.
|
||||
typedef int IntBeforeRegisterTypedTestCaseP;
|
||||
|
||||
REGISTER_TYPED_TEST_CASE_P(TypedTestP1, A, B);
|
||||
|
||||
template <typename T>
|
||||
class TypedTestP2 : public Test {
|
||||
};
|
||||
|
||||
TYPED_TEST_CASE_P(TypedTestP2);
|
||||
|
||||
// This also verifies that tests from different type-parameterized
|
||||
// test cases can share the same name.
|
||||
TYPED_TEST_P(TypedTestP2, A) {}
|
||||
|
||||
REGISTER_TYPED_TEST_CASE_P(TypedTestP2, A);
|
||||
|
||||
// Verifies that the code between TYPED_TEST_CASE_P() and
|
||||
// REGISTER_TYPED_TEST_CASE_P() is not enclosed in a namespace.
|
||||
IntAfterTypedTestCaseP after = 0;
|
||||
IntBeforeRegisterTypedTestCaseP before = 0;
|
||||
|
||||
// Verifies that the last argument of INSTANTIATE_TYPED_TEST_CASE_P()
|
||||
// can be either a single type or a Types<...> type list.
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(Int, TypedTestP1, int);
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(Int, TypedTestP2, Types<int>);
|
||||
|
||||
// Tests that the same type-parameterized test case can be
|
||||
// instantiated more than once in the same translation unit.
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(Double, TypedTestP2, Types<double>);
|
||||
|
||||
// Tests that the same type-parameterized test case can be
|
||||
// instantiated in different translation units linked together.
|
||||
// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)
|
||||
typedef Types<std::vector<double>, std::set<char> > MyContainers;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(My, ContainerTest, MyContainers);
|
||||
|
||||
// Tests that a type-parameterized test case can be defined and
|
||||
// instantiated in a namespace.
|
||||
|
||||
namespace library2 {
|
||||
|
||||
template <typename T>
|
||||
class NumericTest : public Test {
|
||||
};
|
||||
|
||||
TYPED_TEST_CASE_P(NumericTest);
|
||||
|
||||
TYPED_TEST_P(NumericTest, DefaultIsZero) {
|
||||
EXPECT_EQ(0, TypeParam());
|
||||
}
|
||||
|
||||
TYPED_TEST_P(NumericTest, ZeroIsLessThanOne) {
|
||||
EXPECT_LT(TypeParam(0), TypeParam(1));
|
||||
}
|
||||
|
||||
REGISTER_TYPED_TEST_CASE_P(NumericTest,
|
||||
DefaultIsZero, ZeroIsLessThanOne);
|
||||
typedef Types<int, double> NumericTypes;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(My, NumericTest, NumericTypes);
|
||||
|
||||
static const char* GetTestName() {
|
||||
return testing::UnitTest::GetInstance()->current_test_info()->name();
|
||||
}
|
||||
// Test the stripping of space from test names
|
||||
template <typename T> class TrimmedTest : public Test { };
|
||||
TYPED_TEST_CASE_P(TrimmedTest);
|
||||
TYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ("Test1", GetTestName()); }
|
||||
TYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ("Test2", GetTestName()); }
|
||||
TYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ("Test3", GetTestName()); }
|
||||
TYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ("Test4", GetTestName()); }
|
||||
TYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ("Test5", GetTestName()); }
|
||||
REGISTER_TYPED_TEST_CASE_P(
|
||||
TrimmedTest,
|
||||
Test1, Test2,Test3 , Test4 ,Test5 ); // NOLINT
|
||||
template <typename T1, typename T2> struct MyPair {};
|
||||
// Be sure to try a type with a comma in its name just in case it matters.
|
||||
typedef Types<int, double, MyPair<int, int> > TrimTypes;
|
||||
INSTANTIATE_TYPED_TEST_CASE_P(My, TrimmedTest, TrimTypes);
|
||||
|
||||
} // namespace library2
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
#if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
|
||||
|
||||
// Google Test may not support type-parameterized tests with some
|
||||
// compilers. If we use conditional compilation to compile out all
|
||||
// code referring to the gtest_main library, MSVC linker will not link
|
||||
// that library at all and consequently complain about missing entry
|
||||
// point defined in that library (fatal error LNK1561: entry point
|
||||
// must be defined). This dummy test keeps gtest_main linked in.
|
||||
TEST(DummyTest, TypedTestsAreNotSupportedOnThisPlatform) {}
|
||||
|
||||
#endif // #if !defined(GTEST_HAS_TYPED_TEST) && !defined(GTEST_HAS_TYPED_TEST_P)
|
||||
|
|
@ -1,66 +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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
#ifndef GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
#define GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
using testing::Test;
|
||||
|
||||
// For testing that the same type-parameterized test case can be
|
||||
// instantiated in different translation units linked together.
|
||||
// ContainerTest will be instantiated in both gtest-typed-test_test.cc
|
||||
// and gtest-typed-test2_test.cc.
|
||||
|
||||
template <typename T>
|
||||
class ContainerTest : public Test {
|
||||
};
|
||||
|
||||
TYPED_TEST_CASE_P(ContainerTest);
|
||||
|
||||
TYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) {
|
||||
TypeParam container;
|
||||
}
|
||||
|
||||
TYPED_TEST_P(ContainerTest, InitialSizeIsZero) {
|
||||
TypeParam container;
|
||||
EXPECT_EQ(0U, container.size());
|
||||
}
|
||||
|
||||
REGISTER_TYPED_TEST_CASE_P(ContainerTest,
|
||||
CanBeDefaultConstructed, InitialSizeIsZero);
|
||||
|
||||
#endif // GTEST_HAS_TYPED_TEST_P
|
||||
|
||||
#endif // GTEST_TEST_GTEST_TYPED_TEST_TEST_H_
|
||||
|
|
@ -1,341 +0,0 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// The Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// This file contains tests verifying correctness of data provided via
|
||||
// UnitTest's public methods.
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#include <string.h> // For strcmp.
|
||||
#include <algorithm>
|
||||
|
||||
using ::testing::InitGoogleTest;
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
template <typename T>
|
||||
struct LessByName {
|
||||
bool operator()(const T* a, const T* b) {
|
||||
return strcmp(a->name(), b->name()) < 0;
|
||||
}
|
||||
};
|
||||
|
||||
class UnitTestHelper {
|
||||
public:
|
||||
// Returns the array of pointers to all test cases sorted by the test case
|
||||
// name. The caller is responsible for deleting the array.
|
||||
static TestCase const** GetSortedTestCases() {
|
||||
UnitTest& unit_test = *UnitTest::GetInstance();
|
||||
TestCase const** const test_cases =
|
||||
new const TestCase*[unit_test.total_test_case_count()];
|
||||
|
||||
for (int i = 0; i < unit_test.total_test_case_count(); ++i)
|
||||
test_cases[i] = unit_test.GetTestCase(i);
|
||||
|
||||
std::sort(test_cases,
|
||||
test_cases + unit_test.total_test_case_count(),
|
||||
LessByName<TestCase>());
|
||||
return test_cases;
|
||||
}
|
||||
|
||||
// Returns the test case by its name. The caller doesn't own the returned
|
||||
// pointer.
|
||||
static const TestCase* FindTestCase(const char* name) {
|
||||
UnitTest& unit_test = *UnitTest::GetInstance();
|
||||
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
|
||||
const TestCase* test_case = unit_test.GetTestCase(i);
|
||||
if (0 == strcmp(test_case->name(), name))
|
||||
return test_case;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Returns the array of pointers to all tests in a particular test case
|
||||
// sorted by the test name. The caller is responsible for deleting the
|
||||
// array.
|
||||
static TestInfo const** GetSortedTests(const TestCase* test_case) {
|
||||
TestInfo const** const tests =
|
||||
new const TestInfo*[test_case->total_test_count()];
|
||||
|
||||
for (int i = 0; i < test_case->total_test_count(); ++i)
|
||||
tests[i] = test_case->GetTestInfo(i);
|
||||
|
||||
std::sort(tests, tests + test_case->total_test_count(),
|
||||
LessByName<TestInfo>());
|
||||
return tests;
|
||||
}
|
||||
};
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
template <typename T> class TestCaseWithCommentTest : public Test {};
|
||||
TYPED_TEST_CASE(TestCaseWithCommentTest, Types<int>);
|
||||
TYPED_TEST(TestCaseWithCommentTest, Dummy) {}
|
||||
|
||||
const int kTypedTestCases = 1;
|
||||
const int kTypedTests = 1;
|
||||
#else
|
||||
const int kTypedTestCases = 0;
|
||||
const int kTypedTests = 0;
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
// We can only test the accessors that do not change value while tests run.
|
||||
// Since tests can be run in any order, the values the accessors that track
|
||||
// test execution (such as failed_test_count) can not be predicted.
|
||||
TEST(ApiTest, UnitTestImmutableAccessorsWork) {
|
||||
UnitTest* unit_test = UnitTest::GetInstance();
|
||||
|
||||
ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
|
||||
EXPECT_EQ(1 + kTypedTestCases, unit_test->test_case_to_run_count());
|
||||
EXPECT_EQ(2, unit_test->disabled_test_count());
|
||||
EXPECT_EQ(5 + kTypedTests, unit_test->total_test_count());
|
||||
EXPECT_EQ(3 + kTypedTests, unit_test->test_to_run_count());
|
||||
|
||||
const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
|
||||
|
||||
EXPECT_STREQ("ApiTest", test_cases[0]->name());
|
||||
EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
delete[] test_cases;
|
||||
|
||||
// The following lines initiate actions to verify certain methods in
|
||||
// FinalSuccessChecker::TearDown.
|
||||
|
||||
// Records a test property to verify TestResult::GetTestProperty().
|
||||
RecordProperty("key", "value");
|
||||
}
|
||||
|
||||
AssertionResult IsNull(const char* str) {
|
||||
if (str != NULL) {
|
||||
return testing::AssertionFailure() << "argument is " << str;
|
||||
}
|
||||
return AssertionSuccess();
|
||||
}
|
||||
|
||||
TEST(ApiTest, TestCaseImmutableAccessorsWork) {
|
||||
const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
|
||||
ASSERT_TRUE(test_case != NULL);
|
||||
|
||||
EXPECT_STREQ("ApiTest", test_case->name());
|
||||
EXPECT_TRUE(IsNull(test_case->type_param()));
|
||||
EXPECT_TRUE(test_case->should_run());
|
||||
EXPECT_EQ(1, test_case->disabled_test_count());
|
||||
EXPECT_EQ(3, test_case->test_to_run_count());
|
||||
ASSERT_EQ(4, test_case->total_test_count());
|
||||
|
||||
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
|
||||
|
||||
EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[0]->value_param()));
|
||||
EXPECT_TRUE(IsNull(tests[0]->type_param()));
|
||||
EXPECT_FALSE(tests[0]->should_run());
|
||||
|
||||
EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[1]->value_param()));
|
||||
EXPECT_TRUE(IsNull(tests[1]->type_param()));
|
||||
EXPECT_TRUE(tests[1]->should_run());
|
||||
|
||||
EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[2]->value_param()));
|
||||
EXPECT_TRUE(IsNull(tests[2]->type_param()));
|
||||
EXPECT_TRUE(tests[2]->should_run());
|
||||
|
||||
EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[3]->value_param()));
|
||||
EXPECT_TRUE(IsNull(tests[3]->type_param()));
|
||||
EXPECT_TRUE(tests[3]->should_run());
|
||||
|
||||
delete[] tests;
|
||||
tests = NULL;
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
|
||||
ASSERT_TRUE(test_case != NULL);
|
||||
|
||||
EXPECT_STREQ("TestCaseWithCommentTest/0", test_case->name());
|
||||
EXPECT_STREQ(GetTypeName<int>().c_str(), test_case->type_param());
|
||||
EXPECT_TRUE(test_case->should_run());
|
||||
EXPECT_EQ(0, test_case->disabled_test_count());
|
||||
EXPECT_EQ(1, test_case->test_to_run_count());
|
||||
ASSERT_EQ(1, test_case->total_test_count());
|
||||
|
||||
tests = UnitTestHelper::GetSortedTests(test_case);
|
||||
|
||||
EXPECT_STREQ("Dummy", tests[0]->name());
|
||||
EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[0]->value_param()));
|
||||
EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
|
||||
EXPECT_TRUE(tests[0]->should_run());
|
||||
|
||||
delete[] tests;
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
}
|
||||
|
||||
TEST(ApiTest, TestCaseDisabledAccessorsWork) {
|
||||
const TestCase* test_case = UnitTestHelper::FindTestCase("DISABLED_Test");
|
||||
ASSERT_TRUE(test_case != NULL);
|
||||
|
||||
EXPECT_STREQ("DISABLED_Test", test_case->name());
|
||||
EXPECT_TRUE(IsNull(test_case->type_param()));
|
||||
EXPECT_FALSE(test_case->should_run());
|
||||
EXPECT_EQ(1, test_case->disabled_test_count());
|
||||
EXPECT_EQ(0, test_case->test_to_run_count());
|
||||
ASSERT_EQ(1, test_case->total_test_count());
|
||||
|
||||
const TestInfo* const test_info = test_case->GetTestInfo(0);
|
||||
EXPECT_STREQ("Dummy2", test_info->name());
|
||||
EXPECT_STREQ("DISABLED_Test", test_info->test_case_name());
|
||||
EXPECT_TRUE(IsNull(test_info->value_param()));
|
||||
EXPECT_TRUE(IsNull(test_info->type_param()));
|
||||
EXPECT_FALSE(test_info->should_run());
|
||||
}
|
||||
|
||||
// These two tests are here to provide support for testing
|
||||
// test_case_to_run_count, disabled_test_count, and test_to_run_count.
|
||||
TEST(ApiTest, DISABLED_Dummy1) {}
|
||||
TEST(DISABLED_Test, Dummy2) {}
|
||||
|
||||
class FinalSuccessChecker : public Environment {
|
||||
protected:
|
||||
virtual void TearDown() {
|
||||
UnitTest* unit_test = UnitTest::GetInstance();
|
||||
|
||||
EXPECT_EQ(1 + kTypedTestCases, unit_test->successful_test_case_count());
|
||||
EXPECT_EQ(3 + kTypedTests, unit_test->successful_test_count());
|
||||
EXPECT_EQ(0, unit_test->failed_test_case_count());
|
||||
EXPECT_EQ(0, unit_test->failed_test_count());
|
||||
EXPECT_TRUE(unit_test->Passed());
|
||||
EXPECT_FALSE(unit_test->Failed());
|
||||
ASSERT_EQ(2 + kTypedTestCases, unit_test->total_test_case_count());
|
||||
|
||||
const TestCase** const test_cases = UnitTestHelper::GetSortedTestCases();
|
||||
|
||||
EXPECT_STREQ("ApiTest", test_cases[0]->name());
|
||||
EXPECT_TRUE(IsNull(test_cases[0]->type_param()));
|
||||
EXPECT_TRUE(test_cases[0]->should_run());
|
||||
EXPECT_EQ(1, test_cases[0]->disabled_test_count());
|
||||
ASSERT_EQ(4, test_cases[0]->total_test_count());
|
||||
EXPECT_EQ(3, test_cases[0]->successful_test_count());
|
||||
EXPECT_EQ(0, test_cases[0]->failed_test_count());
|
||||
EXPECT_TRUE(test_cases[0]->Passed());
|
||||
EXPECT_FALSE(test_cases[0]->Failed());
|
||||
|
||||
EXPECT_STREQ("DISABLED_Test", test_cases[1]->name());
|
||||
EXPECT_TRUE(IsNull(test_cases[1]->type_param()));
|
||||
EXPECT_FALSE(test_cases[1]->should_run());
|
||||
EXPECT_EQ(1, test_cases[1]->disabled_test_count());
|
||||
ASSERT_EQ(1, test_cases[1]->total_test_count());
|
||||
EXPECT_EQ(0, test_cases[1]->successful_test_count());
|
||||
EXPECT_EQ(0, test_cases[1]->failed_test_count());
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
EXPECT_STREQ("TestCaseWithCommentTest/0", test_cases[2]->name());
|
||||
EXPECT_STREQ(GetTypeName<int>().c_str(), test_cases[2]->type_param());
|
||||
EXPECT_TRUE(test_cases[2]->should_run());
|
||||
EXPECT_EQ(0, test_cases[2]->disabled_test_count());
|
||||
ASSERT_EQ(1, test_cases[2]->total_test_count());
|
||||
EXPECT_EQ(1, test_cases[2]->successful_test_count());
|
||||
EXPECT_EQ(0, test_cases[2]->failed_test_count());
|
||||
EXPECT_TRUE(test_cases[2]->Passed());
|
||||
EXPECT_FALSE(test_cases[2]->Failed());
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
|
||||
const TestCase* test_case = UnitTestHelper::FindTestCase("ApiTest");
|
||||
const TestInfo** tests = UnitTestHelper::GetSortedTests(test_case);
|
||||
EXPECT_STREQ("DISABLED_Dummy1", tests[0]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[0]->test_case_name());
|
||||
EXPECT_FALSE(tests[0]->should_run());
|
||||
|
||||
EXPECT_STREQ("TestCaseDisabledAccessorsWork", tests[1]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[1]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[1]->value_param()));
|
||||
EXPECT_TRUE(IsNull(tests[1]->type_param()));
|
||||
EXPECT_TRUE(tests[1]->should_run());
|
||||
EXPECT_TRUE(tests[1]->result()->Passed());
|
||||
EXPECT_EQ(0, tests[1]->result()->test_property_count());
|
||||
|
||||
EXPECT_STREQ("TestCaseImmutableAccessorsWork", tests[2]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[2]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[2]->value_param()));
|
||||
EXPECT_TRUE(IsNull(tests[2]->type_param()));
|
||||
EXPECT_TRUE(tests[2]->should_run());
|
||||
EXPECT_TRUE(tests[2]->result()->Passed());
|
||||
EXPECT_EQ(0, tests[2]->result()->test_property_count());
|
||||
|
||||
EXPECT_STREQ("UnitTestImmutableAccessorsWork", tests[3]->name());
|
||||
EXPECT_STREQ("ApiTest", tests[3]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[3]->value_param()));
|
||||
EXPECT_TRUE(IsNull(tests[3]->type_param()));
|
||||
EXPECT_TRUE(tests[3]->should_run());
|
||||
EXPECT_TRUE(tests[3]->result()->Passed());
|
||||
EXPECT_EQ(1, tests[3]->result()->test_property_count());
|
||||
const TestProperty& property = tests[3]->result()->GetTestProperty(0);
|
||||
EXPECT_STREQ("key", property.key());
|
||||
EXPECT_STREQ("value", property.value());
|
||||
|
||||
delete[] tests;
|
||||
|
||||
#if GTEST_HAS_TYPED_TEST
|
||||
test_case = UnitTestHelper::FindTestCase("TestCaseWithCommentTest/0");
|
||||
tests = UnitTestHelper::GetSortedTests(test_case);
|
||||
|
||||
EXPECT_STREQ("Dummy", tests[0]->name());
|
||||
EXPECT_STREQ("TestCaseWithCommentTest/0", tests[0]->test_case_name());
|
||||
EXPECT_TRUE(IsNull(tests[0]->value_param()));
|
||||
EXPECT_STREQ(GetTypeName<int>().c_str(), tests[0]->type_param());
|
||||
EXPECT_TRUE(tests[0]->should_run());
|
||||
EXPECT_TRUE(tests[0]->result()->Passed());
|
||||
EXPECT_EQ(0, tests[0]->result()->test_property_count());
|
||||
|
||||
delete[] tests;
|
||||
#endif // GTEST_HAS_TYPED_TEST
|
||||
delete[] test_cases;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
InitGoogleTest(&argc, argv);
|
||||
|
||||
AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker());
|
||||
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
//
|
||||
// Tests for Google C++ Testing Framework (Google Test)
|
||||
//
|
||||
// Sometimes it's desirable to build most of Google Test's own tests
|
||||
// by compiling a single file. This file serves this purpose.
|
||||
#include "test/gtest-filepath_test.cc"
|
||||
#include "test/gtest-linked_ptr_test.cc"
|
||||
#include "test/gtest-message_test.cc"
|
||||
#include "test/gtest-options_test.cc"
|
||||
#include "test/gtest-port_test.cc"
|
||||
#include "test/gtest_pred_impl_unittest.cc"
|
||||
#include "test/gtest_prod_test.cc"
|
||||
#include "test/gtest-test-part_test.cc"
|
||||
#include "test/gtest-typed-test_test.cc"
|
||||
#include "test/gtest-typed-test2_test.cc"
|
||||
#include "test/gtest_unittest.cc"
|
||||
#include "test/production.cc"
|
||||
|
|
@ -1,212 +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 break-on-failure mode.
|
||||
|
||||
A user can ask Google Test to seg-fault when an assertion fails, using
|
||||
either the GTEST_BREAK_ON_FAILURE environment variable or the
|
||||
--gtest_break_on_failure flag. This script tests such functionality
|
||||
by invoking gtest_break_on_failure_unittest_ (a program written with
|
||||
Google Test) with different environments and command line flags.
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import gtest_test_utils
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
# Constants.
|
||||
|
||||
IS_WINDOWS = os.name == 'nt'
|
||||
|
||||
# The environment variable for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'
|
||||
|
||||
# The command line flag for enabling/disabling the break-on-failure mode.
|
||||
BREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'
|
||||
|
||||
# The environment variable for enabling/disabling the throw-on-failure mode.
|
||||
THROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'
|
||||
|
||||
# The environment variable for enabling/disabling the catch-exceptions mode.
|
||||
CATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'
|
||||
|
||||
# Path to the gtest_break_on_failure_unittest_ program.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'gtest_break_on_failure_unittest_')
|
||||
|
||||
|
||||
environ = gtest_test_utils.environ
|
||||
SetEnvVar = gtest_test_utils.SetEnvVar
|
||||
|
||||
# Tests in this file run a Google-Test-based test program and expect it
|
||||
# to terminate prematurely. Therefore they are incompatible with
|
||||
# the premature-exit-file protocol by design. Unset the
|
||||
# premature-exit filepath to prevent Google Test from creating
|
||||
# the file.
|
||||
SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
|
||||
|
||||
|
||||
def Run(command):
|
||||
"""Runs a command; returns 1 if it was killed by a signal, or 0 otherwise."""
|
||||
|
||||
p = gtest_test_utils.Subprocess(command, env=environ)
|
||||
if p.terminated_by_signal:
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
# The tests.
|
||||
|
||||
|
||||
class GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable or
|
||||
the --gtest_break_on_failure flag to turn assertion failures into
|
||||
segmentation faults.
|
||||
"""
|
||||
|
||||
def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):
|
||||
"""Runs gtest_break_on_failure_unittest_ and verifies that it does
|
||||
(or does not) have a seg-fault.
|
||||
|
||||
Args:
|
||||
env_var_value: value of the GTEST_BREAK_ON_FAILURE environment
|
||||
variable; None if the variable should be unset.
|
||||
flag_value: value of the --gtest_break_on_failure flag;
|
||||
None if the flag should not be present.
|
||||
expect_seg_fault: 1 if the program is expected to generate a seg-fault;
|
||||
0 otherwise.
|
||||
"""
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)
|
||||
|
||||
if env_var_value is None:
|
||||
env_var_value_msg = ' is not set'
|
||||
else:
|
||||
env_var_value_msg = '=' + env_var_value
|
||||
|
||||
if flag_value is None:
|
||||
flag = ''
|
||||
elif flag_value == '0':
|
||||
flag = '--%s=0' % BREAK_ON_FAILURE_FLAG
|
||||
else:
|
||||
flag = '--%s' % BREAK_ON_FAILURE_FLAG
|
||||
|
||||
command = [EXE_PATH]
|
||||
if flag:
|
||||
command.append(flag)
|
||||
|
||||
if expect_seg_fault:
|
||||
should_or_not = 'should'
|
||||
else:
|
||||
should_or_not = 'should not'
|
||||
|
||||
has_seg_fault = Run(command)
|
||||
|
||||
SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
msg = ('when %s%s, an assertion failure in "%s" %s cause a seg-fault.' %
|
||||
(BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),
|
||||
should_or_not))
|
||||
self.assert_(has_seg_fault == expect_seg_fault, msg)
|
||||
|
||||
def testDefaultBehavior(self):
|
||||
"""Tests the behavior of the default mode."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
|
||||
def testEnvVar(self):
|
||||
"""Tests using the GTEST_BREAK_ON_FAILURE environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value=None,
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value=None,
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlag(self):
|
||||
"""Tests using the --gtest_break_on_failure flag."""
|
||||
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testFlagOverridesEnvVar(self):
|
||||
"""Tests that the flag overrides the environment variable."""
|
||||
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='0',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='0',
|
||||
expect_seg_fault=0)
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
|
||||
def testBreakOnFailureOverridesThrowOnFailure(self):
|
||||
"""Tests that gtest_break_on_failure overrides gtest_throw_on_failure."""
|
||||
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value=None,
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)
|
||||
|
||||
if IS_WINDOWS:
|
||||
def testCatchExceptionsDoesNotInterfere(self):
|
||||
"""Tests that gtest_catch_exceptions doesn't interfere."""
|
||||
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')
|
||||
try:
|
||||
self.RunAndVerify(env_var_value='1',
|
||||
flag_value='1',
|
||||
expect_seg_fault=1)
|
||||
finally:
|
||||
SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
// Unit test for Google Test's break-on-failure mode.
|
||||
//
|
||||
// A user can ask Google Test to seg-fault when an assertion fails, using
|
||||
// either the GTEST_BREAK_ON_FAILURE environment variable or the
|
||||
// --gtest_break_on_failure flag. This file is used for testing such
|
||||
// functionality.
|
||||
//
|
||||
// This program will be invoked from a Python unit test. It is
|
||||
// expected to fail. Don't run it directly.
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
# include <windows.h>
|
||||
# include <stdlib.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
// A test that's expected to fail.
|
||||
TEST(Foo, Bar) {
|
||||
EXPECT_EQ(2, 3);
|
||||
}
|
||||
|
||||
#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
|
||||
// On Windows Mobile global exception handlers are not supported.
|
||||
LONG WINAPI ExitWithExceptionCode(
|
||||
struct _EXCEPTION_POINTERS* exception_pointers) {
|
||||
exit(exception_pointers->ExceptionRecord->ExceptionCode);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
#if GTEST_OS_WINDOWS
|
||||
// Suppresses display of the Windows error dialog upon encountering
|
||||
// a general protection fault (segment violation).
|
||||
SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
|
||||
|
||||
# if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
// The default unhandled exception filter does not always exit
|
||||
// with the exception code as exit code - for example it exits with
|
||||
// 0 for EXCEPTION_ACCESS_VIOLATION and 1 for EXCEPTION_BREAKPOINT
|
||||
// if the application is compiled in debug mode. Thus we use our own
|
||||
// filter which always exits with the exception code for unhandled
|
||||
// exceptions.
|
||||
SetUnhandledExceptionFilter(ExitWithExceptionCode);
|
||||
|
||||
# endif
|
||||
#endif
|
||||
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
|
|
@ -1,237 +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 Google Test's exception catching behavior.
|
||||
|
||||
This script invokes gtest_catch_exceptions_test_ and
|
||||
gtest_catch_exceptions_ex_test_ (programs written with
|
||||
Google Test) and verifies their output.
|
||||
"""
|
||||
|
||||
__author__ = 'vladl@google.com (Vlad Losev)'
|
||||
|
||||
import os
|
||||
|
||||
import gtest_test_utils
|
||||
|
||||
# Constants.
|
||||
FLAG_PREFIX = '--gtest_'
|
||||
LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'
|
||||
NO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0'
|
||||
FILTER_FLAG = FLAG_PREFIX + 'filter'
|
||||
|
||||
# Path to the gtest_catch_exceptions_ex_test_ binary, compiled with
|
||||
# exceptions enabled.
|
||||
EX_EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'gtest_catch_exceptions_ex_test_')
|
||||
|
||||
# Path to the gtest_catch_exceptions_test_ binary, compiled with
|
||||
# exceptions disabled.
|
||||
EXE_PATH = gtest_test_utils.GetTestExecutablePath(
|
||||
'gtest_catch_exceptions_no_ex_test_')
|
||||
|
||||
environ = gtest_test_utils.environ
|
||||
SetEnvVar = gtest_test_utils.SetEnvVar
|
||||
|
||||
# Tests in this file run a Google-Test-based test program and expect it
|
||||
# to terminate prematurely. Therefore they are incompatible with
|
||||
# the premature-exit-file protocol by design. Unset the
|
||||
# premature-exit filepath to prevent Google Test from creating
|
||||
# the file.
|
||||
SetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
|
||||
|
||||
TEST_LIST = gtest_test_utils.Subprocess(
|
||||
[EXE_PATH, LIST_TESTS_FLAG], env=environ).output
|
||||
|
||||
SUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST
|
||||
|
||||
if SUPPORTS_SEH_EXCEPTIONS:
|
||||
BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output
|
||||
|
||||
EX_BINARY_OUTPUT = gtest_test_utils.Subprocess(
|
||||
[EX_EXE_PATH], env=environ).output
|
||||
|
||||
|
||||
# The tests.
|
||||
if SUPPORTS_SEH_EXCEPTIONS:
|
||||
# pylint:disable-msg=C6302
|
||||
class CatchSehExceptionsTest(gtest_test_utils.TestCase):
|
||||
"""Tests exception-catching behavior."""
|
||||
|
||||
|
||||
def TestSehExceptions(self, test_output):
|
||||
self.assert_('SEH exception with code 0x2a thrown '
|
||||
'in the test fixture\'s constructor'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown '
|
||||
'in the test fixture\'s destructor'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in SetUpTestCase()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in TearDownTestCase()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in SetUp()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in TearDown()'
|
||||
in test_output)
|
||||
self.assert_('SEH exception with code 0x2a thrown in the test body'
|
||||
in test_output)
|
||||
|
||||
def testCatchesSehExceptionsWithCxxExceptionsEnabled(self):
|
||||
self.TestSehExceptions(EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesSehExceptionsWithCxxExceptionsDisabled(self):
|
||||
self.TestSehExceptions(BINARY_OUTPUT)
|
||||
|
||||
|
||||
class CatchCxxExceptionsTest(gtest_test_utils.TestCase):
|
||||
"""Tests C++ exception-catching behavior.
|
||||
|
||||
Tests in this test case verify that:
|
||||
* C++ exceptions are caught and logged as C++ (not SEH) exceptions
|
||||
* Exception thrown affect the remainder of the test work flow in the
|
||||
expected manner.
|
||||
"""
|
||||
|
||||
def testCatchesCxxExceptionsInFixtureConstructor(self):
|
||||
self.assert_('C++ exception with description '
|
||||
'"Standard C++ exception" thrown '
|
||||
'in the test fixture\'s constructor'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('unexpected' not in EX_BINARY_OUTPUT,
|
||||
'This failure belongs in this test only if '
|
||||
'"CxxExceptionInConstructorTest" (no quotes) '
|
||||
'appears on the same line as words "called unexpectedly"')
|
||||
|
||||
if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in
|
||||
EX_BINARY_OUTPUT):
|
||||
|
||||
def testCatchesCxxExceptionsInFixtureDestructor(self):
|
||||
self.assert_('C++ exception with description '
|
||||
'"Standard C++ exception" thrown '
|
||||
'in the test fixture\'s destructor'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInDestructorTest::TearDownTestCase() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInSetUpTestCase(self):
|
||||
self.assert_('C++ exception with description "Standard C++ exception"'
|
||||
' thrown in SetUpTestCase()'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInConstructorTest::TearDownTestCase() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTestCaseTest constructor '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTestCaseTest destructor '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTestCaseTest::SetUp() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTestCaseTest::TearDown() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTestCaseTest test body '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInTearDownTestCase(self):
|
||||
self.assert_('C++ exception with description "Standard C++ exception"'
|
||||
' thrown in TearDownTestCase()'
|
||||
in EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInSetUp(self):
|
||||
self.assert_('C++ exception with description "Standard C++ exception"'
|
||||
' thrown in SetUp()'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTest::TearDownTestCase() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTest destructor '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInSetUpTest::TearDown() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('unexpected' not in EX_BINARY_OUTPUT,
|
||||
'This failure belongs in this test only if '
|
||||
'"CxxExceptionInSetUpTest" (no quotes) '
|
||||
'appears on the same line as words "called unexpectedly"')
|
||||
|
||||
def testCatchesCxxExceptionsInTearDown(self):
|
||||
self.assert_('C++ exception with description "Standard C++ exception"'
|
||||
' thrown in TearDown()'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInTearDownTest::TearDownTestCase() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInTearDownTest destructor '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesCxxExceptionsInTestBody(self):
|
||||
self.assert_('C++ exception with description "Standard C++ exception"'
|
||||
' thrown in the test body'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInTestBodyTest::TearDownTestCase() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInTestBodyTest destructor '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
self.assert_('CxxExceptionInTestBodyTest::TearDown() '
|
||||
'called as expected.'
|
||||
in EX_BINARY_OUTPUT)
|
||||
|
||||
def testCatchesNonStdCxxExceptions(self):
|
||||
self.assert_('Unknown C++ exception thrown in the test body'
|
||||
in EX_BINARY_OUTPUT)
|
||||
|
||||
def testUnhandledCxxExceptionsAbortTheProgram(self):
|
||||
# Filters out SEH exception tests on Windows. Unhandled SEH exceptions
|
||||
# cause tests to show pop-up windows there.
|
||||
FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*'
|
||||
# By default, Google Test doesn't catch the exceptions.
|
||||
uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess(
|
||||
[EX_EXE_PATH,
|
||||
NO_CATCH_EXCEPTIONS_FLAG,
|
||||
FITLER_OUT_SEH_TESTS_FLAG],
|
||||
env=environ).output
|
||||
|
||||
self.assert_('Unhandled C++ exception terminating the program'
|
||||
in uncaught_exceptions_ex_binary_output)
|
||||
self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
|
@ -1,311 +0,0 @@
|
|||
// 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.
|
||||
//
|
||||
// Author: vladl@google.com (Vlad Losev)
|
||||
//
|
||||
// Tests for Google Test itself. Tests in this file throw C++ or SEH
|
||||
// exceptions, and the output is verified by gtest_catch_exceptions_test.py.
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#include <stdio.h> // NOLINT
|
||||
#include <stdlib.h> // For exit().
|
||||
|
||||
#if GTEST_HAS_SEH
|
||||
# include <windows.h>
|
||||
#endif
|
||||
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
# include <exception> // For set_terminate().
|
||||
# include <stdexcept>
|
||||
#endif
|
||||
|
||||
using testing::Test;
|
||||
|
||||
#if GTEST_HAS_SEH
|
||||
|
||||
class SehExceptionInConstructorTest : public Test {
|
||||
public:
|
||||
SehExceptionInConstructorTest() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInConstructorTest, ThrowsExceptionInConstructor) {}
|
||||
|
||||
class SehExceptionInDestructorTest : public Test {
|
||||
public:
|
||||
~SehExceptionInDestructorTest() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInDestructorTest, ThrowsExceptionInDestructor) {}
|
||||
|
||||
class SehExceptionInSetUpTestCaseTest : public Test {
|
||||
public:
|
||||
static void SetUpTestCase() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) {}
|
||||
|
||||
class SehExceptionInTearDownTestCaseTest : public Test {
|
||||
public:
|
||||
static void TearDownTestCase() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {}
|
||||
|
||||
class SehExceptionInSetUpTest : public Test {
|
||||
protected:
|
||||
virtual void SetUp() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInSetUpTest, ThrowsExceptionInSetUp) {}
|
||||
|
||||
class SehExceptionInTearDownTest : public Test {
|
||||
protected:
|
||||
virtual void TearDown() { RaiseException(42, 0, 0, NULL); }
|
||||
};
|
||||
|
||||
TEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
|
||||
|
||||
TEST(SehExceptionTest, ThrowsSehException) {
|
||||
RaiseException(42, 0, 0, NULL);
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_SEH
|
||||
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
|
||||
class CxxExceptionInConstructorTest : public Test {
|
||||
public:
|
||||
CxxExceptionInConstructorTest() {
|
||||
// Without this macro VC++ complains about unreachable code at the end of
|
||||
// the constructor.
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
|
||||
throw std::runtime_error("Standard C++ exception"));
|
||||
}
|
||||
|
||||
static void TearDownTestCase() {
|
||||
printf("%s",
|
||||
"CxxExceptionInConstructorTest::TearDownTestCase() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInConstructorTest() {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest destructor "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
virtual void SetUp() {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest::SetUp() "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest::TearDown() "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInConstructorTest, ThrowsExceptionInConstructor) {
|
||||
ADD_FAILURE() << "CxxExceptionInConstructorTest test body "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
// Exceptions in destructors are not supported in C++11.
|
||||
#if !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L
|
||||
class CxxExceptionInDestructorTest : public Test {
|
||||
public:
|
||||
static void TearDownTestCase() {
|
||||
printf("%s",
|
||||
"CxxExceptionInDestructorTest::TearDownTestCase() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInDestructorTest() {
|
||||
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(
|
||||
throw std::runtime_error("Standard C++ exception"));
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInDestructorTest, ThrowsExceptionInDestructor) {}
|
||||
#endif // C++11 mode
|
||||
|
||||
class CxxExceptionInSetUpTestCaseTest : public Test {
|
||||
public:
|
||||
CxxExceptionInSetUpTestCaseTest() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestCaseTest constructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
static void SetUpTestCase() {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
|
||||
static void TearDownTestCase() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestCaseTest::TearDownTestCase() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInSetUpTestCaseTest() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestCaseTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
virtual void SetUp() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestCaseTest::SetUp() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestCaseTest::TearDown() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInSetUpTestCaseTest, ThrowsExceptionInSetUpTestCase) {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTestCaseTest test body "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
class CxxExceptionInTearDownTestCaseTest : public Test {
|
||||
public:
|
||||
static void TearDownTestCase() {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInTearDownTestCaseTest, ThrowsExceptionInTearDownTestCase) {}
|
||||
|
||||
class CxxExceptionInSetUpTest : public Test {
|
||||
public:
|
||||
static void TearDownTestCase() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTest::TearDownTestCase() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInSetUpTest() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
virtual void SetUp() { throw std::runtime_error("Standard C++ exception"); }
|
||||
|
||||
virtual void TearDown() {
|
||||
printf("%s",
|
||||
"CxxExceptionInSetUpTest::TearDown() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInSetUpTest, ThrowsExceptionInSetUp) {
|
||||
ADD_FAILURE() << "CxxExceptionInSetUpTest test body "
|
||||
<< "called unexpectedly.";
|
||||
}
|
||||
|
||||
class CxxExceptionInTearDownTest : public Test {
|
||||
public:
|
||||
static void TearDownTestCase() {
|
||||
printf("%s",
|
||||
"CxxExceptionInTearDownTest::TearDownTestCase() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInTearDownTest() {
|
||||
printf("%s",
|
||||
"CxxExceptionInTearDownTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInTearDownTest, ThrowsExceptionInTearDown) {}
|
||||
|
||||
class CxxExceptionInTestBodyTest : public Test {
|
||||
public:
|
||||
static void TearDownTestCase() {
|
||||
printf("%s",
|
||||
"CxxExceptionInTestBodyTest::TearDownTestCase() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
protected:
|
||||
~CxxExceptionInTestBodyTest() {
|
||||
printf("%s",
|
||||
"CxxExceptionInTestBodyTest destructor "
|
||||
"called as expected.\n");
|
||||
}
|
||||
|
||||
virtual void TearDown() {
|
||||
printf("%s",
|
||||
"CxxExceptionInTestBodyTest::TearDown() "
|
||||
"called as expected.\n");
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {
|
||||
throw std::runtime_error("Standard C++ exception");
|
||||
}
|
||||
|
||||
TEST(CxxExceptionTest, ThrowsNonStdCxxException) {
|
||||
throw "C-string";
|
||||
}
|
||||
|
||||
// This terminate handler aborts the program using exit() rather than abort().
|
||||
// This avoids showing pop-ups on Windows systems and core dumps on Unix-like
|
||||
// ones.
|
||||
void TerminateHandler() {
|
||||
fprintf(stderr, "%s\n", "Unhandled C++ exception terminating the program.");
|
||||
fflush(NULL);
|
||||
exit(3);
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_EXCEPTIONS
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
std::set_terminate(&TerminateHandler);
|
||||
#endif
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
|
|
@ -1,130 +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.
|
||||
|
||||
"""Verifies that Google Test correctly determines whether to use colors."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import gtest_test_utils
|
||||
|
||||
|
||||
IS_WINDOWS = os.name = 'nt'
|
||||
|
||||
COLOR_ENV_VAR = 'GTEST_COLOR'
|
||||
COLOR_FLAG = 'gtest_color'
|
||||
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_')
|
||||
|
||||
|
||||
def SetEnvVar(env_var, value):
|
||||
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
|
||||
|
||||
if value is not None:
|
||||
os.environ[env_var] = value
|
||||
elif env_var in os.environ:
|
||||
del os.environ[env_var]
|
||||
|
||||
|
||||
def UsesColor(term, color_env_var, color_flag):
|
||||
"""Runs gtest_color_test_ and returns its exit code."""
|
||||
|
||||
SetEnvVar('TERM', term)
|
||||
SetEnvVar(COLOR_ENV_VAR, color_env_var)
|
||||
|
||||
if color_flag is None:
|
||||
args = []
|
||||
else:
|
||||
args = ['--%s=%s' % (COLOR_FLAG, color_flag)]
|
||||
p = gtest_test_utils.Subprocess([COMMAND] + args)
|
||||
return not p.exited or p.exit_code
|
||||
|
||||
|
||||
class GTestColorTest(gtest_test_utils.TestCase):
|
||||
def testNoEnvVarNoFlag(self):
|
||||
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
|
||||
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', None, None))
|
||||
self.assert_(not UsesColor('emacs', None, None))
|
||||
self.assert_(not UsesColor('xterm-mono', None, None))
|
||||
self.assert_(not UsesColor('unknown', None, None))
|
||||
self.assert_(not UsesColor(None, None, None))
|
||||
self.assert_(UsesColor('linux', None, None))
|
||||
self.assert_(UsesColor('cygwin', None, None))
|
||||
self.assert_(UsesColor('xterm', None, None))
|
||||
self.assert_(UsesColor('xterm-color', None, None))
|
||||
self.assert_(UsesColor('xterm-256color', None, None))
|
||||
|
||||
def testFlagOnly(self):
|
||||
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', None, 'no'))
|
||||
self.assert_(not UsesColor('xterm-color', None, 'no'))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('emacs', None, 'auto'))
|
||||
self.assert_(UsesColor('xterm', None, 'auto'))
|
||||
self.assert_(UsesColor('dumb', None, 'yes'))
|
||||
self.assert_(UsesColor('xterm', None, 'yes'))
|
||||
|
||||
def testEnvVarOnly(self):
|
||||
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('dumb', 'no', None))
|
||||
self.assert_(not UsesColor('xterm-color', 'no', None))
|
||||
if not IS_WINDOWS:
|
||||
self.assert_(not UsesColor('dumb', 'auto', None))
|
||||
self.assert_(UsesColor('xterm-color', 'auto', None))
|
||||
self.assert_(UsesColor('dumb', 'yes', None))
|
||||
self.assert_(UsesColor('xterm-color', 'yes', None))
|
||||
|
||||
def testEnvVarAndFlag(self):
|
||||
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
|
||||
|
||||
self.assert_(not UsesColor('xterm-color', 'no', 'no'))
|
||||
self.assert_(UsesColor('dumb', 'no', 'yes'))
|
||||
self.assert_(UsesColor('xterm-color', 'no', 'auto'))
|
||||
|
||||
def testAliasesOfYesAndNo(self):
|
||||
"""Tests using aliases in specifying --gtest_color."""
|
||||
|
||||
self.assert_(UsesColor('dumb', None, 'true'))
|
||||
self.assert_(UsesColor('dumb', None, 'YES'))
|
||||
self.assert_(UsesColor('dumb', None, 'T'))
|
||||
self.assert_(UsesColor('dumb', None, '1'))
|
||||
|
||||
self.assert_(not UsesColor('xterm', None, 'f'))
|
||||
self.assert_(not UsesColor('xterm', None, 'false'))
|
||||
self.assert_(not UsesColor('xterm', None, '0'))
|
||||
self.assert_(not UsesColor('xterm', None, 'unknown'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
gtest_test_utils.Main()
|
||||
|
|
@ -1,71 +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.
|
||||
//
|
||||
// Author: wan@google.com (Zhanyong Wan)
|
||||
|
||||
// A helper program for testing how Google Test determines whether to use
|
||||
// colors in the output. It prints "YES" and returns 1 if Google Test
|
||||
// decides to use colors, and prints "NO" and returns 0 otherwise.
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
// Indicates that this translation unit is part of Google Test's
|
||||
// implementation. It must come before gtest-internal-inl.h is
|
||||
// included, or there will be a compiler error. This trick is to
|
||||
// prevent a user from accidentally including gtest-internal-inl.h in
|
||||
// his code.
|
||||
#define GTEST_IMPLEMENTATION_ 1
|
||||
#include "src/gtest-internal-inl.h"
|
||||
#undef GTEST_IMPLEMENTATION_
|
||||
|
||||
using testing::internal::ShouldUseColor;
|
||||
|
||||
// The purpose of this is to ensure that the UnitTest singleton is
|
||||
// created before main() is entered, and thus that ShouldUseColor()
|
||||
// works the same way as in a real Google-Test-based test. We don't actual
|
||||
// run the TEST itself.
|
||||
TEST(GTestColorTest, Dummy) {
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
|
||||
if (ShouldUseColor(true)) {
|
||||
// Google Test decides to use colors in the output (assuming it
|
||||
// goes to a TTY).
|
||||
printf("YES\n");
|
||||
return 1;
|
||||
} else {
|
||||
// Google Test decides not to use colors in the output.
|
||||
printf("NO\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue