update google testing framework to 1.8.1
This commit is contained in:
parent
e8d7cd3f10
commit
c55ec076f3
|
@ -1,3 +1,37 @@
|
|||
Changes for 1.7.0:
|
||||
|
||||
* All new improvements in Google Test 1.7.0.
|
||||
* New feature: matchers DoubleNear(), FloatNear(),
|
||||
NanSensitiveDoubleNear(), NanSensitiveFloatNear(),
|
||||
UnorderedElementsAre(), UnorderedElementsAreArray(), WhenSorted(),
|
||||
WhenSortedBy(), IsEmpty(), and SizeIs().
|
||||
* Improvement: Google Mock can now be built as a DLL.
|
||||
* Improvement: when compiled by a C++11 compiler, matchers AllOf()
|
||||
and AnyOf() can accept an arbitrary number of matchers.
|
||||
* Improvement: when compiled by a C++11 compiler, matchers
|
||||
ElementsAreArray() can accept an initializer list.
|
||||
* Improvement: when exceptions are enabled, a mock method with no
|
||||
default action now throws instead crashing the test.
|
||||
* Improvement: added class testing::StringMatchResultListener to aid
|
||||
definition of composite matchers.
|
||||
* Improvement: function return types used in MOCK_METHOD*() macros can
|
||||
now contain unprotected commas.
|
||||
* Improvement (potentially breaking): EXPECT_THAT() and ASSERT_THAT()
|
||||
are now more strict in ensuring that the value type and the matcher
|
||||
type are compatible, catching potential bugs in tests.
|
||||
* Improvement: Pointee() now works on an optional<T>.
|
||||
* Improvement: the ElementsAreArray() matcher can now take a vector or
|
||||
iterator range as input, and makes a copy of its input elements
|
||||
before the conversion to a Matcher.
|
||||
* Improvement: the Google Mock Generator can now generate mocks for
|
||||
some class templates.
|
||||
* Bug fix: mock object destruction triggerred by another mock object's
|
||||
destruction no longer hangs.
|
||||
* Improvement: Google Mock Doctor works better with newer Clang and
|
||||
GCC now.
|
||||
* Compatibility fixes.
|
||||
* Bug/warning fixes.
|
||||
|
||||
Changes for 1.6.0:
|
||||
|
||||
* Compilation is much faster and uses much less memory, especially
|
||||
|
@ -60,7 +94,7 @@ Google Test):
|
|||
* New feature: --gmock_catch_leaked_mocks for detecting leaked mocks.
|
||||
* New feature: ACTION_TEMPLATE for defining templatized actions.
|
||||
* New feature: the .After() clause for specifying expectation order.
|
||||
* New feature: the .With() clause for for specifying inter-argument
|
||||
* New feature: the .With() clause for specifying inter-argument
|
||||
constraints.
|
||||
* New feature: actions ReturnArg<k>(), ReturnNew<T>(...), and
|
||||
DeleteArg<k>().
|
||||
|
|
|
@ -5,22 +5,13 @@
|
|||
# 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)
|
||||
|
||||
# Forces BUILD_SHARED_LIBS to OFF as Google Mock currently does not support
|
||||
# working in a DLL.
|
||||
# TODO(vladl@google.com): Implement building gMock as a DLL.
|
||||
set(BUILD_SHARED_LIBS OFF)
|
||||
|
||||
option(gmock_build_tests "Build all of Google Mock's own tests." OFF)
|
||||
|
||||
# A directory to find Google Test sources.
|
||||
if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt")
|
||||
set(gtest_dir gtest)
|
||||
else()
|
||||
set(gtest_dir ../gtest)
|
||||
set(gtest_dir ../googletest)
|
||||
endif()
|
||||
|
||||
# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().
|
||||
|
@ -42,8 +33,13 @@ endif()
|
|||
# as ${gmock_SOURCE_DIR} and to the root binary directory as
|
||||
# ${gmock_BINARY_DIR}.
|
||||
# Language "C" is required for find_package(Threads).
|
||||
project(gmock CXX C)
|
||||
cmake_minimum_required(VERSION 2.6.2)
|
||||
if (CMAKE_VERSION VERSION_LESS 3.0)
|
||||
project(gmock CXX C)
|
||||
else()
|
||||
cmake_policy(SET CMP0048 NEW)
|
||||
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
|
||||
endif()
|
||||
cmake_minimum_required(VERSION 2.6.4)
|
||||
|
||||
if (COMMAND set_up_hermetic_build)
|
||||
set_up_hermetic_build()
|
||||
|
@ -55,18 +51,41 @@ endif()
|
|||
# if they are the same (the default).
|
||||
add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/gtest")
|
||||
|
||||
|
||||
# These commands only run if this is the main project
|
||||
if(CMAKE_PROJECT_NAME STREQUAL "gmock" 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(gmock_build_tests)
|
||||
endif()
|
||||
|
||||
# Although Google Test's CMakeLists.txt calls this function, the
|
||||
# changes there don't affect the current scope. Therefore we have to
|
||||
# call it again here.
|
||||
config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake
|
||||
|
||||
# Adds Google Mock's and Google Test's header directories to the search path.
|
||||
include_directories("${gmock_SOURCE_DIR}/include"
|
||||
"${gmock_SOURCE_DIR}"
|
||||
"${gtest_SOURCE_DIR}/include"
|
||||
# This directory is needed to build directly from Google
|
||||
# Test sources.
|
||||
"${gtest_SOURCE_DIR}")
|
||||
set(gmock_build_include_dirs
|
||||
"${gmock_SOURCE_DIR}/include"
|
||||
"${gmock_SOURCE_DIR}"
|
||||
"${gtest_SOURCE_DIR}/include"
|
||||
# This directory is needed to build directly from Google Test sources.
|
||||
"${gtest_SOURCE_DIR}")
|
||||
include_directories(${gmock_build_include_dirs})
|
||||
|
||||
# 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
|
||||
# VS 2015 14 1900 std::tuple
|
||||
# VS 2017 15 >= 1910 std::tuple
|
||||
if (MSVC AND MSVC_VERSION EQUAL 1700)
|
||||
add_definitions(/D _VARIADIC_MAX=10)
|
||||
endif()
|
||||
|
||||
########################################################################
|
||||
#
|
||||
|
@ -76,11 +95,39 @@ include_directories("${gmock_SOURCE_DIR}/include"
|
|||
# Google Mock libraries. We build them using more strict warnings than what
|
||||
# are used for other targets, to ensure that Google Mock can be compiled by
|
||||
# a user aggressive about warnings.
|
||||
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
|
||||
target_link_libraries(gmock gtest)
|
||||
if (MSVC)
|
||||
cxx_library(gmock
|
||||
"${cxx_strict}"
|
||||
"${gtest_dir}/src/gtest-all.cc"
|
||||
src/gmock-all.cc)
|
||||
|
||||
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main gmock)
|
||||
cxx_library(gmock_main
|
||||
"${cxx_strict}"
|
||||
"${gtest_dir}/src/gtest-all.cc"
|
||||
src/gmock-all.cc
|
||||
src/gmock_main.cc)
|
||||
else()
|
||||
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
|
||||
target_link_libraries(gmock PUBLIC gtest)
|
||||
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main PUBLIC gmock)
|
||||
endif()
|
||||
# If the CMake version supports it, attach header directory information
|
||||
# to the targets for when we are part of a parent build (ie being pulled
|
||||
# in via add_subdirectory() rather than being a standalone build).
|
||||
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
|
||||
target_include_directories(gmock SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_include_directories(gmock_main SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
endif()
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Install rules
|
||||
install_project(gmock gmock_main)
|
||||
|
||||
########################################################################
|
||||
#
|
||||
|
@ -103,6 +150,7 @@ if (gmock_build_tests)
|
|||
|
||||
cxx_test(gmock-actions_test gmock_main)
|
||||
cxx_test(gmock-cardinalities_test gmock_main)
|
||||
cxx_test(gmock_ex_test gmock_main)
|
||||
cxx_test(gmock-generated-actions_test gmock_main)
|
||||
cxx_test(gmock-generated-function-mockers_test gmock_main)
|
||||
cxx_test(gmock-generated-internal-utils_test gmock_main)
|
||||
|
@ -114,9 +162,12 @@ if (gmock_build_tests)
|
|||
cxx_test(gmock-port_test gmock_main)
|
||||
cxx_test(gmock-spec-builders_test gmock_main)
|
||||
cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc)
|
||||
# cxx_test(gmock_stress_test gmock)
|
||||
cxx_test(gmock_test gmock_main)
|
||||
|
||||
if (DEFINED GTEST_HAS_PTHREAD)
|
||||
cxx_test(gmock_stress_test gmock)
|
||||
endif()
|
||||
|
||||
# gmock_all_test is commented to save time building and running tests.
|
||||
# Uncomment if necessary.
|
||||
# cxx_test(gmock_all_test gmock_main)
|
||||
|
@ -124,21 +175,52 @@ if (gmock_build_tests)
|
|||
############################################################
|
||||
# C++ tests built with non-standard compiler flags.
|
||||
|
||||
cxx_library(gmock_main_no_exception "${cxx_no_exception}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
if (MSVC)
|
||||
cxx_library(gmock_main_no_exception "${cxx_no_exception}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
|
||||
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
|
||||
if (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(gmock_main_use_own_tuple "${cxx_use_own_tuple}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
|
||||
cxx_test_with_flags(gmock_use_own_tuple_test "${cxx_use_own_tuple}"
|
||||
gmock_main_use_own_tuple test/gmock-spec-builders_test.cc)
|
||||
endif()
|
||||
else()
|
||||
cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main_no_exception PUBLIC gmock)
|
||||
|
||||
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main_no_rtti PUBLIC gmock)
|
||||
|
||||
cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main_use_own_tuple PUBLIC gmock)
|
||||
endif()
|
||||
cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}"
|
||||
gmock_main_no_exception test/gmock-more-actions_test.cc)
|
||||
|
||||
cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}"
|
||||
gmock_main_no_rtti test/gmock-spec-builders_test.cc)
|
||||
|
||||
cxx_test_with_flags(gmock_use_own_tuple_test "${cxx_use_own_tuple}"
|
||||
gmock_main_use_own_tuple test/gmock-spec-builders_test.cc)
|
||||
cxx_shared_library(shared_gmock_main "${cxx_default}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
|
||||
# Tests that a binary can be built with Google Mock as a shared library. On
|
||||
# some system configurations, it may not possible to run the binary without
|
||||
# knowing more details about the system configurations. We do not try to run
|
||||
# this binary. To get a more robust shared library coverage, configure with
|
||||
# -DBUILD_SHARED_LIBS=ON.
|
||||
cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}"
|
||||
shared_gmock_main test/gmock-spec-builders_test.cc)
|
||||
set_target_properties(shared_gmock_test_
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
|
||||
|
||||
############################################################
|
||||
# Python tests.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
# Automake file
|
||||
|
||||
# Nonstandard package files for distribution.
|
||||
EXTRA_DIST =
|
||||
EXTRA_DIST = LICENSE
|
||||
|
||||
# We may need to build our internally packaged gtest. If so, it will be
|
||||
# included in the 'subdirs' variable.
|
||||
|
@ -34,6 +34,7 @@ pkginclude_HEADERS = \
|
|||
include/gmock/gmock-generated-nice-strict.h \
|
||||
include/gmock/gmock-matchers.h \
|
||||
include/gmock/gmock-more-actions.h \
|
||||
include/gmock/gmock-more-matchers.h \
|
||||
include/gmock/gmock-spec-builders.h \
|
||||
include/gmock/gmock.h
|
||||
|
||||
|
@ -41,7 +42,10 @@ pkginclude_internaldir = $(pkgincludedir)/internal
|
|||
pkginclude_internal_HEADERS = \
|
||||
include/gmock/internal/gmock-generated-internal-utils.h \
|
||||
include/gmock/internal/gmock-internal-utils.h \
|
||||
include/gmock/internal/gmock-port.h
|
||||
include/gmock/internal/gmock-port.h \
|
||||
include/gmock/internal/custom/gmock-generated-actions.h \
|
||||
include/gmock/internal/custom/gmock-matchers.h \
|
||||
include/gmock/internal/custom/gmock-port.h
|
||||
|
||||
lib_libgmock_main_la_SOURCES = src/gmock_main.cc
|
||||
lib_libgmock_main_la_LIBADD = lib/libgmock.la
|
||||
|
@ -73,16 +77,18 @@ test_gmock_link_test_SOURCES = \
|
|||
test/gmock_link_test.h
|
||||
test_gmock_link_test_LDADD = $(GTEST_LIBS) lib/libgmock_main.la lib/libgmock.la
|
||||
|
||||
# Tests that fused gmock files compile and work.
|
||||
TESTS += test/gmock_fused_test
|
||||
check_PROGRAMS += test/gmock_fused_test
|
||||
test_gmock_fused_test_SOURCES = \
|
||||
fused-src/gmock-gtest-all.cc \
|
||||
fused-src/gmock/gmock.h \
|
||||
fused-src/gmock_main.cc \
|
||||
fused-src/gtest/gtest.h \
|
||||
test/gmock_test.cc
|
||||
test_gmock_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src"
|
||||
if HAVE_PYTHON
|
||||
# Tests that fused gmock files compile and work.
|
||||
TESTS += test/gmock_fused_test
|
||||
check_PROGRAMS += test/gmock_fused_test
|
||||
test_gmock_fused_test_SOURCES = \
|
||||
fused-src/gmock-gtest-all.cc \
|
||||
fused-src/gmock/gmock.h \
|
||||
fused-src/gmock_main.cc \
|
||||
fused-src/gtest/gtest.h \
|
||||
test/gmock_test.cc
|
||||
test_gmock_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src"
|
||||
endif
|
||||
|
||||
# Google Mock source files that we don't compile directly.
|
||||
GMOCK_SOURCE_INGLUDES = \
|
||||
|
@ -97,7 +103,9 @@ EXTRA_DIST += $(GMOCK_SOURCE_INGLUDES)
|
|||
# C++ tests that we don't compile using autotools.
|
||||
EXTRA_DIST += \
|
||||
test/gmock-actions_test.cc \
|
||||
test/gmock_all_test.cc \
|
||||
test/gmock-cardinalities_test.cc \
|
||||
test/gmock_ex_test.cc \
|
||||
test/gmock-generated-actions_test.cc \
|
||||
test/gmock-generated-function-mockers_test.cc \
|
||||
test/gmock-generated-internal-utils_test.cc \
|
||||
|
@ -107,7 +115,7 @@ EXTRA_DIST += \
|
|||
test/gmock-more-actions_test.cc \
|
||||
test/gmock-nice-strict_test.cc \
|
||||
test/gmock-port_test.cc \
|
||||
test/gmock_all_test.cc
|
||||
test/gmock_stress_test.cc
|
||||
|
||||
# Python tests, which we don't run using autotools.
|
||||
EXTRA_DIST += \
|
||||
|
@ -131,14 +139,15 @@ EXTRA_DIST += \
|
|||
include/gmock/gmock-generated-function-mockers.h.pump \
|
||||
include/gmock/gmock-generated-matchers.h.pump \
|
||||
include/gmock/gmock-generated-nice-strict.h.pump \
|
||||
include/gmock/internal/gmock-generated-internal-utils.h.pump
|
||||
include/gmock/internal/gmock-generated-internal-utils.h.pump \
|
||||
include/gmock/internal/custom/gmock-generated-actions.h.pump
|
||||
|
||||
# Script for fusing Google Mock and Google Test source files.
|
||||
EXTRA_DIST += scripts/fuse_gmock_files.py
|
||||
|
||||
# The Google Mock Generator tool from the cppclean project.
|
||||
EXTRA_DIST += \
|
||||
scripts/generator/COPYING \
|
||||
scripts/generator/LICENSE \
|
||||
scripts/generator/README \
|
||||
scripts/generator/README.cppclean \
|
||||
scripts/generator/cpp/__init__.py \
|
||||
|
@ -149,6 +158,10 @@ EXTRA_DIST += \
|
|||
scripts/generator/cpp/utils.py \
|
||||
scripts/generator/gmock_gen.py
|
||||
|
||||
# Script for diagnosing compiler errors in programs that use Google
|
||||
# Mock.
|
||||
EXTRA_DIST += scripts/gmock_doctor.py
|
||||
|
||||
# CMake scripts.
|
||||
EXTRA_DIST += \
|
||||
CMakeLists.txt
|
||||
|
@ -169,6 +182,7 @@ EXTRA_DIST += \
|
|||
msvc/2010/gmock_main.vcxproj \
|
||||
msvc/2010/gmock_test.vcxproj
|
||||
|
||||
if HAVE_PYTHON
|
||||
# gmock_test.cc does not really depend on files generated by the
|
||||
# fused-gmock-internal rule. However, gmock_test.o does, and it is
|
||||
# important to include test/gmock_test.cc as part of this rule in order to
|
||||
|
@ -191,6 +205,7 @@ fused-gmock-internal: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \
|
|||
|
||||
maintainer-clean-local:
|
||||
rm -rf "$(srcdir)/fused-src"
|
||||
endif
|
||||
|
||||
# Death tests may produce core dumps in the build directory. In case
|
||||
# this happens, clean them to keep distcleancheck happy.
|
||||
|
|
File diff suppressed because it is too large
Load Diff
354
ext/gmock/README
354
ext/gmock/README
|
@ -1,354 +0,0 @@
|
|||
Google C++ Mocking Framework
|
||||
============================
|
||||
|
||||
http://code.google.com/p/googlemock/
|
||||
|
||||
Overview
|
||||
--------
|
||||
|
||||
Google's framework for writing and using C++ mock classes on a variety
|
||||
of platforms (Linux, Mac OS X, Windows, Windows CE, Symbian, etc).
|
||||
Inspired by jMock, EasyMock, and Hamcrest, and designed with C++'s
|
||||
specifics in mind, it can help you derive better designs of your
|
||||
system and write better tests.
|
||||
|
||||
Google Mock:
|
||||
|
||||
- provides a declarative syntax for defining mocks,
|
||||
- can easily define partial (hybrid) mocks, which are a cross of real
|
||||
and mock objects,
|
||||
- handles functions of arbitrary types and overloaded functions,
|
||||
- comes with a rich set of matchers for validating function arguments,
|
||||
- uses an intuitive syntax for controlling the behavior of a mock,
|
||||
- does automatic verification of expectations (no record-and-replay
|
||||
needed),
|
||||
- allows arbitrary (partial) ordering constraints on
|
||||
function calls to be expressed,
|
||||
- lets a user extend it by defining new matchers and actions.
|
||||
- does not use exceptions, and
|
||||
- is easy to learn and use.
|
||||
|
||||
Please see the project page above for more information as well as the
|
||||
mailing list for questions, discussions, and development. There is
|
||||
also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please
|
||||
join us!
|
||||
|
||||
Please note that code under scripts/generator/ is from the cppclean
|
||||
project (http://code.google.com/p/cppclean/) and under the Apache
|
||||
License, which is different from Google Mock's license.
|
||||
|
||||
Requirements for End Users
|
||||
--------------------------
|
||||
|
||||
Google Mock is implemented on top of the Google Test C++ testing
|
||||
framework (http://code.google.com/p/googletest/), and includes the
|
||||
latter as part of the SVN repositary and distribution package. You
|
||||
must use the bundled version of Google Test when using Google Mock, or
|
||||
you may get compiler/linker errors.
|
||||
|
||||
You can also easily configure Google Mock to work with another testing
|
||||
framework of your choice; although it will still need Google Test as
|
||||
an internal dependency. Please read
|
||||
http://code.google.com/p/googlemock/wiki/ForDummies#Using_Google_Mock_with_Any_Testing_Framework
|
||||
for how to do it.
|
||||
|
||||
Google Mock depends on advanced C++ features and thus requires a more
|
||||
modern compiler. The following are needed to use Google Mock:
|
||||
|
||||
### Linux Requirements ###
|
||||
|
||||
These are the base requirements to build and use Google Mock from a source
|
||||
package (as described below):
|
||||
|
||||
* GNU-compatible Make or "gmake"
|
||||
* POSIX-standard shell
|
||||
* POSIX(-2) Regular Expressions (regex.h)
|
||||
* C++98-standard-compliant compiler (e.g. GCC 3.4 or newer)
|
||||
|
||||
### Windows Requirements ###
|
||||
|
||||
* Microsoft Visual C++ 8.0 SP1 or newer
|
||||
|
||||
### Mac OS X Requirements ###
|
||||
|
||||
* Mac OS X 10.4 Tiger or newer
|
||||
* Developer Tools Installed
|
||||
|
||||
Requirements for Contributors
|
||||
-----------------------------
|
||||
|
||||
We welcome patches. If you plan to contribute a patch, you need to
|
||||
build Google Mock and its own tests from an SVN checkout (described
|
||||
below), which has further requirements:
|
||||
|
||||
* Automake version 1.9 or newer
|
||||
* Autoconf version 2.59 or newer
|
||||
* Libtool / Libtoolize
|
||||
* Python version 2.3 or newer (for running some of the tests and
|
||||
re-generating certain source files from templates)
|
||||
|
||||
Getting the Source
|
||||
------------------
|
||||
|
||||
There are two primary ways of getting Google Mock's source code: you
|
||||
can download a stable source release in your preferred archive format,
|
||||
or directly check out the source from our Subversion (SVN) repositary.
|
||||
The SVN checkout requires a few extra steps and some extra software
|
||||
packages on your system, but lets you track development and make
|
||||
patches much more easily, so we highly encourage it.
|
||||
|
||||
### Source Package ###
|
||||
|
||||
Google Mock is released in versioned source packages which can be
|
||||
downloaded from the download page [1]. Several different archive
|
||||
formats are provided, but the only difference is the tools needed to
|
||||
extract their contents, and the size of the resulting file. Download
|
||||
whichever you are most comfortable with.
|
||||
|
||||
[1] http://code.google.com/p/googlemock/downloads/list
|
||||
|
||||
Once downloaded expand the archive using whichever tools you prefer
|
||||
for that type. This will always result in a new directory with the
|
||||
name "gmock-X.Y.Z" which contains all of the source code. Here are
|
||||
some examples on Linux:
|
||||
|
||||
tar -xvzf gmock-X.Y.Z.tar.gz
|
||||
tar -xvjf gmock-X.Y.Z.tar.bz2
|
||||
unzip gmock-X.Y.Z.zip
|
||||
|
||||
### SVN Checkout ###
|
||||
|
||||
To check out the main branch (also known as the "trunk") of Google
|
||||
Mock, run the following Subversion command:
|
||||
|
||||
svn checkout http://googlemock.googlecode.com/svn/trunk/ gmock-svn
|
||||
|
||||
If you are using a *nix system and plan to use the GNU Autotools build
|
||||
system to build Google Mock (described below), you'll need to
|
||||
configure it now. Otherwise you are done with getting the source
|
||||
files.
|
||||
|
||||
To prepare the Autotools build system, enter the target directory of
|
||||
the checkout command you used ('gmock-svn') and proceed with the
|
||||
following command:
|
||||
|
||||
autoreconf -fvi
|
||||
|
||||
Once you have completed this step, you are ready to build the library.
|
||||
Note that you should only need to complete this step once. The
|
||||
subsequent 'make' invocations will automatically re-generate the bits
|
||||
of the build system that need to be changed.
|
||||
|
||||
If your system uses older versions of the autotools, the above command
|
||||
will fail. You may need to explicitly specify a version to use. For
|
||||
instance, if you have both GNU Automake 1.4 and 1.9 installed and
|
||||
'automake' would invoke the 1.4, use instead:
|
||||
|
||||
AUTOMAKE=automake-1.9 ACLOCAL=aclocal-1.9 autoreconf -fvi
|
||||
|
||||
Make sure you're using the same version of automake and aclocal.
|
||||
|
||||
Setting up the Build
|
||||
--------------------
|
||||
|
||||
To build Google Mock 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.
|
||||
|
||||
### Generic Build Instructions ###
|
||||
|
||||
This section shows how you can integrate Google Mock into your
|
||||
existing build system.
|
||||
|
||||
Suppose you put Google Mock in directory ${GMOCK_DIR} and Google Test
|
||||
in ${GTEST_DIR} (the latter is ${GMOCK_DIR}/gtest by default). To
|
||||
build Google Mock, create a library build target (or a project as
|
||||
called by Visual Studio and Xcode) to compile
|
||||
|
||||
${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc
|
||||
|
||||
with
|
||||
|
||||
${GTEST_DIR}/include, ${GTEST_DIR}, ${GMOCK_DIR}/include, and ${GMOCK_DIR}
|
||||
|
||||
in the header search path. Assuming a Linux-like system and gcc,
|
||||
something like the following will do:
|
||||
|
||||
g++ -I${GTEST_DIR}/include -I${GTEST_DIR} -I${GMOCK_DIR}/include \
|
||||
-I${GMOCK_DIR} -c ${GTEST_DIR}/src/gtest-all.cc
|
||||
g++ -I${GTEST_DIR}/include -I${GTEST_DIR} -I${GMOCK_DIR}/include \
|
||||
-I${GMOCK_DIR} -c ${GMOCK_DIR}/src/gmock-all.cc
|
||||
ar -rv libgmock.a gtest-all.o gmock-all.o
|
||||
|
||||
Next, you should compile your test source file with
|
||||
${GTEST_DIR}/include and ${GMOCK_DIR}/include in the header search
|
||||
path, and link it with gmock and any other necessary libraries:
|
||||
|
||||
g++ -I${GTEST_DIR}/include -I${GMOCK_DIR}/include \
|
||||
path/to/your_test.cc libgmock.a -o your_test
|
||||
|
||||
As an example, the make/ directory contains a Makefile that you can
|
||||
use to build Google Mock on systems where GNU make is available
|
||||
(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google
|
||||
Mock's own tests. Instead, it just builds the Google Mock library and
|
||||
a sample test. You can use it as a starting point for your own build
|
||||
script.
|
||||
|
||||
If the default settings are correct for your environment, the
|
||||
following commands should succeed:
|
||||
|
||||
cd ${GMOCK_DIR}/make
|
||||
make
|
||||
./gmock_test
|
||||
|
||||
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.
|
||||
|
||||
### Windows ###
|
||||
|
||||
The msvc/2005 directory contains VC++ 2005 projects and the msvc/2010
|
||||
directory contains VC++ 2010 projects for building Google Mock and
|
||||
selected tests.
|
||||
|
||||
Change to the appropriate directory and run "msbuild gmock.sln" to
|
||||
build the library and tests (or open the gmock.sln in the MSVC IDE).
|
||||
If you want to create your own project to use with Google Mock, you'll
|
||||
have to configure it to use the gmock_config propety sheet. For that:
|
||||
|
||||
* Open the Property Manager window (View | Other Windows | Property Manager)
|
||||
* Right-click on your project and select "Add Existing Property Sheet..."
|
||||
* Navigate to gmock_config.vsprops or gmock_config.props and select it.
|
||||
* In Project Properties | Configuration Properties | General | Additional
|
||||
Include Directories, type <path to Google Mock>/include.
|
||||
|
||||
Tweaking Google Mock
|
||||
--------------------
|
||||
|
||||
Google Mock 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 Mock by
|
||||
defining control macros on the compiler command line. Generally,
|
||||
these macros are named like GTEST_XYZ and you define them to either 1
|
||||
or 0 to enable or disable a certain feature.
|
||||
|
||||
We list the most frequently used macros below. For a complete list,
|
||||
see file ${GTEST_DIR}/include/gtest/internal/gtest-port.h.
|
||||
|
||||
### Choosing a TR1 Tuple Library ###
|
||||
|
||||
Google Mock uses the C++ Technical Report 1 (TR1) tuple library
|
||||
heavily. Unfortunately TR1 tuple is not yet widely available with all
|
||||
compilers. The good news is that Google Test 1.4.0+ implements a
|
||||
subset of TR1 tuple that's enough for Google Mock's need. Google Mock
|
||||
will automatically use that implementation when the compiler doesn't
|
||||
provide TR1 tuple.
|
||||
|
||||
Usually you don't need to care about which tuple library Google Test
|
||||
and Google Mock use. However, if your project already uses TR1 tuple,
|
||||
you need to tell Google Test and Google Mock to use the same TR1 tuple
|
||||
library the rest of your project uses, or the two tuple
|
||||
implementations will clash. To do that, add
|
||||
|
||||
-DGTEST_USE_OWN_TR1_TUPLE=0
|
||||
|
||||
to the compiler flags while compiling Google Test, Google Mock, and
|
||||
your tests. If you want to force Google Test and Google Mock to use
|
||||
their own tuple library, just add
|
||||
|
||||
-DGTEST_USE_OWN_TR1_TUPLE=1
|
||||
|
||||
to the compiler flags instead.
|
||||
|
||||
If you want to use Boost's TR1 tuple library with Google Mock, please
|
||||
refer to the Boost website (http://www.boost.org/) for how to obtain
|
||||
it and set it up.
|
||||
|
||||
### Tweaking Google Test ###
|
||||
|
||||
Most of Google Test's control macros apply to Google Mock as well.
|
||||
Please see file ${GTEST_DIR}/README for how to tweak them.
|
||||
|
||||
Upgrading from an Earlier Version
|
||||
---------------------------------
|
||||
|
||||
We strive to keep Google Mock releases backward compatible.
|
||||
Sometimes, though, we have to make some breaking changes for the
|
||||
users' long-term benefits. This section describes what you'll need to
|
||||
do if you are upgrading from an earlier version of Google Mock.
|
||||
|
||||
### Upgrading from 1.1.0 or Earlier ###
|
||||
|
||||
You may need to explicitly enable or disable Google Test's own TR1
|
||||
tuple library. See the instructions in section "Choosing a TR1 Tuple
|
||||
Library".
|
||||
|
||||
### Upgrading from 1.4.0 or Earlier ###
|
||||
|
||||
On platforms where the pthread library is available, Google Test and
|
||||
Google Mock use it in order to be thread-safe. For this to work, you
|
||||
may need to tweak your compiler and/or linker flags. Please see the
|
||||
"Multi-threaded Tests" section in file ${GTEST_DIR}/README for what
|
||||
you may need to do.
|
||||
|
||||
If you have custom matchers defined using MatcherInterface or
|
||||
MakePolymorphicMatcher(), you'll need to update their definitions to
|
||||
use the new matcher API [2]. Matchers defined using MATCHER() or
|
||||
MATCHER_P*() aren't affected.
|
||||
|
||||
[2] http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Monomorphic_Matchers,
|
||||
http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Matchers
|
||||
|
||||
Developing Google Mock
|
||||
----------------------
|
||||
|
||||
This section discusses how to make your own changes to Google Mock.
|
||||
|
||||
### Testing Google Mock 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'll need Autotools. First, make sure you have followed
|
||||
the instructions in section "SVN Checkout" to configure Google Mock.
|
||||
Then, create a build output directory and enter it. Next,
|
||||
|
||||
${GMOCK_DIR}/configure # Standard GNU configure script, --help for more info
|
||||
|
||||
Once you have successfully configured Google Mock, the build steps are
|
||||
standard for GNU-style OSS packages.
|
||||
|
||||
make # Standard makefile following GNU conventions
|
||||
make check # Builds and runs all tests - all should pass.
|
||||
|
||||
Note that when building your project against Google Mock, you are building
|
||||
against Google Test as well. There is no need to configure Google Test
|
||||
separately.
|
||||
|
||||
### Regenerating Source Files ###
|
||||
|
||||
Some of Google Mock's source files are generated from templates (not
|
||||
in the C++ sense) using a script. A template file is named FOO.pump,
|
||||
where FOO is the name of the file it will generate. For example, the
|
||||
file include/gmock/gmock-generated-actions.h.pump is used to generate
|
||||
gmock-generated-actions.h in the same directory.
|
||||
|
||||
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' script (for Pump
|
||||
is Useful for Meta Programming) to regenerate them. You can find
|
||||
pump.py in the ${GTEST_DIR}/scripts/ directory. Read the Pump manual
|
||||
[3] for how to use it.
|
||||
|
||||
[3] http://code.google.com/p/googletest/wiki/PumpManual.
|
||||
|
||||
### Contributing a Patch ###
|
||||
|
||||
We welcome patches. Please read the Google Mock developer's guide [4]
|
||||
for how you can contribute. In particular, make sure you have signed
|
||||
the Contributor License Agreement, or we won't be able to accept the
|
||||
patch.
|
||||
|
||||
[4] http://code.google.com/p/googlemock/wiki/DevGuide
|
||||
|
||||
Happy testing!
|
|
@ -0,0 +1,323 @@
|
|||
## Google Mock ##
|
||||
|
||||
The Google C++ mocking framework.
|
||||
|
||||
### Overview ###
|
||||
|
||||
Google's framework for writing and using C++ mock classes.
|
||||
It can help you derive better designs of your system and write better tests.
|
||||
|
||||
It is inspired by:
|
||||
|
||||
* [jMock](http://www.jmock.org/),
|
||||
* [EasyMock](http://www.easymock.org/), and
|
||||
* [Hamcrest](http://code.google.com/p/hamcrest/),
|
||||
|
||||
and designed with C++'s specifics in mind.
|
||||
|
||||
Google mock:
|
||||
|
||||
* lets you create mock classes trivially using simple macros.
|
||||
* supports a rich set of matchers and actions.
|
||||
* handles unordered, partially ordered, or completely ordered expectations.
|
||||
* is extensible by users.
|
||||
|
||||
We hope you find it useful!
|
||||
|
||||
### Features ###
|
||||
|
||||
* Provides a declarative syntax for defining mocks.
|
||||
* Can easily define partial (hybrid) mocks, which are a cross of real
|
||||
and mock objects.
|
||||
* Handles functions of arbitrary types and overloaded functions.
|
||||
* Comes with a rich set of matchers for validating function arguments.
|
||||
* Uses an intuitive syntax for controlling the behavior of a mock.
|
||||
* Does automatic verification of expectations (no record-and-replay needed).
|
||||
* Allows arbitrary (partial) ordering constraints on
|
||||
function calls to be expressed,.
|
||||
* Lets an user extend it by defining new matchers and actions.
|
||||
* Does not use exceptions.
|
||||
* Is easy to learn and use.
|
||||
|
||||
Please see the project page above for more information as well as the
|
||||
mailing list for questions, discussions, and development. There is
|
||||
also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please
|
||||
join us!
|
||||
|
||||
Please note that code under [scripts/generator](scripts/generator/) is
|
||||
from [cppclean](http://code.google.com/p/cppclean/) and released under
|
||||
the Apache License, which is different from Google Mock's license.
|
||||
|
||||
## Getting Started ##
|
||||
|
||||
If you are new to the project, we suggest that you read the user
|
||||
documentation in the following order:
|
||||
|
||||
* Learn the [basics](../../master/googletest/docs/primer.md) of
|
||||
Google Test, if you choose to use Google Mock with it (recommended).
|
||||
* Read [Google Mock for Dummies](../../master/googlemock/docs/ForDummies.md).
|
||||
* Read the instructions below on how to build Google Mock.
|
||||
|
||||
You can also watch Zhanyong's [talk](http://www.youtube.com/watch?v=sYpCyLI47rM) on Google Mock's usage and implementation.
|
||||
|
||||
Once you understand the basics, check out the rest of the docs:
|
||||
|
||||
* [CheatSheet](../../master/googlemock/docs/CheatSheet.md) - all the commonly used stuff
|
||||
at a glance.
|
||||
* [CookBook](../../master/googlemock/docs/CookBook.md) - recipes for getting things done,
|
||||
including advanced techniques.
|
||||
|
||||
If you need help, please check the
|
||||
[KnownIssues](docs/KnownIssues.md) and
|
||||
[FrequentlyAskedQuestions](docs/FrequentlyAskedQuestions.md) before
|
||||
posting a question on the
|
||||
[discussion group](http://groups.google.com/group/googlemock).
|
||||
|
||||
|
||||
### Using Google Mock Without Google Test ###
|
||||
|
||||
Google Mock is not a testing framework itself. Instead, it needs a
|
||||
testing framework for writing tests. Google Mock works seamlessly
|
||||
with [Google Test](https://github.com/google/googletest), but
|
||||
you can also use it with [any C++ testing framework](../../master/googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework).
|
||||
|
||||
### Requirements for End Users ###
|
||||
|
||||
Google Mock is implemented on top of [Google Test](
|
||||
http://github.com/google/googletest/), and depends on it.
|
||||
You must use the bundled version of Google Test when using Google Mock.
|
||||
|
||||
You can also easily configure Google Mock to work with another testing
|
||||
framework, although it will still need Google Test. Please read
|
||||
["Using_Google_Mock_with_Any_Testing_Framework"](
|
||||
../../master/googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework)
|
||||
for instructions.
|
||||
|
||||
Google Mock depends on advanced C++ features and thus requires a more
|
||||
modern compiler. The following are needed to use Google Mock:
|
||||
|
||||
#### Linux Requirements ####
|
||||
|
||||
* GNU-compatible Make or "gmake"
|
||||
* POSIX-standard shell
|
||||
* POSIX(-2) Regular Expressions (regex.h)
|
||||
* C++98-standard-compliant compiler (e.g. GCC 3.4 or newer)
|
||||
|
||||
#### Windows Requirements ####
|
||||
|
||||
* Microsoft Visual C++ 8.0 SP1 or newer
|
||||
|
||||
#### Mac OS X Requirements ####
|
||||
|
||||
* Mac OS X 10.4 Tiger or newer
|
||||
* Developer Tools Installed
|
||||
|
||||
### Requirements for Contributors ###
|
||||
|
||||
We welcome patches. If you plan to contribute a patch, you need to
|
||||
build Google Mock and its tests, which has further requirements:
|
||||
|
||||
* Automake version 1.9 or newer
|
||||
* Autoconf version 2.59 or newer
|
||||
* Libtool / Libtoolize
|
||||
* Python version 2.3 or newer (for running some of the tests and
|
||||
re-generating certain source files from templates)
|
||||
|
||||
### Building Google Mock ###
|
||||
|
||||
#### Using CMake ####
|
||||
|
||||
If you have CMake available, it is recommended that you follow the
|
||||
[build instructions][gtest_cmakebuild]
|
||||
as described for Google Test.
|
||||
|
||||
If are using Google Mock with an
|
||||
existing CMake project, the section
|
||||
[Incorporating Into An Existing CMake Project][gtest_incorpcmake]
|
||||
may be of particular interest.
|
||||
To make it work for Google Mock you will need to change
|
||||
|
||||
target_link_libraries(example gtest_main)
|
||||
|
||||
to
|
||||
|
||||
target_link_libraries(example gmock_main)
|
||||
|
||||
This works because `gmock_main` library is compiled with Google Test.
|
||||
|
||||
#### Preparing to Build (Unix only) ####
|
||||
|
||||
If you are using a Unix system and plan to use the GNU Autotools build
|
||||
system to build Google Mock (described below), you'll need to
|
||||
configure it now.
|
||||
|
||||
To prepare the Autotools build system:
|
||||
|
||||
cd googlemock
|
||||
autoreconf -fvi
|
||||
|
||||
To build Google Mock 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.
|
||||
|
||||
This section shows how you can integrate Google Mock into your
|
||||
existing build system.
|
||||
|
||||
Suppose you put Google Mock in directory `${GMOCK_DIR}` and Google Test
|
||||
in `${GTEST_DIR}` (the latter is `${GMOCK_DIR}/gtest` by default). To
|
||||
build Google Mock, create a library build target (or a project as
|
||||
called by Visual Studio and Xcode) to compile
|
||||
|
||||
${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc
|
||||
|
||||
with
|
||||
|
||||
${GTEST_DIR}/include and ${GMOCK_DIR}/include
|
||||
|
||||
in the system header search path, and
|
||||
|
||||
${GTEST_DIR} and ${GMOCK_DIR}
|
||||
|
||||
in the normal header search path. Assuming a Linux-like system and gcc,
|
||||
something like the following will do:
|
||||
|
||||
g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
|
||||
-isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
|
||||
-pthread -c ${GTEST_DIR}/src/gtest-all.cc
|
||||
g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \
|
||||
-isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \
|
||||
-pthread -c ${GMOCK_DIR}/src/gmock-all.cc
|
||||
ar -rv libgmock.a gtest-all.o gmock-all.o
|
||||
|
||||
(We need -pthread as Google Test and Google Mock use threads.)
|
||||
|
||||
Next, you should compile your test source file with
|
||||
${GTEST\_DIR}/include and ${GMOCK\_DIR}/include in the header search
|
||||
path, and link it with gmock and any other necessary libraries:
|
||||
|
||||
g++ -isystem ${GTEST_DIR}/include -isystem ${GMOCK_DIR}/include \
|
||||
-pthread path/to/your_test.cc libgmock.a -o your_test
|
||||
|
||||
As an example, the make/ directory contains a Makefile that you can
|
||||
use to build Google Mock on systems where GNU make is available
|
||||
(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google
|
||||
Mock's own tests. Instead, it just builds the Google Mock library and
|
||||
a sample test. You can use it as a starting point for your own build
|
||||
script.
|
||||
|
||||
If the default settings are correct for your environment, the
|
||||
following commands should succeed:
|
||||
|
||||
cd ${GMOCK_DIR}/make
|
||||
make
|
||||
./gmock_test
|
||||
|
||||
If you see errors, try to tweak the contents of
|
||||
[make/Makefile](make/Makefile) to make them go away.
|
||||
|
||||
### Windows ###
|
||||
|
||||
The msvc/2005 directory contains VC++ 2005 projects and the msvc/2010
|
||||
directory contains VC++ 2010 projects for building Google Mock and
|
||||
selected tests.
|
||||
|
||||
Change to the appropriate directory and run "msbuild gmock.sln" to
|
||||
build the library and tests (or open the gmock.sln in the MSVC IDE).
|
||||
If you want to create your own project to use with Google Mock, you'll
|
||||
have to configure it to use the `gmock_config` propety sheet. For that:
|
||||
|
||||
* Open the Property Manager window (View | Other Windows | Property Manager)
|
||||
* Right-click on your project and select "Add Existing Property Sheet..."
|
||||
* Navigate to `gmock_config.vsprops` or `gmock_config.props` and select it.
|
||||
* In Project Properties | Configuration Properties | General | Additional
|
||||
Include Directories, type <path to Google Mock>/include.
|
||||
|
||||
### Tweaking Google Mock ###
|
||||
|
||||
Google Mock 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 Mock by
|
||||
defining control macros on the compiler command line. Generally,
|
||||
these macros are named like `GTEST_XYZ` and you define them to either 1
|
||||
or 0 to enable or disable a certain feature.
|
||||
|
||||
We list the most frequently used macros below. For a complete list,
|
||||
see file [${GTEST\_DIR}/include/gtest/internal/gtest-port.h](
|
||||
../googletest/include/gtest/internal/gtest-port.h).
|
||||
|
||||
### Choosing a TR1 Tuple Library ###
|
||||
|
||||
Google Mock uses the C++ Technical Report 1 (TR1) tuple library
|
||||
heavily. Unfortunately TR1 tuple is not yet widely available with all
|
||||
compilers. The good news is that Google Test 1.4.0+ implements a
|
||||
subset of TR1 tuple that's enough for Google Mock's need. Google Mock
|
||||
will automatically use that implementation when the compiler doesn't
|
||||
provide TR1 tuple.
|
||||
|
||||
Usually you don't need to care about which tuple library Google Test
|
||||
and Google Mock use. However, if your project already uses TR1 tuple,
|
||||
you need to tell Google Test and Google Mock to use the same TR1 tuple
|
||||
library the rest of your project uses, or the two tuple
|
||||
implementations will clash. To do that, add
|
||||
|
||||
-DGTEST_USE_OWN_TR1_TUPLE=0
|
||||
|
||||
to the compiler flags while compiling Google Test, Google Mock, and
|
||||
your tests. If you want to force Google Test and Google Mock to use
|
||||
their own tuple library, just add
|
||||
|
||||
-DGTEST_USE_OWN_TR1_TUPLE=1
|
||||
|
||||
to the compiler flags instead.
|
||||
|
||||
If you want to use Boost's TR1 tuple library with Google Mock, please
|
||||
refer to the Boost website (http://www.boost.org/) for how to obtain
|
||||
it and set it up.
|
||||
|
||||
### As a Shared Library (DLL) ###
|
||||
|
||||
Google Mock is compact, so most users can build and link it as a static
|
||||
library for the simplicity. Google Mock can be used as a DLL, but the
|
||||
same DLL must contain Google Test as well. See
|
||||
[Google Test's README][gtest_readme]
|
||||
for instructions on how to set up necessary compiler settings.
|
||||
|
||||
### Tweaking Google Mock ###
|
||||
|
||||
Most of Google Test's control macros apply to Google Mock as well.
|
||||
Please see [Google Test's README][gtest_readme] for how to tweak them.
|
||||
|
||||
### Upgrading from an Earlier Version ###
|
||||
|
||||
We strive to keep Google Mock releases backward compatible.
|
||||
Sometimes, though, we have to make some breaking changes for the
|
||||
users' long-term benefits. This section describes what you'll need to
|
||||
do if you are upgrading from an earlier version of Google Mock.
|
||||
|
||||
#### Upgrading from 1.1.0 or Earlier ####
|
||||
|
||||
You may need to explicitly enable or disable Google Test's own TR1
|
||||
tuple library. See the instructions in section "[Choosing a TR1 Tuple
|
||||
Library](../googletest/#choosing-a-tr1-tuple-library)".
|
||||
|
||||
#### Upgrading from 1.4.0 or Earlier ####
|
||||
|
||||
On platforms where the pthread library is available, Google Test and
|
||||
Google Mock use it in order to be thread-safe. For this to work, you
|
||||
may need to tweak your compiler and/or linker flags. Please see the
|
||||
"[Multi-threaded Tests](../googletest#multi-threaded-tests
|
||||
)" section in file Google Test's README for what you may need to do.
|
||||
|
||||
If you have custom matchers defined using `MatcherInterface` or
|
||||
`MakePolymorphicMatcher()`, you'll need to update their definitions to
|
||||
use the new matcher API (
|
||||
[monomorphic](./docs/CookBook.md#writing-new-monomorphic-matchers),
|
||||
[polymorphic](./docs/CookBook.md#writing-new-polymorphic-matchers)).
|
||||
Matchers defined using `MATCHER()` or `MATCHER_P*()` aren't affected.
|
||||
|
||||
Happy testing!
|
||||
|
||||
[gtest_readme]: ../googletest/README.md "googletest"
|
||||
[gtest_cmakebuild]: ../googletest/README.md#using-cmake "Using CMake"
|
||||
[gtest_incorpcmake]: ../googletest/README.md#incorporating-into-an-existing-cmake-project "Incorporating Into An Existing CMake Project"
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -1,69 +0,0 @@
|
|||
/* build-aux/config.h.in. Generated from configure.ac by autoheader. */
|
||||
|
||||
/* Define to 1 if you have the <dlfcn.h> header file. */
|
||||
#undef HAVE_DLFCN_H
|
||||
|
||||
/* Define to 1 if you have the <inttypes.h> header file. */
|
||||
#undef HAVE_INTTYPES_H
|
||||
|
||||
/* Define to 1 if you have the <memory.h> header file. */
|
||||
#undef HAVE_MEMORY_H
|
||||
|
||||
/* Define if you have POSIX threads libraries and header files. */
|
||||
#undef HAVE_PTHREAD
|
||||
|
||||
/* Define to 1 if you have the <stdint.h> header file. */
|
||||
#undef HAVE_STDINT_H
|
||||
|
||||
/* Define to 1 if you have the <stdlib.h> header file. */
|
||||
#undef HAVE_STDLIB_H
|
||||
|
||||
/* Define to 1 if you have the <strings.h> header file. */
|
||||
#undef HAVE_STRINGS_H
|
||||
|
||||
/* Define to 1 if you have the <string.h> header file. */
|
||||
#undef HAVE_STRING_H
|
||||
|
||||
/* Define to 1 if you have the <sys/stat.h> header file. */
|
||||
#undef HAVE_SYS_STAT_H
|
||||
|
||||
/* Define to 1 if you have the <sys/types.h> header file. */
|
||||
#undef HAVE_SYS_TYPES_H
|
||||
|
||||
/* Define to 1 if you have the <unistd.h> header file. */
|
||||
#undef HAVE_UNISTD_H
|
||||
|
||||
/* Define to the sub-directory in which libtool stores uninstalled libraries.
|
||||
*/
|
||||
#undef LT_OBJDIR
|
||||
|
||||
/* Name of package */
|
||||
#undef PACKAGE
|
||||
|
||||
/* Define to the address where bug reports for this package should be sent. */
|
||||
#undef PACKAGE_BUGREPORT
|
||||
|
||||
/* Define to the full name of this package. */
|
||||
#undef PACKAGE_NAME
|
||||
|
||||
/* Define to the full name and version of this package. */
|
||||
#undef PACKAGE_STRING
|
||||
|
||||
/* Define to the one symbol short name of this package. */
|
||||
#undef PACKAGE_TARNAME
|
||||
|
||||
/* Define to the home page for this package. */
|
||||
#undef PACKAGE_URL
|
||||
|
||||
/* Define to the version of this package. */
|
||||
#undef PACKAGE_VERSION
|
||||
|
||||
/* Define to necessary symbol if this constant uses a non-standard name on
|
||||
your system. */
|
||||
#undef PTHREAD_CREATE_JOINABLE
|
||||
|
||||
/* Define to 1 if you have the ANSI C header files. */
|
||||
#undef STDC_HEADERS
|
||||
|
||||
/* Version number of package */
|
||||
#undef VERSION
|
File diff suppressed because it is too large
Load Diff
|
@ -1,630 +0,0 @@
|
|||
#! /bin/sh
|
||||
# depcomp - compile a program generating dependencies as side-effects
|
||||
|
||||
scriptversion=2009-04-28.21; # UTC
|
||||
|
||||
# Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006, 2007, 2009 Free
|
||||
# Software Foundation, Inc.
|
||||
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2, or (at your option)
|
||||
# any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# As a special exception to the GNU General Public License, if you
|
||||
# distribute this file as part of a program that contains a
|
||||
# configuration script generated by Autoconf, you may include it under
|
||||
# the same distribution terms that you use for the rest of that program.
|
||||
|
||||
# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
|
||||
|
||||
case $1 in
|
||||
'')
|
||||
echo "$0: No command. Try \`$0 --help' for more information." 1>&2
|
||||
exit 1;
|
||||
;;
|
||||
-h | --h*)
|
||||
cat <<\EOF
|
||||
Usage: depcomp [--help] [--version] PROGRAM [ARGS]
|
||||
|
||||
Run PROGRAMS ARGS to compile a file, generating dependencies
|
||||
as side-effects.
|
||||
|
||||
Environment variables:
|
||||
depmode Dependency tracking mode.
|
||||
source Source file read by `PROGRAMS ARGS'.
|
||||
object Object file output by `PROGRAMS ARGS'.
|
||||
DEPDIR directory where to store dependencies.
|
||||
depfile Dependency file to output.
|
||||
tmpdepfile Temporary file to use when outputing dependencies.
|
||||
libtool Whether libtool is used (yes/no).
|
||||
|
||||
Report bugs to <bug-automake@gnu.org>.
|
||||
EOF
|
||||
exit $?
|
||||
;;
|
||||
-v | --v*)
|
||||
echo "depcomp $scriptversion"
|
||||
exit $?
|
||||
;;
|
||||
esac
|
||||
|
||||
if test -z "$depmode" || test -z "$source" || test -z "$object"; then
|
||||
echo "depcomp: Variables source, object and depmode must be set" 1>&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po.
|
||||
depfile=${depfile-`echo "$object" |
|
||||
sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`}
|
||||
tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
|
||||
|
||||
rm -f "$tmpdepfile"
|
||||
|
||||
# Some modes work just like other modes, but use different flags. We
|
||||
# parameterize here, but still list the modes in the big case below,
|
||||
# to make depend.m4 easier to write. Note that we *cannot* use a case
|
||||
# here, because this file can only contain one case statement.
|
||||
if test "$depmode" = hp; then
|
||||
# HP compiler uses -M and no extra arg.
|
||||
gccflag=-M
|
||||
depmode=gcc
|
||||
fi
|
||||
|
||||
if test "$depmode" = dashXmstdout; then
|
||||
# This is just like dashmstdout with a different argument.
|
||||
dashmflag=-xM
|
||||
depmode=dashmstdout
|
||||
fi
|
||||
|
||||
cygpath_u="cygpath -u -f -"
|
||||
if test "$depmode" = msvcmsys; then
|
||||
# This is just like msvisualcpp but w/o cygpath translation.
|
||||
# Just convert the backslash-escaped backslashes to single forward
|
||||
# slashes to satisfy depend.m4
|
||||
cygpath_u="sed s,\\\\\\\\,/,g"
|
||||
depmode=msvisualcpp
|
||||
fi
|
||||
|
||||
case "$depmode" in
|
||||
gcc3)
|
||||
## gcc 3 implements dependency tracking that does exactly what
|
||||
## we want. Yay! Note: for some reason libtool 1.4 doesn't like
|
||||
## it if -MD -MP comes after the -MF stuff. Hmm.
|
||||
## Unfortunately, FreeBSD c89 acceptance of flags depends upon
|
||||
## the command line argument order; so add the flags where they
|
||||
## appear in depend2.am. Note that the slowdown incurred here
|
||||
## affects only configure: in makefiles, %FASTDEP% shortcuts this.
|
||||
for arg
|
||||
do
|
||||
case $arg in
|
||||
-c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;;
|
||||
*) set fnord "$@" "$arg" ;;
|
||||
esac
|
||||
shift # fnord
|
||||
shift # $arg
|
||||
done
|
||||
"$@"
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
mv "$tmpdepfile" "$depfile"
|
||||
;;
|
||||
|
||||
gcc)
|
||||
## There are various ways to get dependency output from gcc. Here's
|
||||
## why we pick this rather obscure method:
|
||||
## - Don't want to use -MD because we'd like the dependencies to end
|
||||
## up in a subdir. Having to rename by hand is ugly.
|
||||
## (We might end up doing this anyway to support other compilers.)
|
||||
## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
|
||||
## -MM, not -M (despite what the docs say).
|
||||
## - Using -M directly means running the compiler twice (even worse
|
||||
## than renaming).
|
||||
if test -z "$gccflag"; then
|
||||
gccflag=-MD,
|
||||
fi
|
||||
"$@" -Wp,"$gccflag$tmpdepfile"
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
rm -f "$depfile"
|
||||
echo "$object : \\" > "$depfile"
|
||||
alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
|
||||
## The second -e expression handles DOS-style file names with drive letters.
|
||||
sed -e 's/^[^:]*: / /' \
|
||||
-e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
|
||||
## This next piece of magic avoids the `deleted header file' problem.
|
||||
## The problem is that when a header file which appears in a .P file
|
||||
## is deleted, the dependency causes make to die (because there is
|
||||
## typically no way to rebuild the header). We avoid this by adding
|
||||
## dummy dependencies for each header file. Too bad gcc doesn't do
|
||||
## this for us directly.
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" |
|
||||
## Some versions of gcc put a space before the `:'. On the theory
|
||||
## that the space means something, we add a space to the output as
|
||||
## well.
|
||||
## Some versions of the HPUX 10.20 sed can't process this invocation
|
||||
## correctly. Breaking it into two sed invocations is a workaround.
|
||||
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
hp)
|
||||
# This case exists only to let depend.m4 do its work. It works by
|
||||
# looking at the text of this script. This case will never be run,
|
||||
# since it is checked for above.
|
||||
exit 1
|
||||
;;
|
||||
|
||||
sgi)
|
||||
if test "$libtool" = yes; then
|
||||
"$@" "-Wp,-MDupdate,$tmpdepfile"
|
||||
else
|
||||
"$@" -MDupdate "$tmpdepfile"
|
||||
fi
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
rm -f "$depfile"
|
||||
|
||||
if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files
|
||||
echo "$object : \\" > "$depfile"
|
||||
|
||||
# Clip off the initial element (the dependent). Don't try to be
|
||||
# clever and replace this with sed code, as IRIX sed won't handle
|
||||
# lines with more than a fixed number of characters (4096 in
|
||||
# IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines;
|
||||
# the IRIX cc adds comments like `#:fec' to the end of the
|
||||
# dependency line.
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" \
|
||||
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
|
||||
tr '
|
||||
' ' ' >> "$depfile"
|
||||
echo >> "$depfile"
|
||||
|
||||
# The second pass generates a dummy entry for each header file.
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" \
|
||||
| sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
|
||||
>> "$depfile"
|
||||
else
|
||||
# The sourcefile does not contain any dependencies, so just
|
||||
# store a dummy comment line, to avoid errors with the Makefile
|
||||
# "include basename.Plo" scheme.
|
||||
echo "#dummy" > "$depfile"
|
||||
fi
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
aix)
|
||||
# The C for AIX Compiler uses -M and outputs the dependencies
|
||||
# in a .u file. In older versions, this file always lives in the
|
||||
# current directory. Also, the AIX compiler puts `$object:' at the
|
||||
# start of each line; $object doesn't have directory information.
|
||||
# Version 6 uses the directory in both cases.
|
||||
dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
|
||||
test "x$dir" = "x$object" && dir=
|
||||
base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
|
||||
if test "$libtool" = yes; then
|
||||
tmpdepfile1=$dir$base.u
|
||||
tmpdepfile2=$base.u
|
||||
tmpdepfile3=$dir.libs/$base.u
|
||||
"$@" -Wc,-M
|
||||
else
|
||||
tmpdepfile1=$dir$base.u
|
||||
tmpdepfile2=$dir$base.u
|
||||
tmpdepfile3=$dir$base.u
|
||||
"$@" -M
|
||||
fi
|
||||
stat=$?
|
||||
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
|
||||
exit $stat
|
||||
fi
|
||||
|
||||
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3"
|
||||
do
|
||||
test -f "$tmpdepfile" && break
|
||||
done
|
||||
if test -f "$tmpdepfile"; then
|
||||
# Each line is of the form `foo.o: dependent.h'.
|
||||
# Do two passes, one to just change these to
|
||||
# `$object: dependent.h' and one to simply `dependent.h:'.
|
||||
sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
|
||||
# That's a tab and a space in the [].
|
||||
sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
|
||||
else
|
||||
# The sourcefile does not contain any dependencies, so just
|
||||
# store a dummy comment line, to avoid errors with the Makefile
|
||||
# "include basename.Plo" scheme.
|
||||
echo "#dummy" > "$depfile"
|
||||
fi
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
icc)
|
||||
# Intel's C compiler understands `-MD -MF file'. However on
|
||||
# icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
|
||||
# ICC 7.0 will fill foo.d with something like
|
||||
# foo.o: sub/foo.c
|
||||
# foo.o: sub/foo.h
|
||||
# which is wrong. We want:
|
||||
# sub/foo.o: sub/foo.c
|
||||
# sub/foo.o: sub/foo.h
|
||||
# sub/foo.c:
|
||||
# sub/foo.h:
|
||||
# ICC 7.1 will output
|
||||
# foo.o: sub/foo.c sub/foo.h
|
||||
# and will wrap long lines using \ :
|
||||
# foo.o: sub/foo.c ... \
|
||||
# sub/foo.h ... \
|
||||
# ...
|
||||
|
||||
"$@" -MD -MF "$tmpdepfile"
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile"
|
||||
exit $stat
|
||||
fi
|
||||
rm -f "$depfile"
|
||||
# Each line is of the form `foo.o: dependent.h',
|
||||
# or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
|
||||
# Do two passes, one to just change these to
|
||||
# `$object: dependent.h' and one to simply `dependent.h:'.
|
||||
sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
|
||||
# Some versions of the HPUX 10.20 sed can't process this invocation
|
||||
# correctly. Breaking it into two sed invocations is a workaround.
|
||||
sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" |
|
||||
sed -e 's/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
hp2)
|
||||
# The "hp" stanza above does not work with aCC (C++) and HP's ia64
|
||||
# compilers, which have integrated preprocessors. The correct option
|
||||
# to use with these is +Maked; it writes dependencies to a file named
|
||||
# 'foo.d', which lands next to the object file, wherever that
|
||||
# happens to be.
|
||||
# Much of this is similar to the tru64 case; see comments there.
|
||||
dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
|
||||
test "x$dir" = "x$object" && dir=
|
||||
base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
|
||||
if test "$libtool" = yes; then
|
||||
tmpdepfile1=$dir$base.d
|
||||
tmpdepfile2=$dir.libs/$base.d
|
||||
"$@" -Wc,+Maked
|
||||
else
|
||||
tmpdepfile1=$dir$base.d
|
||||
tmpdepfile2=$dir$base.d
|
||||
"$@" +Maked
|
||||
fi
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile1" "$tmpdepfile2"
|
||||
exit $stat
|
||||
fi
|
||||
|
||||
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2"
|
||||
do
|
||||
test -f "$tmpdepfile" && break
|
||||
done
|
||||
if test -f "$tmpdepfile"; then
|
||||
sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile"
|
||||
# Add `dependent.h:' lines.
|
||||
sed -ne '2,${
|
||||
s/^ *//
|
||||
s/ \\*$//
|
||||
s/$/:/
|
||||
p
|
||||
}' "$tmpdepfile" >> "$depfile"
|
||||
else
|
||||
echo "#dummy" > "$depfile"
|
||||
fi
|
||||
rm -f "$tmpdepfile" "$tmpdepfile2"
|
||||
;;
|
||||
|
||||
tru64)
|
||||
# The Tru64 compiler uses -MD to generate dependencies as a side
|
||||
# effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
|
||||
# At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
|
||||
# dependencies in `foo.d' instead, so we check for that too.
|
||||
# Subdirectories are respected.
|
||||
dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
|
||||
test "x$dir" = "x$object" && dir=
|
||||
base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
|
||||
|
||||
if test "$libtool" = yes; then
|
||||
# With Tru64 cc, shared objects can also be used to make a
|
||||
# static library. This mechanism is used in libtool 1.4 series to
|
||||
# handle both shared and static libraries in a single compilation.
|
||||
# With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d.
|
||||
#
|
||||
# With libtool 1.5 this exception was removed, and libtool now
|
||||
# generates 2 separate objects for the 2 libraries. These two
|
||||
# compilations output dependencies in $dir.libs/$base.o.d and
|
||||
# in $dir$base.o.d. We have to check for both files, because
|
||||
# one of the two compilations can be disabled. We should prefer
|
||||
# $dir$base.o.d over $dir.libs/$base.o.d because the latter is
|
||||
# automatically cleaned when .libs/ is deleted, while ignoring
|
||||
# the former would cause a distcleancheck panic.
|
||||
tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4
|
||||
tmpdepfile2=$dir$base.o.d # libtool 1.5
|
||||
tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5
|
||||
tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504
|
||||
"$@" -Wc,-MD
|
||||
else
|
||||
tmpdepfile1=$dir$base.o.d
|
||||
tmpdepfile2=$dir$base.d
|
||||
tmpdepfile3=$dir$base.d
|
||||
tmpdepfile4=$dir$base.d
|
||||
"$@" -MD
|
||||
fi
|
||||
|
||||
stat=$?
|
||||
if test $stat -eq 0; then :
|
||||
else
|
||||
rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
|
||||
exit $stat
|
||||
fi
|
||||
|
||||
for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4"
|
||||
do
|
||||
test -f "$tmpdepfile" && break
|
||||
done
|
||||
if test -f "$tmpdepfile"; then
|
||||
sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
|
||||
# That's a tab and a space in the [].
|
||||
sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
|
||||
else
|
||||
echo "#dummy" > "$depfile"
|
||||
fi
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
#nosideeffect)
|
||||
# This comment above is used by automake to tell side-effect
|
||||
# dependency tracking mechanisms from slower ones.
|
||||
|
||||
dashmstdout)
|
||||
# Important note: in order to support this mode, a compiler *must*
|
||||
# always write the preprocessed file to stdout, regardless of -o.
|
||||
"$@" || exit $?
|
||||
|
||||
# Remove the call to Libtool.
|
||||
if test "$libtool" = yes; then
|
||||
while test "X$1" != 'X--mode=compile'; do
|
||||
shift
|
||||
done
|
||||
shift
|
||||
fi
|
||||
|
||||
# Remove `-o $object'.
|
||||
IFS=" "
|
||||
for arg
|
||||
do
|
||||
case $arg in
|
||||
-o)
|
||||
shift
|
||||
;;
|
||||
$object)
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
set fnord "$@" "$arg"
|
||||
shift # fnord
|
||||
shift # $arg
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
test -z "$dashmflag" && dashmflag=-M
|
||||
# Require at least two characters before searching for `:'
|
||||
# in the target name. This is to cope with DOS-style filenames:
|
||||
# a dependency such as `c:/foo/bar' could be seen as target `c' otherwise.
|
||||
"$@" $dashmflag |
|
||||
sed 's:^[ ]*[^: ][^:][^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile"
|
||||
rm -f "$depfile"
|
||||
cat < "$tmpdepfile" > "$depfile"
|
||||
tr ' ' '
|
||||
' < "$tmpdepfile" | \
|
||||
## Some versions of the HPUX 10.20 sed can't process this invocation
|
||||
## correctly. Breaking it into two sed invocations is a workaround.
|
||||
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
dashXmstdout)
|
||||
# This case only exists to satisfy depend.m4. It is never actually
|
||||
# run, as this mode is specially recognized in the preamble.
|
||||
exit 1
|
||||
;;
|
||||
|
||||
makedepend)
|
||||
"$@" || exit $?
|
||||
# Remove any Libtool call
|
||||
if test "$libtool" = yes; then
|
||||
while test "X$1" != 'X--mode=compile'; do
|
||||
shift
|
||||
done
|
||||
shift
|
||||
fi
|
||||
# X makedepend
|
||||
shift
|
||||
cleared=no eat=no
|
||||
for arg
|
||||
do
|
||||
case $cleared in
|
||||
no)
|
||||
set ""; shift
|
||||
cleared=yes ;;
|
||||
esac
|
||||
if test $eat = yes; then
|
||||
eat=no
|
||||
continue
|
||||
fi
|
||||
case "$arg" in
|
||||
-D*|-I*)
|
||||
set fnord "$@" "$arg"; shift ;;
|
||||
# Strip any option that makedepend may not understand. Remove
|
||||
# the object too, otherwise makedepend will parse it as a source file.
|
||||
-arch)
|
||||
eat=yes ;;
|
||||
-*|$object)
|
||||
;;
|
||||
*)
|
||||
set fnord "$@" "$arg"; shift ;;
|
||||
esac
|
||||
done
|
||||
obj_suffix=`echo "$object" | sed 's/^.*\././'`
|
||||
touch "$tmpdepfile"
|
||||
${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
|
||||
rm -f "$depfile"
|
||||
cat < "$tmpdepfile" > "$depfile"
|
||||
sed '1,2d' "$tmpdepfile" | tr ' ' '
|
||||
' | \
|
||||
## Some versions of the HPUX 10.20 sed can't process this invocation
|
||||
## correctly. Breaking it into two sed invocations is a workaround.
|
||||
sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile" "$tmpdepfile".bak
|
||||
;;
|
||||
|
||||
cpp)
|
||||
# Important note: in order to support this mode, a compiler *must*
|
||||
# always write the preprocessed file to stdout.
|
||||
"$@" || exit $?
|
||||
|
||||
# Remove the call to Libtool.
|
||||
if test "$libtool" = yes; then
|
||||
while test "X$1" != 'X--mode=compile'; do
|
||||
shift
|
||||
done
|
||||
shift
|
||||
fi
|
||||
|
||||
# Remove `-o $object'.
|
||||
IFS=" "
|
||||
for arg
|
||||
do
|
||||
case $arg in
|
||||
-o)
|
||||
shift
|
||||
;;
|
||||
$object)
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
set fnord "$@" "$arg"
|
||||
shift # fnord
|
||||
shift # $arg
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
"$@" -E |
|
||||
sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \
|
||||
-e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
|
||||
sed '$ s: \\$::' > "$tmpdepfile"
|
||||
rm -f "$depfile"
|
||||
echo "$object : \\" > "$depfile"
|
||||
cat < "$tmpdepfile" >> "$depfile"
|
||||
sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
msvisualcpp)
|
||||
# Important note: in order to support this mode, a compiler *must*
|
||||
# always write the preprocessed file to stdout.
|
||||
"$@" || exit $?
|
||||
|
||||
# Remove the call to Libtool.
|
||||
if test "$libtool" = yes; then
|
||||
while test "X$1" != 'X--mode=compile'; do
|
||||
shift
|
||||
done
|
||||
shift
|
||||
fi
|
||||
|
||||
IFS=" "
|
||||
for arg
|
||||
do
|
||||
case "$arg" in
|
||||
-o)
|
||||
shift
|
||||
;;
|
||||
$object)
|
||||
shift
|
||||
;;
|
||||
"-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
|
||||
set fnord "$@"
|
||||
shift
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
set fnord "$@" "$arg"
|
||||
shift
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
"$@" -E 2>/dev/null |
|
||||
sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile"
|
||||
rm -f "$depfile"
|
||||
echo "$object : \\" > "$depfile"
|
||||
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile"
|
||||
echo " " >> "$depfile"
|
||||
sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile"
|
||||
rm -f "$tmpdepfile"
|
||||
;;
|
||||
|
||||
msvcmsys)
|
||||
# This case exists only to let depend.m4 do its work. It works by
|
||||
# looking at the text of this script. This case will never be run,
|
||||
# since it is checked for above.
|
||||
exit 1
|
||||
;;
|
||||
|
||||
none)
|
||||
exec "$@"
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "Unknown depmode $depmode" 1>&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
exit 0
|
||||
|
||||
# Local Variables:
|
||||
# mode: shell-script
|
||||
# sh-indentation: 2
|
||||
# eval: (add-hook 'write-file-hooks 'time-stamp)
|
||||
# time-stamp-start: "scriptversion="
|
||||
# time-stamp-format: "%:y-%02m-%02d.%02H"
|
||||
# time-stamp-time-zone: "UTC"
|
||||
# time-stamp-end: "; # UTC"
|
||||
# End:
|
|
@ -1,520 +0,0 @@
|
|||
#!/bin/sh
|
||||
# install - install a program, script, or datafile
|
||||
|
||||
scriptversion=2009-04-28.21; # UTC
|
||||
|
||||
# This originates from X11R5 (mit/util/scripts/install.sh), which was
|
||||
# later released in X11R6 (xc/config/util/install.sh) with the
|
||||
# following copyright and license.
|
||||
#
|
||||
# Copyright (C) 1994 X Consortium
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to
|
||||
# deal in the Software without restriction, including without limitation the
|
||||
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
# sell copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
|
||||
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
|
||||
# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
#
|
||||
# Except as contained in this notice, the name of the X Consortium shall not
|
||||
# be used in advertising or otherwise to promote the sale, use or other deal-
|
||||
# ings in this Software without prior written authorization from the X Consor-
|
||||
# tium.
|
||||
#
|
||||
#
|
||||
# FSF changes to this file are in the public domain.
|
||||
#
|
||||
# Calling this script install-sh is preferred over install.sh, to prevent
|
||||
# `make' implicit rules from creating a file called install from it
|
||||
# when there is no Makefile.
|
||||
#
|
||||
# This script is compatible with the BSD install script, but was written
|
||||
# from scratch.
|
||||
|
||||
nl='
|
||||
'
|
||||
IFS=" "" $nl"
|
||||
|
||||
# set DOITPROG to echo to test this script
|
||||
|
||||
# Don't use :- since 4.3BSD and earlier shells don't like it.
|
||||
doit=${DOITPROG-}
|
||||
if test -z "$doit"; then
|
||||
doit_exec=exec
|
||||
else
|
||||
doit_exec=$doit
|
||||
fi
|
||||
|
||||
# Put in absolute file names if you don't have them in your path;
|
||||
# or use environment vars.
|
||||
|
||||
chgrpprog=${CHGRPPROG-chgrp}
|
||||
chmodprog=${CHMODPROG-chmod}
|
||||
chownprog=${CHOWNPROG-chown}
|
||||
cmpprog=${CMPPROG-cmp}
|
||||
cpprog=${CPPROG-cp}
|
||||
mkdirprog=${MKDIRPROG-mkdir}
|
||||
mvprog=${MVPROG-mv}
|
||||
rmprog=${RMPROG-rm}
|
||||
stripprog=${STRIPPROG-strip}
|
||||
|
||||
posix_glob='?'
|
||||
initialize_posix_glob='
|
||||
test "$posix_glob" != "?" || {
|
||||
if (set -f) 2>/dev/null; then
|
||||
posix_glob=
|
||||
else
|
||||
posix_glob=:
|
||||
fi
|
||||
}
|
||||
'
|
||||
|
||||
posix_mkdir=
|
||||
|
||||
# Desired mode of installed file.
|
||||
mode=0755
|
||||
|
||||
chgrpcmd=
|
||||
chmodcmd=$chmodprog
|
||||
chowncmd=
|
||||
mvcmd=$mvprog
|
||||
rmcmd="$rmprog -f"
|
||||
stripcmd=
|
||||
|
||||
src=
|
||||
dst=
|
||||
dir_arg=
|
||||
dst_arg=
|
||||
|
||||
copy_on_change=false
|
||||
no_target_directory=
|
||||
|
||||
usage="\
|
||||
Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
|
||||
or: $0 [OPTION]... SRCFILES... DIRECTORY
|
||||
or: $0 [OPTION]... -t DIRECTORY SRCFILES...
|
||||
or: $0 [OPTION]... -d DIRECTORIES...
|
||||
|
||||
In the 1st form, copy SRCFILE to DSTFILE.
|
||||
In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
|
||||
In the 4th, create DIRECTORIES.
|
||||
|
||||
Options:
|
||||
--help display this help and exit.
|
||||
--version display version info and exit.
|
||||
|
||||
-c (ignored)
|
||||
-C install only if different (preserve the last data modification time)
|
||||
-d create directories instead of installing files.
|
||||
-g GROUP $chgrpprog installed files to GROUP.
|
||||
-m MODE $chmodprog installed files to MODE.
|
||||
-o USER $chownprog installed files to USER.
|
||||
-s $stripprog installed files.
|
||||
-t DIRECTORY install into DIRECTORY.
|
||||
-T report an error if DSTFILE is a directory.
|
||||
|
||||
Environment variables override the default commands:
|
||||
CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
|
||||
RMPROG STRIPPROG
|
||||
"
|
||||
|
||||
while test $# -ne 0; do
|
||||
case $1 in
|
||||
-c) ;;
|
||||
|
||||
-C) copy_on_change=true;;
|
||||
|
||||
-d) dir_arg=true;;
|
||||
|
||||
-g) chgrpcmd="$chgrpprog $2"
|
||||
shift;;
|
||||
|
||||
--help) echo "$usage"; exit $?;;
|
||||
|
||||
-m) mode=$2
|
||||
case $mode in
|
||||
*' '* | *' '* | *'
|
||||
'* | *'*'* | *'?'* | *'['*)
|
||||
echo "$0: invalid mode: $mode" >&2
|
||||
exit 1;;
|
||||
esac
|
||||
shift;;
|
||||
|
||||
-o) chowncmd="$chownprog $2"
|
||||
shift;;
|
||||
|
||||
-s) stripcmd=$stripprog;;
|
||||
|
||||
-t) dst_arg=$2
|
||||
shift;;
|
||||
|
||||
-T) no_target_directory=true;;
|
||||
|
||||
--version) echo "$0 $scriptversion"; exit $?;;
|
||||
|
||||
--) shift
|
||||
break;;
|
||||
|
||||
-*) echo "$0: invalid option: $1" >&2
|
||||
exit 1;;
|
||||
|
||||
*) break;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
|
||||
# When -d is used, all remaining arguments are directories to create.
|
||||
# When -t is used, the destination is already specified.
|
||||
# Otherwise, the last argument is the destination. Remove it from $@.
|
||||
for arg
|
||||
do
|
||||
if test -n "$dst_arg"; then
|
||||
# $@ is not empty: it contains at least $arg.
|
||||
set fnord "$@" "$dst_arg"
|
||||
shift # fnord
|
||||
fi
|
||||
shift # arg
|
||||
dst_arg=$arg
|
||||
done
|
||||
fi
|
||||
|
||||
if test $# -eq 0; then
|
||||
if test -z "$dir_arg"; then
|
||||
echo "$0: no input file specified." >&2
|
||||
exit 1
|
||||
fi
|
||||
# It's OK to call `install-sh -d' without argument.
|
||||
# This can happen when creating conditional directories.
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if test -z "$dir_arg"; then
|
||||
trap '(exit $?); exit' 1 2 13 15
|
||||
|
||||
# Set umask so as not to create temps with too-generous modes.
|
||||
# However, 'strip' requires both read and write access to temps.
|
||||
case $mode in
|
||||
# Optimize common cases.
|
||||
*644) cp_umask=133;;
|
||||
*755) cp_umask=22;;
|
||||
|
||||
*[0-7])
|
||||
if test -z "$stripcmd"; then
|
||||
u_plus_rw=
|
||||
else
|
||||
u_plus_rw='% 200'
|
||||
fi
|
||||
cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
|
||||
*)
|
||||
if test -z "$stripcmd"; then
|
||||
u_plus_rw=
|
||||
else
|
||||
u_plus_rw=,u+rw
|
||||
fi
|
||||
cp_umask=$mode$u_plus_rw;;
|
||||
esac
|
||||
fi
|
||||
|
||||
for src
|
||||
do
|
||||
# Protect names starting with `-'.
|
||||
case $src in
|
||||
-*) src=./$src;;
|
||||
esac
|
||||
|
||||
if test -n "$dir_arg"; then
|
||||
dst=$src
|
||||
dstdir=$dst
|
||||
test -d "$dstdir"
|
||||
dstdir_status=$?
|
||||
else
|
||||
|
||||
# Waiting for this to be detected by the "$cpprog $src $dsttmp" command
|
||||
# might cause directories to be created, which would be especially bad
|
||||
# if $src (and thus $dsttmp) contains '*'.
|
||||
if test ! -f "$src" && test ! -d "$src"; then
|
||||
echo "$0: $src does not exist." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if test -z "$dst_arg"; then
|
||||
echo "$0: no destination specified." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
dst=$dst_arg
|
||||
# Protect names starting with `-'.
|
||||
case $dst in
|
||||
-*) dst=./$dst;;
|
||||
esac
|
||||
|
||||
# If destination is a directory, append the input filename; won't work
|
||||
# if double slashes aren't ignored.
|
||||
if test -d "$dst"; then
|
||||
if test -n "$no_target_directory"; then
|
||||
echo "$0: $dst_arg: Is a directory" >&2
|
||||
exit 1
|
||||
fi
|
||||
dstdir=$dst
|
||||
dst=$dstdir/`basename "$src"`
|
||||
dstdir_status=0
|
||||
else
|
||||
# Prefer dirname, but fall back on a substitute if dirname fails.
|
||||
dstdir=`
|
||||
(dirname "$dst") 2>/dev/null ||
|
||||
expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
|
||||
X"$dst" : 'X\(//\)[^/]' \| \
|
||||
X"$dst" : 'X\(//\)$' \| \
|
||||
X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
|
||||
echo X"$dst" |
|
||||
sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
|
||||
s//\1/
|
||||
q
|
||||
}
|
||||
/^X\(\/\/\)[^/].*/{
|
||||
s//\1/
|
||||
q
|
||||
}
|
||||
/^X\(\/\/\)$/{
|
||||
s//\1/
|
||||
q
|
||||
}
|
||||
/^X\(\/\).*/{
|
||||
s//\1/
|
||||
q
|
||||
}
|
||||
s/.*/./; q'
|
||||
`
|
||||
|
||||
test -d "$dstdir"
|
||||
dstdir_status=$?
|
||||
fi
|
||||
fi
|
||||
|
||||
obsolete_mkdir_used=false
|
||||
|
||||
if test $dstdir_status != 0; then
|
||||
case $posix_mkdir in
|
||||
'')
|
||||
# Create intermediate dirs using mode 755 as modified by the umask.
|
||||
# This is like FreeBSD 'install' as of 1997-10-28.
|
||||
umask=`umask`
|
||||
case $stripcmd.$umask in
|
||||
# Optimize common cases.
|
||||
*[2367][2367]) mkdir_umask=$umask;;
|
||||
.*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
|
||||
|
||||
*[0-7])
|
||||
mkdir_umask=`expr $umask + 22 \
|
||||
- $umask % 100 % 40 + $umask % 20 \
|
||||
- $umask % 10 % 4 + $umask % 2
|
||||
`;;
|
||||
*) mkdir_umask=$umask,go-w;;
|
||||
esac
|
||||
|
||||
# With -d, create the new directory with the user-specified mode.
|
||||
# Otherwise, rely on $mkdir_umask.
|
||||
if test -n "$dir_arg"; then
|
||||
mkdir_mode=-m$mode
|
||||
else
|
||||
mkdir_mode=
|
||||
fi
|
||||
|
||||
posix_mkdir=false
|
||||
case $umask in
|
||||
*[123567][0-7][0-7])
|
||||
# POSIX mkdir -p sets u+wx bits regardless of umask, which
|
||||
# is incompatible with FreeBSD 'install' when (umask & 300) != 0.
|
||||
;;
|
||||
*)
|
||||
tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
|
||||
trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
|
||||
|
||||
if (umask $mkdir_umask &&
|
||||
exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
|
||||
then
|
||||
if test -z "$dir_arg" || {
|
||||
# Check for POSIX incompatibilities with -m.
|
||||
# HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
|
||||
# other-writeable bit of parent directory when it shouldn't.
|
||||
# FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
|
||||
ls_ld_tmpdir=`ls -ld "$tmpdir"`
|
||||
case $ls_ld_tmpdir in
|
||||
d????-?r-*) different_mode=700;;
|
||||
d????-?--*) different_mode=755;;
|
||||
*) false;;
|
||||
esac &&
|
||||
$mkdirprog -m$different_mode -p -- "$tmpdir" && {
|
||||
ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
|
||||
test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
|
||||
}
|
||||
}
|
||||
then posix_mkdir=:
|
||||
fi
|
||||
rmdir "$tmpdir/d" "$tmpdir"
|
||||
else
|
||||
# Remove any dirs left behind by ancient mkdir implementations.
|
||||
rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
|
||||
fi
|
||||
trap '' 0;;
|
||||
esac;;
|
||||
esac
|
||||
|
||||
if
|
||||
$posix_mkdir && (
|
||||
umask $mkdir_umask &&
|
||||
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
|
||||
)
|
||||
then :
|
||||
else
|
||||
|
||||
# The umask is ridiculous, or mkdir does not conform to POSIX,
|
||||
# or it failed possibly due to a race condition. Create the
|
||||
# directory the slow way, step by step, checking for races as we go.
|
||||
|
||||
case $dstdir in
|
||||
/*) prefix='/';;
|
||||
-*) prefix='./';;
|
||||
*) prefix='';;
|
||||
esac
|
||||
|
||||
eval "$initialize_posix_glob"
|
||||
|
||||
oIFS=$IFS
|
||||
IFS=/
|
||||
$posix_glob set -f
|
||||
set fnord $dstdir
|
||||
shift
|
||||
$posix_glob set +f
|
||||
IFS=$oIFS
|
||||
|
||||
prefixes=
|
||||
|
||||
for d
|
||||
do
|
||||
test -z "$d" && continue
|
||||
|
||||
prefix=$prefix$d
|
||||
if test -d "$prefix"; then
|
||||
prefixes=
|
||||
else
|
||||
if $posix_mkdir; then
|
||||
(umask=$mkdir_umask &&
|
||||
$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
|
||||
# Don't fail if two instances are running concurrently.
|
||||
test -d "$prefix" || exit 1
|
||||
else
|
||||
case $prefix in
|
||||
*\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
|
||||
*) qprefix=$prefix;;
|
||||
esac
|
||||
prefixes="$prefixes '$qprefix'"
|
||||
fi
|
||||
fi
|
||||
prefix=$prefix/
|
||||
done
|
||||
|
||||
if test -n "$prefixes"; then
|
||||
# Don't fail if two instances are running concurrently.
|
||||
(umask $mkdir_umask &&
|
||||
eval "\$doit_exec \$mkdirprog $prefixes") ||
|
||||
test -d "$dstdir" || exit 1
|
||||
obsolete_mkdir_used=true
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if test -n "$dir_arg"; then
|
||||
{ test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
|
||||
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
|
||||
{ test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
|
||||
test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
|
||||
else
|
||||
|
||||
# Make a couple of temp file names in the proper directory.
|
||||
dsttmp=$dstdir/_inst.$$_
|
||||
rmtmp=$dstdir/_rm.$$_
|
||||
|
||||
# Trap to clean up those temp files at exit.
|
||||
trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
|
||||
|
||||
# Copy the file name to the temp name.
|
||||
(umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
|
||||
|
||||
# and set any options; do chmod last to preserve setuid bits.
|
||||
#
|
||||
# If any of these fail, we abort the whole thing. If we want to
|
||||
# ignore errors from any of these, just make sure not to ignore
|
||||
# errors from the above "$doit $cpprog $src $dsttmp" command.
|
||||
#
|
||||
{ test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
|
||||
{ test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
|
||||
{ test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
|
||||
{ test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
|
||||
|
||||
# If -C, don't bother to copy if it wouldn't change the file.
|
||||
if $copy_on_change &&
|
||||
old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` &&
|
||||
new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
|
||||
|
||||
eval "$initialize_posix_glob" &&
|
||||
$posix_glob set -f &&
|
||||
set X $old && old=:$2:$4:$5:$6 &&
|
||||
set X $new && new=:$2:$4:$5:$6 &&
|
||||
$posix_glob set +f &&
|
||||
|
||||
test "$old" = "$new" &&
|
||||
$cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
|
||||
then
|
||||
rm -f "$dsttmp"
|
||||
else
|
||||
# Rename the file to the real destination.
|
||||
$doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
|
||||
|
||||
# The rename failed, perhaps because mv can't rename something else
|
||||
# to itself, or perhaps because mv is so ancient that it does not
|
||||
# support -f.
|
||||
{
|
||||
# Now remove or move aside any old file at destination location.
|
||||
# We try this two ways since rm can't unlink itself on some
|
||||
# systems and the destination file might be busy for other
|
||||
# reasons. In this case, the final cleanup might fail but the new
|
||||
# file should still install successfully.
|
||||
{
|
||||
test ! -f "$dst" ||
|
||||
$doit $rmcmd -f "$dst" 2>/dev/null ||
|
||||
{ $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
|
||||
{ $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
|
||||
} ||
|
||||
{ echo "$0: cannot unlink or rename $dst" >&2
|
||||
(exit 1); exit 1
|
||||
}
|
||||
} &&
|
||||
|
||||
# Now rename the file to the real destination.
|
||||
$doit $mvcmd "$dsttmp" "$dst"
|
||||
}
|
||||
fi || exit 1
|
||||
|
||||
trap '' 0
|
||||
fi
|
||||
done
|
||||
|
||||
# Local variables:
|
||||
# eval: (add-hook 'write-file-hooks 'time-stamp)
|
||||
# time-stamp-start: "scriptversion="
|
||||
# time-stamp-format: "%:y-%02m-%02d.%02H"
|
||||
# time-stamp-time-zone: "UTC"
|
||||
# time-stamp-end: "; # UTC"
|
||||
# End:
|
File diff suppressed because it is too large
Load Diff
|
@ -1,376 +0,0 @@
|
|||
#! /bin/sh
|
||||
# Common stub for a few missing GNU programs while installing.
|
||||
|
||||
scriptversion=2009-04-28.21; # UTC
|
||||
|
||||
# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006,
|
||||
# 2008, 2009 Free Software Foundation, Inc.
|
||||
# Originally by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
|
||||
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2, or (at your option)
|
||||
# any later version.
|
||||
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# As a special exception to the GNU General Public License, if you
|
||||
# distribute this file as part of a program that contains a
|
||||
# configuration script generated by Autoconf, you may include it under
|
||||
# the same distribution terms that you use for the rest of that program.
|
||||
|
||||
if test $# -eq 0; then
|
||||
echo 1>&2 "Try \`$0 --help' for more information"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
run=:
|
||||
sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p'
|
||||
sed_minuso='s/.* -o \([^ ]*\).*/\1/p'
|
||||
|
||||
# In the cases where this matters, `missing' is being run in the
|
||||
# srcdir already.
|
||||
if test -f configure.ac; then
|
||||
configure_ac=configure.ac
|
||||
else
|
||||
configure_ac=configure.in
|
||||
fi
|
||||
|
||||
msg="missing on your system"
|
||||
|
||||
case $1 in
|
||||
--run)
|
||||
# Try to run requested program, and just exit if it succeeds.
|
||||
run=
|
||||
shift
|
||||
"$@" && exit 0
|
||||
# Exit code 63 means version mismatch. This often happens
|
||||
# when the user try to use an ancient version of a tool on
|
||||
# a file that requires a minimum version. In this case we
|
||||
# we should proceed has if the program had been absent, or
|
||||
# if --run hadn't been passed.
|
||||
if test $? = 63; then
|
||||
run=:
|
||||
msg="probably too old"
|
||||
fi
|
||||
;;
|
||||
|
||||
-h|--h|--he|--hel|--help)
|
||||
echo "\
|
||||
$0 [OPTION]... PROGRAM [ARGUMENT]...
|
||||
|
||||
Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
|
||||
error status if there is no known handling for PROGRAM.
|
||||
|
||||
Options:
|
||||
-h, --help display this help and exit
|
||||
-v, --version output version information and exit
|
||||
--run try to run the given command, and emulate it if it fails
|
||||
|
||||
Supported PROGRAM values:
|
||||
aclocal touch file \`aclocal.m4'
|
||||
autoconf touch file \`configure'
|
||||
autoheader touch file \`config.h.in'
|
||||
autom4te touch the output file, or create a stub one
|
||||
automake touch all \`Makefile.in' files
|
||||
bison create \`y.tab.[ch]', if possible, from existing .[ch]
|
||||
flex create \`lex.yy.c', if possible, from existing .c
|
||||
help2man touch the output file
|
||||
lex create \`lex.yy.c', if possible, from existing .c
|
||||
makeinfo touch the output file
|
||||
tar try tar, gnutar, gtar, then tar without non-portable flags
|
||||
yacc create \`y.tab.[ch]', if possible, from existing .[ch]
|
||||
|
||||
Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and
|
||||
\`g' are ignored when checking the name.
|
||||
|
||||
Send bug reports to <bug-automake@gnu.org>."
|
||||
exit $?
|
||||
;;
|
||||
|
||||
-v|--v|--ve|--ver|--vers|--versi|--versio|--version)
|
||||
echo "missing $scriptversion (GNU Automake)"
|
||||
exit $?
|
||||
;;
|
||||
|
||||
-*)
|
||||
echo 1>&2 "$0: Unknown \`$1' option"
|
||||
echo 1>&2 "Try \`$0 --help' for more information"
|
||||
exit 1
|
||||
;;
|
||||
|
||||
esac
|
||||
|
||||
# normalize program name to check for.
|
||||
program=`echo "$1" | sed '
|
||||
s/^gnu-//; t
|
||||
s/^gnu//; t
|
||||
s/^g//; t'`
|
||||
|
||||
# Now exit if we have it, but it failed. Also exit now if we
|
||||
# don't have it and --version was passed (most likely to detect
|
||||
# the program). This is about non-GNU programs, so use $1 not
|
||||
# $program.
|
||||
case $1 in
|
||||
lex*|yacc*)
|
||||
# Not GNU programs, they don't have --version.
|
||||
;;
|
||||
|
||||
tar*)
|
||||
if test -n "$run"; then
|
||||
echo 1>&2 "ERROR: \`tar' requires --run"
|
||||
exit 1
|
||||
elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
|
||||
*)
|
||||
if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
|
||||
# We have it, but it failed.
|
||||
exit 1
|
||||
elif test "x$2" = "x--version" || test "x$2" = "x--help"; then
|
||||
# Could not run --version or --help. This is probably someone
|
||||
# running `$TOOL --version' or `$TOOL --help' to check whether
|
||||
# $TOOL exists and not knowing $TOOL uses missing.
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
# If it does not exist, or fails to run (possibly an outdated version),
|
||||
# try to emulate it.
|
||||
case $program in
|
||||
aclocal*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is $msg. You should only need it if
|
||||
you modified \`acinclude.m4' or \`${configure_ac}'. You might want
|
||||
to install the \`Automake' and \`Perl' packages. Grab them from
|
||||
any GNU archive site."
|
||||
touch aclocal.m4
|
||||
;;
|
||||
|
||||
autoconf*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is $msg. You should only need it if
|
||||
you modified \`${configure_ac}'. You might want to install the
|
||||
\`Autoconf' and \`GNU m4' packages. Grab them from any GNU
|
||||
archive site."
|
||||
touch configure
|
||||
;;
|
||||
|
||||
autoheader*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is $msg. You should only need it if
|
||||
you modified \`acconfig.h' or \`${configure_ac}'. You might want
|
||||
to install the \`Autoconf' and \`GNU m4' packages. Grab them
|
||||
from any GNU archive site."
|
||||
files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}`
|
||||
test -z "$files" && files="config.h"
|
||||
touch_files=
|
||||
for f in $files; do
|
||||
case $f in
|
||||
*:*) touch_files="$touch_files "`echo "$f" |
|
||||
sed -e 's/^[^:]*://' -e 's/:.*//'`;;
|
||||
*) touch_files="$touch_files $f.in";;
|
||||
esac
|
||||
done
|
||||
touch $touch_files
|
||||
;;
|
||||
|
||||
automake*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is $msg. You should only need it if
|
||||
you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
|
||||
You might want to install the \`Automake' and \`Perl' packages.
|
||||
Grab them from any GNU archive site."
|
||||
find . -type f -name Makefile.am -print |
|
||||
sed 's/\.am$/.in/' |
|
||||
while read f; do touch "$f"; done
|
||||
;;
|
||||
|
||||
autom4te*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is needed, but is $msg.
|
||||
You might have modified some files without having the
|
||||
proper tools for further handling them.
|
||||
You can get \`$1' as part of \`Autoconf' from any GNU
|
||||
archive site."
|
||||
|
||||
file=`echo "$*" | sed -n "$sed_output"`
|
||||
test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
|
||||
if test -f "$file"; then
|
||||
touch $file
|
||||
else
|
||||
test -z "$file" || exec >$file
|
||||
echo "#! /bin/sh"
|
||||
echo "# Created by GNU Automake missing as a replacement of"
|
||||
echo "# $ $@"
|
||||
echo "exit 0"
|
||||
chmod +x $file
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
|
||||
bison*|yacc*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' $msg. You should only need it if
|
||||
you modified a \`.y' file. You may need the \`Bison' package
|
||||
in order for those modifications to take effect. You can get
|
||||
\`Bison' from any GNU archive site."
|
||||
rm -f y.tab.c y.tab.h
|
||||
if test $# -ne 1; then
|
||||
eval LASTARG="\${$#}"
|
||||
case $LASTARG in
|
||||
*.y)
|
||||
SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
|
||||
if test -f "$SRCFILE"; then
|
||||
cp "$SRCFILE" y.tab.c
|
||||
fi
|
||||
SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
|
||||
if test -f "$SRCFILE"; then
|
||||
cp "$SRCFILE" y.tab.h
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
if test ! -f y.tab.h; then
|
||||
echo >y.tab.h
|
||||
fi
|
||||
if test ! -f y.tab.c; then
|
||||
echo 'main() { return 0; }' >y.tab.c
|
||||
fi
|
||||
;;
|
||||
|
||||
lex*|flex*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is $msg. You should only need it if
|
||||
you modified a \`.l' file. You may need the \`Flex' package
|
||||
in order for those modifications to take effect. You can get
|
||||
\`Flex' from any GNU archive site."
|
||||
rm -f lex.yy.c
|
||||
if test $# -ne 1; then
|
||||
eval LASTARG="\${$#}"
|
||||
case $LASTARG in
|
||||
*.l)
|
||||
SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
|
||||
if test -f "$SRCFILE"; then
|
||||
cp "$SRCFILE" lex.yy.c
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
if test ! -f lex.yy.c; then
|
||||
echo 'main() { return 0; }' >lex.yy.c
|
||||
fi
|
||||
;;
|
||||
|
||||
help2man*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is $msg. You should only need it if
|
||||
you modified a dependency of a manual page. You may need the
|
||||
\`Help2man' package in order for those modifications to take
|
||||
effect. You can get \`Help2man' from any GNU archive site."
|
||||
|
||||
file=`echo "$*" | sed -n "$sed_output"`
|
||||
test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
|
||||
if test -f "$file"; then
|
||||
touch $file
|
||||
else
|
||||
test -z "$file" || exec >$file
|
||||
echo ".ab help2man is required to generate this page"
|
||||
exit $?
|
||||
fi
|
||||
;;
|
||||
|
||||
makeinfo*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is $msg. You should only need it if
|
||||
you modified a \`.texi' or \`.texinfo' file, or any other file
|
||||
indirectly affecting the aspect of the manual. The spurious
|
||||
call might also be the consequence of using a buggy \`make' (AIX,
|
||||
DU, IRIX). You might want to install the \`Texinfo' package or
|
||||
the \`GNU make' package. Grab either from any GNU archive site."
|
||||
# The file to touch is that specified with -o ...
|
||||
file=`echo "$*" | sed -n "$sed_output"`
|
||||
test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"`
|
||||
if test -z "$file"; then
|
||||
# ... or it is the one specified with @setfilename ...
|
||||
infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
|
||||
file=`sed -n '
|
||||
/^@setfilename/{
|
||||
s/.* \([^ ]*\) *$/\1/
|
||||
p
|
||||
q
|
||||
}' $infile`
|
||||
# ... or it is derived from the source name (dir/f.texi becomes f.info)
|
||||
test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info
|
||||
fi
|
||||
# If the file does not exist, the user really needs makeinfo;
|
||||
# let's fail without touching anything.
|
||||
test -f $file || exit 1
|
||||
touch $file
|
||||
;;
|
||||
|
||||
tar*)
|
||||
shift
|
||||
|
||||
# We have already tried tar in the generic part.
|
||||
# Look for gnutar/gtar before invocation to avoid ugly error
|
||||
# messages.
|
||||
if (gnutar --version > /dev/null 2>&1); then
|
||||
gnutar "$@" && exit 0
|
||||
fi
|
||||
if (gtar --version > /dev/null 2>&1); then
|
||||
gtar "$@" && exit 0
|
||||
fi
|
||||
firstarg="$1"
|
||||
if shift; then
|
||||
case $firstarg in
|
||||
*o*)
|
||||
firstarg=`echo "$firstarg" | sed s/o//`
|
||||
tar "$firstarg" "$@" && exit 0
|
||||
;;
|
||||
esac
|
||||
case $firstarg in
|
||||
*h*)
|
||||
firstarg=`echo "$firstarg" | sed s/h//`
|
||||
tar "$firstarg" "$@" && exit 0
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
echo 1>&2 "\
|
||||
WARNING: I can't seem to be able to run \`tar' with the given arguments.
|
||||
You may want to install GNU tar or Free paxutils, or check the
|
||||
command line arguments."
|
||||
exit 1
|
||||
;;
|
||||
|
||||
*)
|
||||
echo 1>&2 "\
|
||||
WARNING: \`$1' is needed, and is $msg.
|
||||
You might have modified some files without having the
|
||||
proper tools for further handling them. Check the \`README' file,
|
||||
it often tells you about the needed prerequisites for installing
|
||||
this package. You may also peek at any GNU archive site, in case
|
||||
some other package would contain this missing \`$1' program."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
exit 0
|
||||
|
||||
# Local variables:
|
||||
# eval: (add-hook 'write-file-hooks 'time-stamp)
|
||||
# time-stamp-start: "scriptversion="
|
||||
# time-stamp-format: "%:y-%02m-%02d.%02H"
|
||||
# time-stamp-time-zone: "UTC"
|
||||
# time-stamp-end: "; # UTC"
|
||||
# End:
|
|
@ -0,0 +1,9 @@
|
|||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gmock
|
||||
Description: GoogleMock (without main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
|
|
@ -0,0 +1,9 @@
|
|||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gmock_main
|
||||
Description: GoogleMock (with main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@
|
File diff suppressed because it is too large
Load Diff
|
@ -1,13 +1,13 @@
|
|||
m4_include(gtest/m4/acx_pthread.m4)
|
||||
m4_include(../googletest/m4/acx_pthread.m4)
|
||||
|
||||
AC_INIT([Google C++ Mocking Framework],
|
||||
[1.6.0],
|
||||
[1.8.0],
|
||||
[googlemock@googlegroups.com],
|
||||
[gmock])
|
||||
|
||||
# Provide various options to initialize the Autoconf and configure processes.
|
||||
AC_PREREQ([2.59])
|
||||
AC_CONFIG_SRCDIR([./COPYING])
|
||||
AC_CONFIG_SRCDIR([./LICENSE])
|
||||
AC_CONFIG_AUX_DIR([build-aux])
|
||||
AC_CONFIG_HEADERS([build-aux/config.h])
|
||||
AC_CONFIG_FILES([Makefile])
|
||||
|
@ -101,7 +101,7 @@ AC_ARG_VAR([GTEST_VERSION],
|
|||
[The version of Google Test available.])
|
||||
HAVE_BUILT_GTEST="no"
|
||||
|
||||
GTEST_MIN_VERSION="1.6.0"
|
||||
GTEST_MIN_VERSION="1.8.0"
|
||||
|
||||
AS_IF([test "x${enable_external_gtest}" = "xyes"],
|
||||
[# Begin filling in variables as we are able.
|
||||
|
@ -129,14 +129,14 @@ AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"],
|
|||
GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags`
|
||||
GTEST_LIBS=`${GTEST_CONFIG} --libs`
|
||||
GTEST_VERSION=`${GTEST_CONFIG} --version`],
|
||||
[AC_CONFIG_SUBDIRS([gtest])
|
||||
# GTEST_CONFIG needs to be executable both in a Makefile environmont and
|
||||
[
|
||||
# GTEST_CONFIG needs to be executable both in a Makefile environment and
|
||||
# in a shell script environment, so resolve an absolute path for it here.
|
||||
GTEST_CONFIG="`pwd -P`/gtest/scripts/gtest-config"
|
||||
GTEST_CPPFLAGS='-I$(top_srcdir)/gtest/include'
|
||||
GTEST_CONFIG="`pwd -P`/../googletest/scripts/gtest-config"
|
||||
GTEST_CPPFLAGS='-I$(top_srcdir)/../googletest/include'
|
||||
GTEST_CXXFLAGS='-g'
|
||||
GTEST_LDFLAGS=''
|
||||
GTEST_LIBS='$(top_builddir)/gtest/lib/libgtest.la'
|
||||
GTEST_LIBS='$(top_builddir)/../googletest/lib/libgtest.la'
|
||||
GTEST_VERSION="${GTEST_MIN_VERSION}"])
|
||||
|
||||
# TODO(chandlerc@google.com) Check the types, structures, and other compiler
|
||||
|
|
|
@ -0,0 +1,564 @@
|
|||
|
||||
|
||||
# Defining a Mock Class #
|
||||
|
||||
## Mocking a Normal Class ##
|
||||
|
||||
Given
|
||||
```
|
||||
class Foo {
|
||||
...
|
||||
virtual ~Foo();
|
||||
virtual int GetSize() const = 0;
|
||||
virtual string Describe(const char* name) = 0;
|
||||
virtual string Describe(int type) = 0;
|
||||
virtual bool Process(Bar elem, int count) = 0;
|
||||
};
|
||||
```
|
||||
(note that `~Foo()` **must** be virtual) we can define its mock as
|
||||
```
|
||||
#include "gmock/gmock.h"
|
||||
|
||||
class MockFoo : public Foo {
|
||||
MOCK_CONST_METHOD0(GetSize, int());
|
||||
MOCK_METHOD1(Describe, string(const char* name));
|
||||
MOCK_METHOD1(Describe, string(int type));
|
||||
MOCK_METHOD2(Process, bool(Bar elem, int count));
|
||||
};
|
||||
```
|
||||
|
||||
To create a "nice" mock object which ignores all uninteresting calls,
|
||||
or a "strict" mock object, which treats them as failures:
|
||||
```
|
||||
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
|
||||
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
|
||||
```
|
||||
|
||||
## Mocking a Class Template ##
|
||||
|
||||
To mock
|
||||
```
|
||||
template <typename Elem>
|
||||
class StackInterface {
|
||||
public:
|
||||
...
|
||||
virtual ~StackInterface();
|
||||
virtual int GetSize() const = 0;
|
||||
virtual void Push(const Elem& x) = 0;
|
||||
};
|
||||
```
|
||||
(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros:
|
||||
```
|
||||
template <typename Elem>
|
||||
class MockStack : public StackInterface<Elem> {
|
||||
public:
|
||||
...
|
||||
MOCK_CONST_METHOD0_T(GetSize, int());
|
||||
MOCK_METHOD1_T(Push, void(const Elem& x));
|
||||
};
|
||||
```
|
||||
|
||||
## Specifying Calling Conventions for Mock Functions ##
|
||||
|
||||
If your mock function doesn't use the default calling convention, you
|
||||
can specify it by appending `_WITH_CALLTYPE` to any of the macros
|
||||
described in the previous two sections and supplying the calling
|
||||
convention as the first argument to the macro. For example,
|
||||
```
|
||||
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n));
|
||||
MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y));
|
||||
```
|
||||
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
|
||||
|
||||
# Using Mocks in Tests #
|
||||
|
||||
The typical flow is:
|
||||
1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted.
|
||||
1. Create the mock objects.
|
||||
1. Optionally, set the default actions of the mock objects.
|
||||
1. Set your expectations on the mock objects (How will they be called? What wil they do?).
|
||||
1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](../../googletest/) assertions.
|
||||
1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied.
|
||||
|
||||
Here is an example:
|
||||
```
|
||||
using ::testing::Return; // #1
|
||||
|
||||
TEST(BarTest, DoesThis) {
|
||||
MockFoo foo; // #2
|
||||
|
||||
ON_CALL(foo, GetSize()) // #3
|
||||
.WillByDefault(Return(1));
|
||||
// ... other default actions ...
|
||||
|
||||
EXPECT_CALL(foo, Describe(5)) // #4
|
||||
.Times(3)
|
||||
.WillRepeatedly(Return("Category 5"));
|
||||
// ... other expectations ...
|
||||
|
||||
EXPECT_EQ("good", MyProductionFunction(&foo)); // #5
|
||||
} // #6
|
||||
```
|
||||
|
||||
# Setting Default Actions #
|
||||
|
||||
Google Mock has a **built-in default action** for any function that
|
||||
returns `void`, `bool`, a numeric value, or a pointer.
|
||||
|
||||
To customize the default action for functions with return type `T` globally:
|
||||
```
|
||||
using ::testing::DefaultValue;
|
||||
|
||||
// Sets the default value to be returned. T must be CopyConstructible.
|
||||
DefaultValue<T>::Set(value);
|
||||
// Sets a factory. Will be invoked on demand. T must be MoveConstructible.
|
||||
// T MakeT();
|
||||
DefaultValue<T>::SetFactory(&MakeT);
|
||||
// ... use the mocks ...
|
||||
// Resets the default value.
|
||||
DefaultValue<T>::Clear();
|
||||
```
|
||||
|
||||
To customize the default action for a particular method, use `ON_CALL()`:
|
||||
```
|
||||
ON_CALL(mock_object, method(matchers))
|
||||
.With(multi_argument_matcher) ?
|
||||
.WillByDefault(action);
|
||||
```
|
||||
|
||||
# Setting Expectations #
|
||||
|
||||
`EXPECT_CALL()` sets **expectations** on a mock method (How will it be
|
||||
called? What will it do?):
|
||||
```
|
||||
EXPECT_CALL(mock_object, method(matchers))
|
||||
.With(multi_argument_matcher) ?
|
||||
.Times(cardinality) ?
|
||||
.InSequence(sequences) *
|
||||
.After(expectations) *
|
||||
.WillOnce(action) *
|
||||
.WillRepeatedly(action) ?
|
||||
.RetiresOnSaturation(); ?
|
||||
```
|
||||
|
||||
If `Times()` is omitted, the cardinality is assumed to be:
|
||||
|
||||
* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`;
|
||||
* `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or
|
||||
* `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0.
|
||||
|
||||
A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time.
|
||||
|
||||
# Matchers #
|
||||
|
||||
A **matcher** matches a _single_ argument. You can use it inside
|
||||
`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value
|
||||
directly:
|
||||
|
||||
| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. |
|
||||
|:------------------------------|:----------------------------------------|
|
||||
| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. |
|
||||
|
||||
Built-in matchers (where `argument` is the function argument) are
|
||||
divided into several categories:
|
||||
|
||||
## Wildcard ##
|
||||
|`_`|`argument` can be any value of the correct type.|
|
||||
|:--|:-----------------------------------------------|
|
||||
|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. |
|
||||
|
||||
## Generic Comparison ##
|
||||
|
||||
|`Eq(value)` or `value`|`argument == value`|
|
||||
|:---------------------|:------------------|
|
||||
|`Ge(value)` |`argument >= value`|
|
||||
|`Gt(value)` |`argument > value` |
|
||||
|`Le(value)` |`argument <= value`|
|
||||
|`Lt(value)` |`argument < value` |
|
||||
|`Ne(value)` |`argument != value`|
|
||||
|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).|
|
||||
|`NotNull()` |`argument` is a non-null pointer (raw or smart).|
|
||||
|`VariantWith<T>(m)` |`argument` is `variant<>` that holds the alternative of
|
||||
type T with a value matching `m`.|
|
||||
|`Ref(variable)` |`argument` is a reference to `variable`.|
|
||||
|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.|
|
||||
|
||||
Except `Ref()`, these matchers make a _copy_ of `value` in case it's
|
||||
modified or destructed later. If the compiler complains that `value`
|
||||
doesn't have a public copy constructor, try wrap it in `ByRef()`,
|
||||
e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure
|
||||
`non_copyable_value` is not changed afterwards, or the meaning of your
|
||||
matcher will be changed.
|
||||
|
||||
## Floating-Point Matchers ##
|
||||
|
||||
|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.|
|
||||
|:-------------------|:----------------------------------------------------------------------------------------------|
|
||||
|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |
|
||||
|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |
|
||||
|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |
|
||||
|
||||
The above matchers use ULP-based comparison (the same as used in
|
||||
[Google Test](../../googletest/)). They
|
||||
automatically pick a reasonable error bound based on the absolute
|
||||
value of the expected value. `DoubleEq()` and `FloatEq()` conform to
|
||||
the IEEE standard, which requires comparing two NaNs for equality to
|
||||
return false. The `NanSensitive*` version instead treats two NaNs as
|
||||
equal, which is often what a user wants.
|
||||
|
||||
|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.|
|
||||
|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------|
|
||||
|`FloatNear(a_float, max_abs_error)` |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
|
||||
|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
|
||||
|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
|
||||
|
||||
## String Matchers ##
|
||||
|
||||
The `argument` can be either a C string or a C++ string object:
|
||||
|
||||
|`ContainsRegex(string)`|`argument` matches the given regular expression.|
|
||||
|:----------------------|:-----------------------------------------------|
|
||||
|`EndsWith(suffix)` |`argument` ends with string `suffix`. |
|
||||
|`HasSubstr(string)` |`argument` contains `string` as a sub-string. |
|
||||
|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.|
|
||||
|`StartsWith(prefix)` |`argument` starts with string `prefix`. |
|
||||
|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. |
|
||||
|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.|
|
||||
|`StrEq(string)` |`argument` is equal to `string`. |
|
||||
|`StrNe(string)` |`argument` is not equal to `string`. |
|
||||
|
||||
`ContainsRegex()` and `MatchesRegex()` use the regular expression
|
||||
syntax defined
|
||||
[here](../../googletest/docs/advanced.md#regular-expression-syntax).
|
||||
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
|
||||
strings as well.
|
||||
|
||||
## Container Matchers ##
|
||||
|
||||
Most STL-style containers support `==`, so you can use
|
||||
`Eq(expected_container)` or simply `expected_container` to match a
|
||||
container exactly. If you want to write the elements in-line,
|
||||
match them more flexibly, or get more informative messages, you can use:
|
||||
|
||||
| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
|
||||
|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |
|
||||
| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. |
|
||||
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. |
|
||||
| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
|
||||
| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |
|
||||
| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
|
||||
| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. |
|
||||
| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. |
|
||||
| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. |
|
||||
| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. |
|
||||
| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. |
|
||||
|
||||
Notes:
|
||||
|
||||
* These matchers can also match:
|
||||
1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and
|
||||
1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)).
|
||||
* The array being matched may be multi-dimensional (i.e. its elements can be arrays).
|
||||
* `m` in `Pointwise(m, ...)` should be a matcher for `::testing::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write:
|
||||
|
||||
```
|
||||
using ::testing::get;
|
||||
MATCHER(FooEq, "") {
|
||||
return get<0>(arg).Equals(get<1>(arg));
|
||||
}
|
||||
...
|
||||
EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
|
||||
```
|
||||
|
||||
## Member Matchers ##
|
||||
|
||||
|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
|
||||
|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.|
|
||||
|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |
|
||||
|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.|
|
||||
|
||||
## Matching the Result of a Function or Functor ##
|
||||
|
||||
|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.|
|
||||
|:---------------|:---------------------------------------------------------------------|
|
||||
|
||||
## Pointer Matchers ##
|
||||
|
||||
|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.|
|
||||
|:-----------|:-----------------------------------------------------------------------------------------------|
|
||||
|`WhenDynamicCastTo<T>(m)`| when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |
|
||||
|
||||
## Multiargument Matchers ##
|
||||
|
||||
Technically, all matchers match a _single_ value. A "multi-argument"
|
||||
matcher is just one that matches a _tuple_. The following matchers can
|
||||
be used to match a tuple `(x, y)`:
|
||||
|
||||
|`Eq()`|`x == y`|
|
||||
|:-----|:-------|
|
||||
|`Ge()`|`x >= y`|
|
||||
|`Gt()`|`x > y` |
|
||||
|`Le()`|`x <= y`|
|
||||
|`Lt()`|`x < y` |
|
||||
|`Ne()`|`x != y`|
|
||||
|
||||
You can use the following selectors to pick a subset of the arguments
|
||||
(or reorder them) to participate in the matching:
|
||||
|
||||
|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.|
|
||||
|:-----------|:-------------------------------------------------------------------|
|
||||
|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.|
|
||||
|
||||
## Composite Matchers ##
|
||||
|
||||
You can make a matcher from one or more other matchers:
|
||||
|
||||
|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.|
|
||||
|:-----------------------|:---------------------------------------------------|
|
||||
|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.|
|
||||
|`Not(m)` |`argument` doesn't match matcher `m`. |
|
||||
|
||||
## Adapters for Matchers ##
|
||||
|
||||
|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.|
|
||||
|:------------------|:--------------------------------------|
|
||||
|`SafeMatcherCast<T>(m)`| [safely casts](CookBook.md#casting-matchers) matcher `m` to type `Matcher<T>`. |
|
||||
|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.|
|
||||
|
||||
## Matchers as Predicates ##
|
||||
|
||||
|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.|
|
||||
|:------------------|:---------------------------------------------------------------------------------------------|
|
||||
|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. |
|
||||
|`Value(value, m)` |evaluates to `true` if `value` matches `m`. |
|
||||
|
||||
## Defining Matchers ##
|
||||
|
||||
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
|
||||
|:-------------------------------------------------|:------------------------------------------------------|
|
||||
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. |
|
||||
| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
|
||||
|
||||
**Notes:**
|
||||
|
||||
1. The `MATCHER*` macros cannot be used inside a function or class.
|
||||
1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters).
|
||||
1. You can use `PrintToString(x)` to convert a value `x` of any type to a string.
|
||||
|
||||
## Matchers as Test Assertions ##
|
||||
|
||||
|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/primer.md#assertions) if the value of `expression` doesn't match matcher `m`.|
|
||||
|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. |
|
||||
|
||||
# Actions #
|
||||
|
||||
**Actions** specify what a mock function should do when invoked.
|
||||
|
||||
## Returning a Value ##
|
||||
|
||||
|`Return()`|Return from a `void` mock function.|
|
||||
|:---------|:----------------------------------|
|
||||
|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.|
|
||||
|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.|
|
||||
|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.|
|
||||
|`ReturnNull()`|Return a null pointer. |
|
||||
|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.|
|
||||
|`ReturnRef(variable)`|Return a reference to `variable`. |
|
||||
|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.|
|
||||
|
||||
## Side Effects ##
|
||||
|
||||
|`Assign(&variable, value)`|Assign `value` to variable.|
|
||||
|:-------------------------|:--------------------------|
|
||||
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
|
||||
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
|
||||
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
|
||||
| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. |
|
||||
|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.|
|
||||
|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.|
|
||||
|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.|
|
||||
|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.|
|
||||
|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.|
|
||||
|
||||
## Using a Function or a Functor as an Action ##
|
||||
|
||||
|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.|
|
||||
|:----------|:-----------------------------------------------------------------------------------------------------------------|
|
||||
|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. |
|
||||
|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |
|
||||
|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. |
|
||||
|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.|
|
||||
|
||||
The return value of the invoked function is used as the return value
|
||||
of the action.
|
||||
|
||||
When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`:
|
||||
```
|
||||
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
|
||||
...
|
||||
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
|
||||
```
|
||||
|
||||
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example,
|
||||
```
|
||||
InvokeArgument<2>(5, string("Hi"), ByRef(foo))
|
||||
```
|
||||
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference.
|
||||
|
||||
## Default Action ##
|
||||
|
||||
|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).|
|
||||
|:------------|:--------------------------------------------------------------------|
|
||||
|
||||
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error.
|
||||
|
||||
## Composite Actions ##
|
||||
|
||||
|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. |
|
||||
|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------|
|
||||
|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. |
|
||||
|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
|
||||
|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
|
||||
|`WithoutArgs(a)` |Perform action `a` without any arguments. |
|
||||
|
||||
## Defining Actions ##
|
||||
|
||||
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
|
||||
|:--------------------------------------|:---------------------------------------------------------------------------------------|
|
||||
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
|
||||
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |
|
||||
|
||||
The `ACTION*` macros cannot be used inside a function or class.
|
||||
|
||||
# Cardinalities #
|
||||
|
||||
These are used in `Times()` to specify how many times a mock function will be called:
|
||||
|
||||
|`AnyNumber()`|The function can be called any number of times.|
|
||||
|:------------|:----------------------------------------------|
|
||||
|`AtLeast(n)` |The call is expected at least `n` times. |
|
||||
|`AtMost(n)` |The call is expected at most `n` times. |
|
||||
|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.|
|
||||
|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.|
|
||||
|
||||
# Expectation Order #
|
||||
|
||||
By default, the expectations can be matched in _any_ order. If some
|
||||
or all expectations must be matched in a given order, there are two
|
||||
ways to specify it. They can be used either independently or
|
||||
together.
|
||||
|
||||
## The After Clause ##
|
||||
|
||||
```
|
||||
using ::testing::Expectation;
|
||||
...
|
||||
Expectation init_x = EXPECT_CALL(foo, InitX());
|
||||
Expectation init_y = EXPECT_CALL(foo, InitY());
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.After(init_x, init_y);
|
||||
```
|
||||
says that `Bar()` can be called only after both `InitX()` and
|
||||
`InitY()` have been called.
|
||||
|
||||
If you don't know how many pre-requisites an expectation has when you
|
||||
write it, you can use an `ExpectationSet` to collect them:
|
||||
|
||||
```
|
||||
using ::testing::ExpectationSet;
|
||||
...
|
||||
ExpectationSet all_inits;
|
||||
for (int i = 0; i < element_count; i++) {
|
||||
all_inits += EXPECT_CALL(foo, InitElement(i));
|
||||
}
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.After(all_inits);
|
||||
```
|
||||
says that `Bar()` can be called only after all elements have been
|
||||
initialized (but we don't care about which elements get initialized
|
||||
before the others).
|
||||
|
||||
Modifying an `ExpectationSet` after using it in an `.After()` doesn't
|
||||
affect the meaning of the `.After()`.
|
||||
|
||||
## Sequences ##
|
||||
|
||||
When you have a long chain of sequential expectations, it's easier to
|
||||
specify the order using **sequences**, which don't require you to given
|
||||
each expectation in the chain a different name. <i>All expected<br>
|
||||
calls</i> in the same sequence must occur in the order they are
|
||||
specified.
|
||||
|
||||
```
|
||||
using ::testing::Sequence;
|
||||
Sequence s1, s2;
|
||||
...
|
||||
EXPECT_CALL(foo, Reset())
|
||||
.InSequence(s1, s2)
|
||||
.WillOnce(Return(true));
|
||||
EXPECT_CALL(foo, GetSize())
|
||||
.InSequence(s1)
|
||||
.WillOnce(Return(1));
|
||||
EXPECT_CALL(foo, Describe(A<const char*>()))
|
||||
.InSequence(s2)
|
||||
.WillOnce(Return("dummy"));
|
||||
```
|
||||
says that `Reset()` must be called before _both_ `GetSize()` _and_
|
||||
`Describe()`, and the latter two can occur in any order.
|
||||
|
||||
To put many expectations in a sequence conveniently:
|
||||
```
|
||||
using ::testing::InSequence;
|
||||
{
|
||||
InSequence dummy;
|
||||
|
||||
EXPECT_CALL(...)...;
|
||||
EXPECT_CALL(...)...;
|
||||
...
|
||||
EXPECT_CALL(...)...;
|
||||
}
|
||||
```
|
||||
says that all expected calls in the scope of `dummy` must occur in
|
||||
strict order. The name `dummy` is irrelevant.)
|
||||
|
||||
# Verifying and Resetting a Mock #
|
||||
|
||||
Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier:
|
||||
```
|
||||
using ::testing::Mock;
|
||||
...
|
||||
// Verifies and removes the expectations on mock_obj;
|
||||
// returns true iff successful.
|
||||
Mock::VerifyAndClearExpectations(&mock_obj);
|
||||
...
|
||||
// Verifies and removes the expectations on mock_obj;
|
||||
// also removes the default actions set by ON_CALL();
|
||||
// returns true iff successful.
|
||||
Mock::VerifyAndClear(&mock_obj);
|
||||
```
|
||||
|
||||
You can also tell Google Mock that a mock object can be leaked and doesn't
|
||||
need to be verified:
|
||||
```
|
||||
Mock::AllowLeak(&mock_obj);
|
||||
```
|
||||
|
||||
# Mock Classes #
|
||||
|
||||
Google Mock defines a convenient mock class template
|
||||
```
|
||||
class MockFunction<R(A1, ..., An)> {
|
||||
public:
|
||||
MOCK_METHODn(Call, R(A1, ..., An));
|
||||
};
|
||||
```
|
||||
See this [recipe](CookBook.md#using-check-points) for one application of it.
|
||||
|
||||
# Flags #
|
||||
|
||||
| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
|
||||
|:-------------------------------|:----------------------------------------------|
|
||||
| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,280 @@
|
|||
This page discusses the design of new Google Mock features.
|
||||
|
||||
|
||||
|
||||
# Macros for Defining Actions #
|
||||
|
||||
## Problem ##
|
||||
|
||||
Due to the lack of closures in C++, it currently requires some
|
||||
non-trivial effort to define a custom action in Google Mock. For
|
||||
example, suppose you want to "increment the value pointed to by the
|
||||
second argument of the mock function and return it", you could write:
|
||||
|
||||
```
|
||||
int IncrementArg1(Unused, int* p, Unused) {
|
||||
return ++(*p);
|
||||
}
|
||||
|
||||
... WillOnce(Invoke(IncrementArg1));
|
||||
```
|
||||
|
||||
There are several things unsatisfactory about this approach:
|
||||
|
||||
* Even though the action only cares about the second argument of the mock function, its definition needs to list other arguments as dummies. This is tedious.
|
||||
* The defined action is usable only in mock functions that takes exactly 3 arguments - an unnecessary restriction.
|
||||
* To use the action, one has to say `Invoke(IncrementArg1)`, which isn't as nice as `IncrementArg1()`.
|
||||
|
||||
The latter two problems can be overcome using `MakePolymorphicAction()`,
|
||||
but it requires much more boilerplate code:
|
||||
|
||||
```
|
||||
class IncrementArg1Action {
|
||||
public:
|
||||
template <typename Result, typename ArgumentTuple>
|
||||
Result Perform(const ArgumentTuple& args) const {
|
||||
return ++(*tr1::get<1>(args));
|
||||
}
|
||||
};
|
||||
|
||||
PolymorphicAction<IncrementArg1Action> IncrementArg1() {
|
||||
return MakePolymorphicAction(IncrementArg1Action());
|
||||
}
|
||||
|
||||
... WillOnce(IncrementArg1());
|
||||
```
|
||||
|
||||
Our goal is to allow defining custom actions with the least amount of
|
||||
boiler-plate C++ requires.
|
||||
|
||||
## Solution ##
|
||||
|
||||
We propose to introduce a new macro:
|
||||
```
|
||||
ACTION(name) { statements; }
|
||||
```
|
||||
|
||||
Using this in a namespace scope will define an action with the given
|
||||
name that executes the statements. Inside the statements, you can
|
||||
refer to the K-th (0-based) argument of the mock function as `argK`.
|
||||
For example:
|
||||
```
|
||||
ACTION(IncrementArg1) { return ++(*arg1); }
|
||||
```
|
||||
allows you to write
|
||||
```
|
||||
... WillOnce(IncrementArg1());
|
||||
```
|
||||
|
||||
Note that you don't need to specify the types of the mock function
|
||||
arguments, as brevity is a top design goal here. Rest assured that
|
||||
your code is still type-safe though: you'll get a compiler error if
|
||||
`*arg1` doesn't support the `++` operator, or if the type of
|
||||
`++(*arg1)` isn't compatible with the mock function's return type.
|
||||
|
||||
Another example:
|
||||
```
|
||||
ACTION(Foo) {
|
||||
(*arg2)(5);
|
||||
Blah();
|
||||
*arg1 = 0;
|
||||
return arg0;
|
||||
}
|
||||
```
|
||||
defines an action `Foo()` that invokes argument #2 (a function pointer)
|
||||
with 5, calls function `Blah()`, sets the value pointed to by argument
|
||||
#1 to 0, and returns argument #0.
|
||||
|
||||
For more convenience and flexibility, you can also use the following
|
||||
pre-defined symbols in the body of `ACTION`:
|
||||
|
||||
| `argK_type` | The type of the K-th (0-based) argument of the mock function |
|
||||
|:------------|:-------------------------------------------------------------|
|
||||
| `args` | All arguments of the mock function as a tuple |
|
||||
| `args_type` | The type of all arguments of the mock function as a tuple |
|
||||
| `return_type` | The return type of the mock function |
|
||||
| `function_type` | The type of the mock function |
|
||||
|
||||
For example, when using an `ACTION` as a stub action for mock function:
|
||||
```
|
||||
int DoSomething(bool flag, int* ptr);
|
||||
```
|
||||
we have:
|
||||
| **Pre-defined Symbol** | **Is Bound To** |
|
||||
|:-----------------------|:----------------|
|
||||
| `arg0` | the value of `flag` |
|
||||
| `arg0_type` | the type `bool` |
|
||||
| `arg1` | the value of `ptr` |
|
||||
| `arg1_type` | the type `int*` |
|
||||
| `args` | the tuple `(flag, ptr)` |
|
||||
| `args_type` | the type `std::tr1::tuple<bool, int*>` |
|
||||
| `return_type` | the type `int` |
|
||||
| `function_type` | the type `int(bool, int*)` |
|
||||
|
||||
## Parameterized actions ##
|
||||
|
||||
Sometimes you'll want to parameterize the action. For that we propose
|
||||
another macro
|
||||
```
|
||||
ACTION_P(name, param) { statements; }
|
||||
```
|
||||
|
||||
For example,
|
||||
```
|
||||
ACTION_P(Add, n) { return arg0 + n; }
|
||||
```
|
||||
will allow you to write
|
||||
```
|
||||
// Returns argument #0 + 5.
|
||||
... WillOnce(Add(5));
|
||||
```
|
||||
|
||||
For convenience, we use the term _arguments_ for the values used to
|
||||
invoke the mock function, and the term _parameters_ for the values
|
||||
used to instantiate an action.
|
||||
|
||||
Note that you don't need to provide the type of the parameter either.
|
||||
Suppose the parameter is named `param`, you can also use the
|
||||
Google-Mock-defined symbol `param_type` to refer to the type of the
|
||||
parameter as inferred by the compiler.
|
||||
|
||||
We will also provide `ACTION_P2`, `ACTION_P3`, and etc to support
|
||||
multi-parameter actions. For example,
|
||||
```
|
||||
ACTION_P2(ReturnDistanceTo, x, y) {
|
||||
double dx = arg0 - x;
|
||||
double dy = arg1 - y;
|
||||
return sqrt(dx*dx + dy*dy);
|
||||
}
|
||||
```
|
||||
lets you write
|
||||
```
|
||||
... WillOnce(ReturnDistanceTo(5.0, 26.5));
|
||||
```
|
||||
|
||||
You can view `ACTION` as a degenerated parameterized action where the
|
||||
number of parameters is 0.
|
||||
|
||||
## Advanced Usages ##
|
||||
|
||||
### Overloading Actions ###
|
||||
|
||||
You can easily define actions overloaded on the number of parameters:
|
||||
```
|
||||
ACTION_P(Plus, a) { ... }
|
||||
ACTION_P2(Plus, a, b) { ... }
|
||||
```
|
||||
|
||||
### Restricting the Type of an Argument or Parameter ###
|
||||
|
||||
For maximum brevity and reusability, the `ACTION*` macros don't let
|
||||
you specify the types of the mock function arguments and the action
|
||||
parameters. Instead, we let the compiler infer the types for us.
|
||||
|
||||
Sometimes, however, we may want to be more explicit about the types.
|
||||
There are several tricks to do that. For example:
|
||||
```
|
||||
ACTION(Foo) {
|
||||
// Makes sure arg0 can be converted to int.
|
||||
int n = arg0;
|
||||
... use n instead of arg0 here ...
|
||||
}
|
||||
|
||||
ACTION_P(Bar, param) {
|
||||
// Makes sure the type of arg1 is const char*.
|
||||
::testing::StaticAssertTypeEq<const char*, arg1_type>();
|
||||
|
||||
// Makes sure param can be converted to bool.
|
||||
bool flag = param;
|
||||
}
|
||||
```
|
||||
where `StaticAssertTypeEq` is a compile-time assertion we plan to add to
|
||||
Google Test (the name is chosen to match `static_assert` in C++0x).
|
||||
|
||||
### Using the ACTION Object's Type ###
|
||||
|
||||
If you are writing a function that returns an `ACTION` object, you'll
|
||||
need to know its type. The type depends on the macro used to define
|
||||
the action and the parameter types. The rule is relatively simple:
|
||||
| **Given Definition** | **Expression** | **Has Type** |
|
||||
|:---------------------|:---------------|:-------------|
|
||||
| `ACTION(Foo)` | `Foo()` | `FooAction` |
|
||||
| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
|
||||
| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
|
||||
| ... | ... | ... |
|
||||
|
||||
Note that we have to pick different suffixes (`Action`, `ActionP`,
|
||||
`ActionP2`, and etc) for actions with different numbers of parameters,
|
||||
or the action definitions cannot be overloaded on the number of
|
||||
parameters.
|
||||
|
||||
## When to Use ##
|
||||
|
||||
While the new macros are very convenient, please also consider other
|
||||
means of implementing actions (e.g. via `ActionInterface` or
|
||||
`MakePolymorphicAction()`), especially if you need to use the defined
|
||||
action a lot. While the other approaches require more work, they give
|
||||
you more control on the types of the mock function arguments and the
|
||||
action parameters, which in general leads to better compiler error
|
||||
messages that pay off in the long run. They also allow overloading
|
||||
actions based on parameter types, as opposed to just the number of
|
||||
parameters.
|
||||
|
||||
## Related Work ##
|
||||
|
||||
As you may have realized, the `ACTION*` macros resemble closures (also
|
||||
known as lambda expressions or anonymous functions). Indeed, both of
|
||||
them seek to lower the syntactic overhead for defining a function.
|
||||
|
||||
C++0x will support lambdas, but they are not part of C++ right now.
|
||||
Some non-standard libraries (most notably BLL or Boost Lambda Library)
|
||||
try to alleviate this problem. However, they are not a good choice
|
||||
for defining actions as:
|
||||
|
||||
* They are non-standard and not widely installed. Google Mock only depends on standard libraries and `tr1::tuple`, which is part of the new C++ standard and comes with gcc 4+. We want to keep it that way.
|
||||
* They are not trivial to learn.
|
||||
* They will become obsolete when C++0x's lambda feature is widely supported. We don't want to make our users use a dying library.
|
||||
* Since they are based on operators, they are rather ad hoc: you cannot use statements, and you cannot pass the lambda arguments to a function, for example.
|
||||
* They have subtle semantics that easily confuses new users. For example, in expression `_1++ + foo++`, `foo` will be incremented only once where the expression is evaluated, while `_1` will be incremented every time the unnamed function is invoked. This is far from intuitive.
|
||||
|
||||
`ACTION*` avoid all these problems.
|
||||
|
||||
## Future Improvements ##
|
||||
|
||||
There may be a need for composing `ACTION*` definitions (i.e. invoking
|
||||
another `ACTION` inside the definition of one `ACTION*`). We are not
|
||||
sure we want it yet, as one can get a similar effect by putting
|
||||
`ACTION` definitions in function templates and composing the function
|
||||
templates. We'll revisit this based on user feedback.
|
||||
|
||||
The reason we don't allow `ACTION*()` inside a function body is that
|
||||
the current C++ standard doesn't allow function-local types to be used
|
||||
to instantiate templates. The upcoming C++0x standard will lift this
|
||||
restriction. Once this feature is widely supported by compilers, we
|
||||
can revisit the implementation and add support for using `ACTION*()`
|
||||
inside a function.
|
||||
|
||||
C++0x will also support lambda expressions. When they become
|
||||
available, we may want to support using lambdas as actions.
|
||||
|
||||
# Macros for Defining Matchers #
|
||||
|
||||
Once the macros for defining actions are implemented, we plan to do
|
||||
the same for matchers:
|
||||
|
||||
```
|
||||
MATCHER(name) { statements; }
|
||||
```
|
||||
|
||||
where you can refer to the value being matched as `arg`. For example,
|
||||
given:
|
||||
|
||||
```
|
||||
MATCHER(IsPositive) { return arg > 0; }
|
||||
```
|
||||
|
||||
you can use `IsPositive()` as a matcher that matches a value iff it is
|
||||
greater than 0.
|
||||
|
||||
We will also add `MATCHER_P`, `MATCHER_P2`, and etc for parameterized
|
||||
matchers.
|
|
@ -0,0 +1,15 @@
|
|||
This page lists all documentation markdown files for Google Mock **(the
|
||||
current git version)**
|
||||
-- **if you use a former version of Google Mock, please read the
|
||||
documentation for that specific version instead (e.g. by checking out
|
||||
the respective git branch/tag).**
|
||||
|
||||
* [ForDummies](ForDummies.md) -- start here if you are new to Google Mock.
|
||||
* [CheatSheet](CheatSheet.md) -- a quick reference.
|
||||
* [CookBook](CookBook.md) -- recipes for doing various tasks using Google Mock.
|
||||
* [FrequentlyAskedQuestions](FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list.
|
||||
|
||||
To contribute code to Google Mock, read:
|
||||
|
||||
* [CONTRIBUTING](../CONTRIBUTING.md) -- read this _before_ writing your first patch.
|
||||
* [Pump Manual](../../googletest/docs/PumpManual.md) -- how we generate some of Google Mock's source files.
|
|
@ -0,0 +1,447 @@
|
|||
|
||||
|
||||
(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](FrequentlyAskedQuestions.md#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors).)
|
||||
|
||||
# What Is Google C++ Mocking Framework? #
|
||||
When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc).
|
||||
|
||||
**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community:
|
||||
|
||||
* **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake.
|
||||
* **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive.
|
||||
|
||||
If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks.
|
||||
|
||||
**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java.
|
||||
|
||||
Using Google Mock involves three basic steps:
|
||||
|
||||
1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class;
|
||||
1. Create some mock objects and specify its expectations and behavior using an intuitive syntax;
|
||||
1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises.
|
||||
|
||||
# Why Google Mock? #
|
||||
While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_:
|
||||
|
||||
* Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distances to avoid it.
|
||||
* The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad-hoc restrictions.
|
||||
* The knowledge you gained from using one mock doesn't transfer to the next.
|
||||
|
||||
In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference.
|
||||
|
||||
Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you:
|
||||
|
||||
* You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid".
|
||||
* Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database).
|
||||
* Your tests are brittle as some resources they use are unreliable (e.g. the network).
|
||||
* You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one.
|
||||
* You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best.
|
||||
* You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks.
|
||||
|
||||
We encourage you to use Google Mock as:
|
||||
|
||||
* a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs!
|
||||
* a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators.
|
||||
|
||||
# Getting Started #
|
||||
Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go.
|
||||
|
||||
# A Case for Mock Turtles #
|
||||
Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface:
|
||||
|
||||
```
|
||||
class Turtle {
|
||||
...
|
||||
virtual ~Turtle() {}
|
||||
virtual void PenUp() = 0;
|
||||
virtual void PenDown() = 0;
|
||||
virtual void Forward(int distance) = 0;
|
||||
virtual void Turn(int degrees) = 0;
|
||||
virtual void GoTo(int x, int y) = 0;
|
||||
virtual int GetX() const = 0;
|
||||
virtual int GetY() const = 0;
|
||||
};
|
||||
```
|
||||
|
||||
(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.)
|
||||
|
||||
You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle.
|
||||
|
||||
Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_.
|
||||
|
||||
# Writing the Mock Class #
|
||||
If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.)
|
||||
|
||||
## How to Define It ##
|
||||
Using the `Turtle` interface as example, here are the simple steps you need to follow:
|
||||
|
||||
1. Derive a class `MockTurtle` from `Turtle`.
|
||||
1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](CookBook.md#mocking-nonvirtual-methods), it's much more involved). Count how many arguments it has.
|
||||
1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so.
|
||||
1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_).
|
||||
1. Repeat until all virtual functions you want to mock are done.
|
||||
|
||||
After the process, you should have something like:
|
||||
|
||||
```
|
||||
#include "gmock/gmock.h" // Brings in Google Mock.
|
||||
class MockTurtle : public Turtle {
|
||||
public:
|
||||
...
|
||||
MOCK_METHOD0(PenUp, void());
|
||||
MOCK_METHOD0(PenDown, void());
|
||||
MOCK_METHOD1(Forward, void(int distance));
|
||||
MOCK_METHOD1(Turn, void(int degrees));
|
||||
MOCK_METHOD2(GoTo, void(int x, int y));
|
||||
MOCK_CONST_METHOD0(GetX, int());
|
||||
MOCK_CONST_METHOD0(GetY, int());
|
||||
};
|
||||
```
|
||||
|
||||
You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins.
|
||||
|
||||
**Tip:** If even this is too much work for you, you'll find the
|
||||
`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line
|
||||
tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it,
|
||||
and it will print the definition of the mock class for you. Due to the
|
||||
complexity of the C++ language, this script may not always work, but
|
||||
it can be quite handy when it does. For more details, read the [user documentation](../scripts/generator/README).
|
||||
|
||||
## Where to Put It ##
|
||||
When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?)
|
||||
|
||||
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed.
|
||||
|
||||
Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does.
|
||||
|
||||
# Using Mocks in Tests #
|
||||
Once you have a mock class, using it is easy. The typical work flow is:
|
||||
|
||||
1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.).
|
||||
1. Create some mock objects.
|
||||
1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.).
|
||||
1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately.
|
||||
1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```
|
||||
#include "path/to/mock-turtle.h"
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest/gtest.h"
|
||||
using ::testing::AtLeast; // #1
|
||||
|
||||
TEST(PainterTest, CanDrawSomething) {
|
||||
MockTurtle turtle; // #2
|
||||
EXPECT_CALL(turtle, PenDown()) // #3
|
||||
.Times(AtLeast(1));
|
||||
|
||||
Painter painter(&turtle); // #4
|
||||
|
||||
EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
|
||||
} // #5
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
// The following line must be executed to initialize Google Mock
|
||||
// (and Google Test) before running the tests.
|
||||
::testing::InitGoogleMock(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
```
|
||||
|
||||
As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this:
|
||||
|
||||
```
|
||||
path/to/my_test.cc:119: Failure
|
||||
Actual function call count doesn't match this expectation:
|
||||
Actually: never called;
|
||||
Expected: called at least once.
|
||||
```
|
||||
|
||||
**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation.
|
||||
|
||||
**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap.
|
||||
|
||||
**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions.
|
||||
|
||||
This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier.
|
||||
|
||||
Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks.
|
||||
|
||||
## Using Google Mock with Any Testing Framework ##
|
||||
If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or
|
||||
[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to:
|
||||
```
|
||||
int main(int argc, char** argv) {
|
||||
// The following line causes Google Mock to throw an exception on failure,
|
||||
// which will be interpreted by your testing framework as a test failure.
|
||||
::testing::GTEST_FLAG(throw_on_failure) = true;
|
||||
::testing::InitGoogleMock(&argc, argv);
|
||||
... whatever your testing framework requires ...
|
||||
}
|
||||
```
|
||||
|
||||
This approach has a catch: it makes Google Mock throw an exception
|
||||
from a mock object's destructor sometimes. With some compilers, this
|
||||
sometimes causes the test program to crash. You'll still be able to
|
||||
notice that the test has failed, but it's not a graceful failure.
|
||||
|
||||
A better solution is to use Google Test's
|
||||
[event listener API](../../googletest/docs/advanced.md#extending-google-test-by-handling-test-events)
|
||||
to report a test failure to your testing framework properly. You'll need to
|
||||
implement the `OnTestPartResult()` method of the event listener interface, but it
|
||||
should be straightforward.
|
||||
|
||||
If this turns out to be too much work, we suggest that you stick with
|
||||
Google Test, which works with Google Mock seamlessly (in fact, it is
|
||||
technically part of Google Mock.). If there is a reason that you
|
||||
cannot use Google Test, please let us know.
|
||||
|
||||
# Setting Expectations #
|
||||
The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right."
|
||||
|
||||
## General Syntax ##
|
||||
In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is:
|
||||
|
||||
```
|
||||
EXPECT_CALL(mock_object, method(matchers))
|
||||
.Times(cardinality)
|
||||
.WillOnce(action)
|
||||
.WillRepeatedly(action);
|
||||
```
|
||||
|
||||
The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.)
|
||||
|
||||
The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections.
|
||||
|
||||
This syntax is designed to make an expectation read like English. For example, you can probably guess that
|
||||
|
||||
```
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.Times(5)
|
||||
.WillOnce(Return(100))
|
||||
.WillOnce(Return(150))
|
||||
.WillRepeatedly(Return(200));
|
||||
```
|
||||
|
||||
says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL).
|
||||
|
||||
**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier.
|
||||
|
||||
## Matchers: What Arguments Do We Expect? ##
|
||||
When a mock function takes arguments, we must specify what arguments we are expecting; for example:
|
||||
|
||||
```
|
||||
// Expects the turtle to move forward by 100 units.
|
||||
EXPECT_CALL(turtle, Forward(100));
|
||||
```
|
||||
|
||||
Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes":
|
||||
|
||||
```
|
||||
using ::testing::_;
|
||||
...
|
||||
// Expects the turtle to move forward.
|
||||
EXPECT_CALL(turtle, Forward(_));
|
||||
```
|
||||
|
||||
`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected.
|
||||
|
||||
A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher:
|
||||
|
||||
```
|
||||
using ::testing::Ge;
|
||||
...
|
||||
EXPECT_CALL(turtle, Forward(Ge(100)));
|
||||
```
|
||||
|
||||
This checks that the turtle will be told to go forward by at least 100 units.
|
||||
|
||||
## Cardinalities: How Many Times Will It Be Called? ##
|
||||
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly.
|
||||
|
||||
An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called.
|
||||
|
||||
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](CheatSheet.md).
|
||||
|
||||
The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember:
|
||||
|
||||
* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
|
||||
* If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`.
|
||||
* If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`.
|
||||
|
||||
**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times?
|
||||
|
||||
## Actions: What Should It Do? ##
|
||||
Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock.
|
||||
|
||||
First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). In addition, in C++ 11 and above, a mock function whose return type is default-constructible (i.e. has a default constructor) has a default action of returning a default-constructed value. If you don't say anything, this behavior will be used.
|
||||
|
||||
Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example,
|
||||
|
||||
```
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(100))
|
||||
.WillOnce(Return(200))
|
||||
.WillOnce(Return(300));
|
||||
```
|
||||
|
||||
This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively.
|
||||
|
||||
```
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetY())
|
||||
.WillOnce(Return(100))
|
||||
.WillOnce(Return(200))
|
||||
.WillRepeatedly(Return(300));
|
||||
```
|
||||
|
||||
says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on.
|
||||
|
||||
Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.).
|
||||
|
||||
What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](CheatSheet.md#actions).
|
||||
|
||||
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want:
|
||||
|
||||
```
|
||||
int n = 100;
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.Times(4)
|
||||
.WillRepeatedly(Return(n++));
|
||||
```
|
||||
|
||||
Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](CookBook.md).
|
||||
|
||||
Time for another quiz! What do you think the following means?
|
||||
|
||||
```
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetY())
|
||||
.Times(4)
|
||||
.WillOnce(Return(100));
|
||||
```
|
||||
|
||||
Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions.
|
||||
|
||||
## Using Multiple Expectations ##
|
||||
So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects.
|
||||
|
||||
By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example:
|
||||
|
||||
```
|
||||
using ::testing::_;
|
||||
...
|
||||
EXPECT_CALL(turtle, Forward(_)); // #1
|
||||
EXPECT_CALL(turtle, Forward(10)) // #2
|
||||
.Times(2);
|
||||
```
|
||||
|
||||
If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation.
|
||||
|
||||
**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it.
|
||||
|
||||
## Ordered vs Unordered Calls ##
|
||||
By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified.
|
||||
|
||||
Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy:
|
||||
|
||||
```
|
||||
using ::testing::InSequence;
|
||||
...
|
||||
TEST(FooTest, DrawsLineSegment) {
|
||||
...
|
||||
{
|
||||
InSequence dummy;
|
||||
|
||||
EXPECT_CALL(turtle, PenDown());
|
||||
EXPECT_CALL(turtle, Forward(100));
|
||||
EXPECT_CALL(turtle, PenUp());
|
||||
}
|
||||
Foo();
|
||||
}
|
||||
```
|
||||
|
||||
By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant.
|
||||
|
||||
In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error.
|
||||
|
||||
(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook.md#expecting-partially-ordered-calls).)
|
||||
|
||||
## All Expectations Are Sticky (Unless Said Otherwise) ##
|
||||
Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)?
|
||||
|
||||
After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!):
|
||||
|
||||
```
|
||||
using ::testing::_;
|
||||
...
|
||||
EXPECT_CALL(turtle, GoTo(_, _)) // #1
|
||||
.Times(AnyNumber());
|
||||
EXPECT_CALL(turtle, GoTo(0, 0)) // #2
|
||||
.Times(2);
|
||||
```
|
||||
|
||||
Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above.
|
||||
|
||||
This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.).
|
||||
|
||||
Simple? Let's see if you've really understood it: what does the following code say?
|
||||
|
||||
```
|
||||
using ::testing::Return;
|
||||
...
|
||||
for (int i = n; i > 0; i--) {
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(10*i));
|
||||
}
|
||||
```
|
||||
|
||||
If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful!
|
||||
|
||||
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated:
|
||||
|
||||
```
|
||||
using ::testing::Return;
|
||||
...
|
||||
for (int i = n; i > 0; i--) {
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(10*i))
|
||||
.RetiresOnSaturation();
|
||||
}
|
||||
```
|
||||
|
||||
And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence:
|
||||
|
||||
```
|
||||
using ::testing::InSequence;
|
||||
using ::testing::Return;
|
||||
...
|
||||
{
|
||||
InSequence s;
|
||||
|
||||
for (int i = 1; i <= n; i++) {
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(10*i))
|
||||
.RetiresOnSaturation();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call).
|
||||
|
||||
## Uninteresting Calls ##
|
||||
A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called.
|
||||
|
||||
In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure.
|
||||
|
||||
# What Now? #
|
||||
Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned.
|
||||
|
||||
Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss.
|
|
@ -0,0 +1,627 @@
|
|||
|
||||
|
||||
Please send your questions to the
|
||||
[googlemock](http://groups.google.com/group/googlemock) discussion
|
||||
group. If you need help with compiler errors, make sure you have
|
||||
tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.
|
||||
|
||||
## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ##
|
||||
|
||||
In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](CookBook.md#mocking-nonvirtual-methods).
|
||||
|
||||
## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ##
|
||||
|
||||
After version 1.4.0 of Google Mock was released, we had an idea on how
|
||||
to make it easier to write matchers that can generate informative
|
||||
messages efficiently. We experimented with this idea and liked what
|
||||
we saw. Therefore we decided to implement it.
|
||||
|
||||
Unfortunately, this means that if you have defined your own matchers
|
||||
by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
|
||||
your definitions will no longer compile. Matchers defined using the
|
||||
`MATCHER*` family of macros are not affected.
|
||||
|
||||
Sorry for the hassle if your matchers are affected. We believe it's
|
||||
in everyone's long-term interest to make this change sooner than
|
||||
later. Fortunately, it's usually not hard to migrate an existing
|
||||
matcher to the new API. Here's what you need to do:
|
||||
|
||||
If you wrote your matcher like this:
|
||||
```
|
||||
// Old matcher definition that doesn't work with the latest
|
||||
// Google Mock.
|
||||
using ::testing::MatcherInterface;
|
||||
...
|
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> {
|
||||
public:
|
||||
...
|
||||
virtual bool Matches(MyType value) const {
|
||||
// Returns true if value matches.
|
||||
return value.GetFoo() > 5;
|
||||
}
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
you'll need to change it to:
|
||||
```
|
||||
// New matcher definition that works with the latest Google Mock.
|
||||
using ::testing::MatcherInterface;
|
||||
using ::testing::MatchResultListener;
|
||||
...
|
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> {
|
||||
public:
|
||||
...
|
||||
virtual bool MatchAndExplain(MyType value,
|
||||
MatchResultListener* listener) const {
|
||||
// Returns true if value matches.
|
||||
return value.GetFoo() > 5;
|
||||
}
|
||||
...
|
||||
};
|
||||
```
|
||||
(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
|
||||
argument of type `MatchResultListener*`.)
|
||||
|
||||
If you were also using `ExplainMatchResultTo()` to improve the matcher
|
||||
message:
|
||||
```
|
||||
// Old matcher definition that doesn't work with the lastest
|
||||
// Google Mock.
|
||||
using ::testing::MatcherInterface;
|
||||
...
|
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> {
|
||||
public:
|
||||
...
|
||||
virtual bool Matches(MyType value) const {
|
||||
// Returns true if value matches.
|
||||
return value.GetFoo() > 5;
|
||||
}
|
||||
|
||||
virtual void ExplainMatchResultTo(MyType value,
|
||||
::std::ostream* os) const {
|
||||
// Prints some helpful information to os to help
|
||||
// a user understand why value matches (or doesn't match).
|
||||
*os << "the Foo property is " << value.GetFoo();
|
||||
}
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
you should move the logic of `ExplainMatchResultTo()` into
|
||||
`MatchAndExplain()`, using the `MatchResultListener` argument where
|
||||
the `::std::ostream` was used:
|
||||
```
|
||||
// New matcher definition that works with the latest Google Mock.
|
||||
using ::testing::MatcherInterface;
|
||||
using ::testing::MatchResultListener;
|
||||
...
|
||||
class MyWonderfulMatcher : public MatcherInterface<MyType> {
|
||||
public:
|
||||
...
|
||||
virtual bool MatchAndExplain(MyType value,
|
||||
MatchResultListener* listener) const {
|
||||
// Returns true if value matches.
|
||||
*listener << "the Foo property is " << value.GetFoo();
|
||||
return value.GetFoo() > 5;
|
||||
}
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
If your matcher is defined using `MakePolymorphicMatcher()`:
|
||||
```
|
||||
// Old matcher definition that doesn't work with the latest
|
||||
// Google Mock.
|
||||
using ::testing::MakePolymorphicMatcher;
|
||||
...
|
||||
class MyGreatMatcher {
|
||||
public:
|
||||
...
|
||||
bool Matches(MyType value) const {
|
||||
// Returns true if value matches.
|
||||
return value.GetBar() < 42;
|
||||
}
|
||||
...
|
||||
};
|
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ...
|
||||
```
|
||||
|
||||
you should rename the `Matches()` method to `MatchAndExplain()` and
|
||||
add a `MatchResultListener*` argument (the same as what you need to do
|
||||
for matchers defined by implementing `MatcherInterface`):
|
||||
```
|
||||
// New matcher definition that works with the latest Google Mock.
|
||||
using ::testing::MakePolymorphicMatcher;
|
||||
using ::testing::MatchResultListener;
|
||||
...
|
||||
class MyGreatMatcher {
|
||||
public:
|
||||
...
|
||||
bool MatchAndExplain(MyType value,
|
||||
MatchResultListener* listener) const {
|
||||
// Returns true if value matches.
|
||||
return value.GetBar() < 42;
|
||||
}
|
||||
...
|
||||
};
|
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ...
|
||||
```
|
||||
|
||||
If your polymorphic matcher uses `ExplainMatchResultTo()` for better
|
||||
failure messages:
|
||||
```
|
||||
// Old matcher definition that doesn't work with the latest
|
||||
// Google Mock.
|
||||
using ::testing::MakePolymorphicMatcher;
|
||||
...
|
||||
class MyGreatMatcher {
|
||||
public:
|
||||
...
|
||||
bool Matches(MyType value) const {
|
||||
// Returns true if value matches.
|
||||
return value.GetBar() < 42;
|
||||
}
|
||||
...
|
||||
};
|
||||
void ExplainMatchResultTo(const MyGreatMatcher& matcher,
|
||||
MyType value,
|
||||
::std::ostream* os) {
|
||||
// Prints some helpful information to os to help
|
||||
// a user understand why value matches (or doesn't match).
|
||||
*os << "the Bar property is " << value.GetBar();
|
||||
}
|
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ...
|
||||
```
|
||||
|
||||
you'll need to move the logic inside `ExplainMatchResultTo()` to
|
||||
`MatchAndExplain()`:
|
||||
```
|
||||
// New matcher definition that works with the latest Google Mock.
|
||||
using ::testing::MakePolymorphicMatcher;
|
||||
using ::testing::MatchResultListener;
|
||||
...
|
||||
class MyGreatMatcher {
|
||||
public:
|
||||
...
|
||||
bool MatchAndExplain(MyType value,
|
||||
MatchResultListener* listener) const {
|
||||
// Returns true if value matches.
|
||||
*listener << "the Bar property is " << value.GetBar();
|
||||
return value.GetBar() < 42;
|
||||
}
|
||||
...
|
||||
};
|
||||
... MakePolymorphicMatcher(MyGreatMatcher()) ...
|
||||
```
|
||||
|
||||
For more information, you can read these
|
||||
[two](CookBook.md#writing-new-monomorphic-matchers)
|
||||
[recipes](CookBook.md#writing-new-polymorphic-matchers)
|
||||
from the cookbook. As always, you
|
||||
are welcome to post questions on `googlemock@googlegroups.com` if you
|
||||
need any help.
|
||||
|
||||
## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ##
|
||||
|
||||
Google Mock works out of the box with Google Test. However, it's easy
|
||||
to configure it to work with any testing framework of your choice.
|
||||
[Here](ForDummies.md#using-google-mock-with-any-testing-framework) is how.
|
||||
|
||||
## How am I supposed to make sense of these horrible template errors? ##
|
||||
|
||||
If you are confused by the compiler errors gcc threw at you,
|
||||
try consulting the _Google Mock Doctor_ tool first. What it does is to
|
||||
scan stdin for gcc error messages, and spit out diagnoses on the
|
||||
problems (we call them diseases) your code has.
|
||||
|
||||
To "install", run command:
|
||||
```
|
||||
alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
|
||||
```
|
||||
|
||||
To use it, do:
|
||||
```
|
||||
<your-favorite-build-command> <your-test> 2>&1 | gmd
|
||||
```
|
||||
|
||||
For example:
|
||||
```
|
||||
make my_test 2>&1 | gmd
|
||||
```
|
||||
|
||||
Or you can run `gmd` and copy-n-paste gcc's error messages to it.
|
||||
|
||||
## Can I mock a variadic function? ##
|
||||
|
||||
You cannot mock a variadic function (i.e. a function taking ellipsis
|
||||
(`...`) arguments) directly in Google Mock.
|
||||
|
||||
The problem is that in general, there is _no way_ for a mock object to
|
||||
know how many arguments are passed to the variadic method, and what
|
||||
the arguments' types are. Only the _author of the base class_ knows
|
||||
the protocol, and we cannot look into their head.
|
||||
|
||||
Therefore, to mock such a function, the _user_ must teach the mock
|
||||
object how to figure out the number of arguments and their types. One
|
||||
way to do it is to provide overloaded versions of the function.
|
||||
|
||||
Ellipsis arguments are inherited from C and not really a C++ feature.
|
||||
They are unsafe to use and don't work with arguments that have
|
||||
constructors or destructors. Therefore we recommend to avoid them in
|
||||
C++ as much as possible.
|
||||
|
||||
## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ##
|
||||
|
||||
If you compile this using Microsoft Visual C++ 2005 SP1:
|
||||
```
|
||||
class Foo {
|
||||
...
|
||||
virtual void Bar(const int i) = 0;
|
||||
};
|
||||
|
||||
class MockFoo : public Foo {
|
||||
...
|
||||
MOCK_METHOD1(Bar, void(const int i));
|
||||
};
|
||||
```
|
||||
You may get the following warning:
|
||||
```
|
||||
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
|
||||
```
|
||||
|
||||
This is a MSVC bug. The same code compiles fine with gcc ,for
|
||||
example. If you use Visual C++ 2008 SP1, you would get the warning:
|
||||
```
|
||||
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
|
||||
```
|
||||
|
||||
In C++, if you _declare_ a function with a `const` parameter, the
|
||||
`const` modifier is _ignored_. Therefore, the `Foo` base class above
|
||||
is equivalent to:
|
||||
```
|
||||
class Foo {
|
||||
...
|
||||
virtual void Bar(int i) = 0; // int or const int? Makes no difference.
|
||||
};
|
||||
```
|
||||
|
||||
In fact, you can _declare_ Bar() with an `int` parameter, and _define_
|
||||
it with a `const int` parameter. The compiler will still match them
|
||||
up.
|
||||
|
||||
Since making a parameter `const` is meaningless in the method
|
||||
_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
|
||||
That should workaround the VC bug.
|
||||
|
||||
Note that we are talking about the _top-level_ `const` modifier here.
|
||||
If the function parameter is passed by pointer or reference, declaring
|
||||
the _pointee_ or _referee_ as `const` is still meaningful. For
|
||||
example, the following two declarations are _not_ equivalent:
|
||||
```
|
||||
void Bar(int* p); // Neither p nor *p is const.
|
||||
void Bar(const int* p); // p is not const, but *p is.
|
||||
```
|
||||
|
||||
## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ##
|
||||
|
||||
We've noticed that when the `/clr` compiler flag is used, Visual C++
|
||||
uses 5~6 times as much memory when compiling a mock class. We suggest
|
||||
to avoid `/clr` when compiling native C++ mocks.
|
||||
|
||||
## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ##
|
||||
|
||||
You might want to run your test with
|
||||
`--gmock_verbose=info`. This flag lets Google Mock print a trace
|
||||
of every mock function call it receives. By studying the trace,
|
||||
you'll gain insights on why the expectations you set are not met.
|
||||
|
||||
## How can I assert that a function is NEVER called? ##
|
||||
|
||||
```
|
||||
EXPECT_CALL(foo, Bar(_))
|
||||
.Times(0);
|
||||
```
|
||||
|
||||
## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ##
|
||||
|
||||
When Google Mock detects a failure, it prints relevant information
|
||||
(the mock function arguments, the state of relevant expectations, and
|
||||
etc) to help the user debug. If another failure is detected, Google
|
||||
Mock will do the same, including printing the state of relevant
|
||||
expectations.
|
||||
|
||||
Sometimes an expectation's state didn't change between two failures,
|
||||
and you'll see the same description of the state twice. They are
|
||||
however _not_ redundant, as they refer to _different points in time_.
|
||||
The fact they are the same _is_ interesting information.
|
||||
|
||||
## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ##
|
||||
|
||||
Does the class (hopefully a pure interface) you are mocking have a
|
||||
virtual destructor?
|
||||
|
||||
Whenever you derive from a base class, make sure its destructor is
|
||||
virtual. Otherwise Bad Things will happen. Consider the following
|
||||
code:
|
||||
|
||||
```
|
||||
class Base {
|
||||
public:
|
||||
// Not virtual, but should be.
|
||||
~Base() { ... }
|
||||
...
|
||||
};
|
||||
|
||||
class Derived : public Base {
|
||||
public:
|
||||
...
|
||||
private:
|
||||
std::string value_;
|
||||
};
|
||||
|
||||
...
|
||||
Base* p = new Derived;
|
||||
...
|
||||
delete p; // Surprise! ~Base() will be called, but ~Derived() will not
|
||||
// - value_ is leaked.
|
||||
```
|
||||
|
||||
By changing `~Base()` to virtual, `~Derived()` will be correctly
|
||||
called when `delete p` is executed, and the heap checker
|
||||
will be happy.
|
||||
|
||||
## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ##
|
||||
|
||||
When people complain about this, often they are referring to code like:
|
||||
|
||||
```
|
||||
// foo.Bar() should be called twice, return 1 the first time, and return
|
||||
// 2 the second time. However, I have to write the expectations in the
|
||||
// reverse order. This sucks big time!!!
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(2))
|
||||
.RetiresOnSaturation();
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(1))
|
||||
.RetiresOnSaturation();
|
||||
```
|
||||
|
||||
The problem is that they didn't pick the **best** way to express the test's
|
||||
intent.
|
||||
|
||||
By default, expectations don't have to be matched in _any_ particular
|
||||
order. If you want them to match in a certain order, you need to be
|
||||
explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's
|
||||
easy to accidentally over-specify your tests, and we want to make it
|
||||
harder to do so.
|
||||
|
||||
There are two better ways to write the test spec. You could either
|
||||
put the expectations in sequence:
|
||||
|
||||
```
|
||||
// foo.Bar() should be called twice, return 1 the first time, and return
|
||||
// 2 the second time. Using a sequence, we can write the expectations
|
||||
// in their natural order.
|
||||
{
|
||||
InSequence s;
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(1))
|
||||
.RetiresOnSaturation();
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(2))
|
||||
.RetiresOnSaturation();
|
||||
}
|
||||
```
|
||||
|
||||
or you can put the sequence of actions in the same expectation:
|
||||
|
||||
```
|
||||
// foo.Bar() should be called twice, return 1 the first time, and return
|
||||
// 2 the second time.
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(1))
|
||||
.WillOnce(Return(2))
|
||||
.RetiresOnSaturation();
|
||||
```
|
||||
|
||||
Back to the original questions: why does Google Mock search the
|
||||
expectations (and `ON_CALL`s) from back to front? Because this
|
||||
allows a user to set up a mock's behavior for the common case early
|
||||
(e.g. in the mock's constructor or the test fixture's set-up phase)
|
||||
and customize it with more specific rules later. If Google Mock
|
||||
searches from front to back, this very useful pattern won't be
|
||||
possible.
|
||||
|
||||
## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ##
|
||||
|
||||
When choosing between being neat and being safe, we lean toward the
|
||||
latter. So the answer is that we think it's better to show the
|
||||
warning.
|
||||
|
||||
Often people write `ON_CALL`s in the mock object's
|
||||
constructor or `SetUp()`, as the default behavior rarely changes from
|
||||
test to test. Then in the test body they set the expectations, which
|
||||
are often different for each test. Having an `ON_CALL` in the set-up
|
||||
part of a test doesn't mean that the calls are expected. If there's
|
||||
no `EXPECT_CALL` and the method is called, it's possibly an error. If
|
||||
we quietly let the call go through without notifying the user, bugs
|
||||
may creep in unnoticed.
|
||||
|
||||
If, however, you are sure that the calls are OK, you can write
|
||||
|
||||
```
|
||||
EXPECT_CALL(foo, Bar(_))
|
||||
.WillRepeatedly(...);
|
||||
```
|
||||
|
||||
instead of
|
||||
|
||||
```
|
||||
ON_CALL(foo, Bar(_))
|
||||
.WillByDefault(...);
|
||||
```
|
||||
|
||||
This tells Google Mock that you do expect the calls and no warning should be
|
||||
printed.
|
||||
|
||||
Also, you can control the verbosity using the `--gmock_verbose` flag.
|
||||
If you find the output too noisy when debugging, just choose a less
|
||||
verbose level.
|
||||
|
||||
## How can I delete the mock function's argument in an action? ##
|
||||
|
||||
If you find yourself needing to perform some action that's not
|
||||
supported by Google Mock directly, remember that you can define your own
|
||||
actions using
|
||||
[MakeAction()](CookBook.md#writing-new-actions) or
|
||||
[MakePolymorphicAction()](CookBook.md#writing_new_polymorphic_actions),
|
||||
or you can write a stub function and invoke it using
|
||||
[Invoke()](CookBook.md#using-functions_methods_functors).
|
||||
|
||||
## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##
|
||||
|
||||
What?! I think it's beautiful. :-)
|
||||
|
||||
While which syntax looks more natural is a subjective matter to some
|
||||
extent, Google Mock's syntax was chosen for several practical advantages it
|
||||
has.
|
||||
|
||||
Try to mock a function that takes a map as an argument:
|
||||
```
|
||||
virtual int GetSize(const map<int, std::string>& m);
|
||||
```
|
||||
|
||||
Using the proposed syntax, it would be:
|
||||
```
|
||||
MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
|
||||
```
|
||||
|
||||
Guess what? You'll get a compiler error as the compiler thinks that
|
||||
`const map<int, std::string>& m` are **two**, not one, arguments. To work
|
||||
around this you can use `typedef` to give the map type a name, but
|
||||
that gets in the way of your work. Google Mock's syntax avoids this
|
||||
problem as the function's argument types are protected inside a pair
|
||||
of parentheses:
|
||||
```
|
||||
// This compiles fine.
|
||||
MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
|
||||
```
|
||||
|
||||
You still need a `typedef` if the return type contains an unprotected
|
||||
comma, but that's much rarer.
|
||||
|
||||
Other advantages include:
|
||||
1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
|
||||
1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
|
||||
1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`!
|
||||
|
||||
## My code calls a static/global function. Can I mock it? ##
|
||||
|
||||
You can, but you need to make some changes.
|
||||
|
||||
In general, if you find yourself needing to mock a static function,
|
||||
it's a sign that your modules are too tightly coupled (and less
|
||||
flexible, less reusable, less testable, etc). You are probably better
|
||||
off defining a small interface and call the function through that
|
||||
interface, which then can be easily mocked. It's a bit of work
|
||||
initially, but usually pays for itself quickly.
|
||||
|
||||
This Google Testing Blog
|
||||
[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html)
|
||||
says it excellently. Check it out.
|
||||
|
||||
## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ##
|
||||
|
||||
I know it's not a question, but you get an answer for free any way. :-)
|
||||
|
||||
With Google Mock, you can create mocks in C++ easily. And people might be
|
||||
tempted to use them everywhere. Sometimes they work great, and
|
||||
sometimes you may find them, well, a pain to use. So, what's wrong in
|
||||
the latter case?
|
||||
|
||||
When you write a test without using mocks, you exercise the code and
|
||||
assert that it returns the correct value or that the system is in an
|
||||
expected state. This is sometimes called "state-based testing".
|
||||
|
||||
Mocks are great for what some call "interaction-based" testing:
|
||||
instead of checking the system state at the very end, mock objects
|
||||
verify that they are invoked the right way and report an error as soon
|
||||
as it arises, giving you a handle on the precise context in which the
|
||||
error was triggered. This is often more effective and economical to
|
||||
do than state-based testing.
|
||||
|
||||
If you are doing state-based testing and using a test double just to
|
||||
simulate the real object, you are probably better off using a fake.
|
||||
Using a mock in this case causes pain, as it's not a strong point for
|
||||
mocks to perform complex actions. If you experience this and think
|
||||
that mocks suck, you are just not using the right tool for your
|
||||
problem. Or, you might be trying to solve the wrong problem. :-)
|
||||
|
||||
## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ##
|
||||
|
||||
By all means, NO! It's just an FYI.
|
||||
|
||||
What it means is that you have a mock function, you haven't set any
|
||||
expectations on it (by Google Mock's rule this means that you are not
|
||||
interested in calls to this function and therefore it can be called
|
||||
any number of times), and it is called. That's OK - you didn't say
|
||||
it's not OK to call the function!
|
||||
|
||||
What if you actually meant to disallow this function to be called, but
|
||||
forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While
|
||||
one can argue that it's the user's fault, Google Mock tries to be nice and
|
||||
prints you a note.
|
||||
|
||||
So, when you see the message and believe that there shouldn't be any
|
||||
uninteresting calls, you should investigate what's going on. To make
|
||||
your life easier, Google Mock prints the function name and arguments
|
||||
when an uninteresting call is encountered.
|
||||
|
||||
## I want to define a custom action. Should I use Invoke() or implement the action interface? ##
|
||||
|
||||
Either way is fine - you want to choose the one that's more convenient
|
||||
for your circumstance.
|
||||
|
||||
Usually, if your action is for a particular function type, defining it
|
||||
using `Invoke()` should be easier; if your action can be used in
|
||||
functions of different types (e.g. if you are defining
|
||||
`Return(value)`), `MakePolymorphicAction()` is
|
||||
easiest. Sometimes you want precise control on what types of
|
||||
functions the action can be used in, and implementing
|
||||
`ActionInterface` is the way to go here. See the implementation of
|
||||
`Return()` in `include/gmock/gmock-actions.h` for an example.
|
||||
|
||||
## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ##
|
||||
|
||||
You got this error as Google Mock has no idea what value it should return
|
||||
when the mock method is called. `SetArgPointee()` says what the
|
||||
side effect is, but doesn't say what the return value should be. You
|
||||
need `DoAll()` to chain a `SetArgPointee()` with a `Return()`.
|
||||
|
||||
See this [recipe](CookBook.md#mocking_side_effects) for more details and an example.
|
||||
|
||||
|
||||
## My question is not in your FAQ! ##
|
||||
|
||||
If you cannot find the answer to your question in this FAQ, there are
|
||||
some other resources you can use:
|
||||
|
||||
1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
|
||||
1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).
|
||||
|
||||
Please note that creating an issue in the
|
||||
[issue tracker](https://github.com/google/googletest/issues) is _not_
|
||||
a good way to get your answer, as it is monitored infrequently by a
|
||||
very small number of people.
|
||||
|
||||
When asking a question, it's helpful to provide as much of the
|
||||
following information as possible (people cannot help you if there's
|
||||
not enough information in your question):
|
||||
|
||||
* the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
|
||||
* your operating system,
|
||||
* the name and version of your compiler,
|
||||
* the complete command line flags you give to your compiler,
|
||||
* the complete compiler error messages (if the question is about compilation),
|
||||
* the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.
|
|
@ -0,0 +1,19 @@
|
|||
As any non-trivial software system, Google Mock has some known limitations and problems. We are working on improving it, and welcome your help! The follow is a list of issues we know about.
|
||||
|
||||
|
||||
|
||||
## README contains outdated information on Google Mock's compatibility with other testing frameworks ##
|
||||
|
||||
The `README` file in release 1.1.0 still says that Google Mock only works with Google Test. Actually, you can configure Google Mock to work with any testing framework you choose.
|
||||
|
||||
## Tests failing on machines using Power PC CPUs (e.g. some Macs) ##
|
||||
|
||||
`gmock_output_test` and `gmock-printers_test` are known to fail with Power PC CPUs. This is due to portability issues with these tests, and is not an indication of problems in Google Mock itself. You can safely ignore them.
|
||||
|
||||
## Failed to resolve libgtest.so.0 in tests when built against installed Google Test ##
|
||||
|
||||
This only applies if you manually built and installed Google Test, and then built a Google Mock against it (either explicitly, or because gtest-config was in your path post-install). In this situation, Libtool has a known issue with certain systems' ldconfig setup:
|
||||
|
||||
http://article.gmane.org/gmane.comp.sysutils.automake.general/9025
|
||||
|
||||
This requires a manual run of "sudo ldconfig" after the "sudo make install" for Google Test before any binaries which link against it can be executed. This isn't a bug in our install, but we should at least have documented it or hacked a work-around into our install. We should have one of these solutions in our next release.
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -26,26 +26,32 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file implements some commonly used actions.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
#ifndef _WIN32_WCE
|
||||
# include <errno.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
#include "gmock/internal/gmock-internal-utils.h"
|
||||
#include "gmock/internal/gmock-port.h"
|
||||
|
||||
#if GTEST_LANG_CXX11 // Defined by gtest-port.h via gmock-port.h.
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
#endif // GTEST_LANG_CXX11
|
||||
|
||||
namespace testing {
|
||||
|
||||
// To implement an action Foo, define:
|
||||
|
@ -62,16 +68,17 @@ namespace internal {
|
|||
template <typename F1, typename F2>
|
||||
class ActionAdaptor;
|
||||
|
||||
// BuiltInDefaultValue<T>::Get() returns the "built-in" default
|
||||
// value for type T, which is NULL when T is a pointer type, 0 when T
|
||||
// is a numeric type, false when T is bool, or "" when T is string or
|
||||
// std::string. For any other type T, this value is undefined and the
|
||||
// function will abort the process.
|
||||
// BuiltInDefaultValueGetter<T, true>::Get() returns a
|
||||
// default-constructed T value. BuiltInDefaultValueGetter<T,
|
||||
// false>::Get() crashes with an error.
|
||||
//
|
||||
// This primary template is used when kDefaultConstructible is true.
|
||||
template <typename T, bool kDefaultConstructible>
|
||||
struct BuiltInDefaultValueGetter {
|
||||
static T Get() { return T(); }
|
||||
};
|
||||
template <typename T>
|
||||
class BuiltInDefaultValue {
|
||||
public:
|
||||
// This function returns true iff type T has a built-in default value.
|
||||
static bool Exists() { return false; }
|
||||
struct BuiltInDefaultValueGetter<T, false> {
|
||||
static T Get() {
|
||||
Assert(false, __FILE__, __LINE__,
|
||||
"Default action undefined for the function return type.");
|
||||
|
@ -81,6 +88,40 @@ class BuiltInDefaultValue {
|
|||
}
|
||||
};
|
||||
|
||||
// BuiltInDefaultValue<T>::Get() returns the "built-in" default value
|
||||
// for type T, which is NULL when T is a raw pointer type, 0 when T is
|
||||
// a numeric type, false when T is bool, or "" when T is string or
|
||||
// std::string. In addition, in C++11 and above, it turns a
|
||||
// default-constructed T value if T is default constructible. For any
|
||||
// other type T, the built-in default T value is undefined, and the
|
||||
// function will abort the process.
|
||||
template <typename T>
|
||||
class BuiltInDefaultValue {
|
||||
public:
|
||||
#if GTEST_LANG_CXX11
|
||||
// This function returns true iff type T has a built-in default value.
|
||||
static bool Exists() {
|
||||
return ::std::is_default_constructible<T>::value;
|
||||
}
|
||||
|
||||
static T Get() {
|
||||
return BuiltInDefaultValueGetter<
|
||||
T, ::std::is_default_constructible<T>::value>::Get();
|
||||
}
|
||||
|
||||
#else // GTEST_LANG_CXX11
|
||||
// This function returns true iff type T has a built-in default value.
|
||||
static bool Exists() {
|
||||
return false;
|
||||
}
|
||||
|
||||
static T Get() {
|
||||
return BuiltInDefaultValueGetter<T, false>::Get();
|
||||
}
|
||||
|
||||
#endif // GTEST_LANG_CXX11
|
||||
};
|
||||
|
||||
// This partial specialization says that we use the same built-in
|
||||
// default value for T and const T.
|
||||
template <typename T>
|
||||
|
@ -163,18 +204,27 @@ class DefaultValue {
|
|||
// Sets the default value for type T; requires T to be
|
||||
// copy-constructable and have a public destructor.
|
||||
static void Set(T x) {
|
||||
delete value_;
|
||||
value_ = new T(x);
|
||||
delete producer_;
|
||||
producer_ = new FixedValueProducer(x);
|
||||
}
|
||||
|
||||
// Provides a factory function to be called to generate the default value.
|
||||
// This method can be used even if T is only move-constructible, but it is not
|
||||
// limited to that case.
|
||||
typedef T (*FactoryFunction)();
|
||||
static void SetFactory(FactoryFunction factory) {
|
||||
delete producer_;
|
||||
producer_ = new FactoryValueProducer(factory);
|
||||
}
|
||||
|
||||
// Unsets the default value for type T.
|
||||
static void Clear() {
|
||||
delete value_;
|
||||
value_ = NULL;
|
||||
delete producer_;
|
||||
producer_ = NULL;
|
||||
}
|
||||
|
||||
// Returns true iff the user has set the default value for type T.
|
||||
static bool IsSet() { return value_ != NULL; }
|
||||
static bool IsSet() { return producer_ != NULL; }
|
||||
|
||||
// Returns true if T has a default return value set by the user or there
|
||||
// exists a built-in default value.
|
||||
|
@ -183,14 +233,42 @@ class DefaultValue {
|
|||
}
|
||||
|
||||
// Returns the default value for type T if the user has set one;
|
||||
// otherwise returns the built-in default value if there is one;
|
||||
// otherwise aborts the process.
|
||||
// otherwise returns the built-in default value. Requires that Exists()
|
||||
// is true, which ensures that the return value is well-defined.
|
||||
static T Get() {
|
||||
return value_ == NULL ?
|
||||
internal::BuiltInDefaultValue<T>::Get() : *value_;
|
||||
return producer_ == NULL ?
|
||||
internal::BuiltInDefaultValue<T>::Get() : producer_->Produce();
|
||||
}
|
||||
|
||||
private:
|
||||
static const T* value_;
|
||||
class ValueProducer {
|
||||
public:
|
||||
virtual ~ValueProducer() {}
|
||||
virtual T Produce() = 0;
|
||||
};
|
||||
|
||||
class FixedValueProducer : public ValueProducer {
|
||||
public:
|
||||
explicit FixedValueProducer(T value) : value_(value) {}
|
||||
virtual T Produce() { return value_; }
|
||||
|
||||
private:
|
||||
const T value_;
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
|
||||
};
|
||||
|
||||
class FactoryValueProducer : public ValueProducer {
|
||||
public:
|
||||
explicit FactoryValueProducer(FactoryFunction factory)
|
||||
: factory_(factory) {}
|
||||
virtual T Produce() { return factory_(); }
|
||||
|
||||
private:
|
||||
const FactoryFunction factory_;
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
|
||||
};
|
||||
|
||||
static ValueProducer* producer_;
|
||||
};
|
||||
|
||||
// This partial specialization allows a user to set default values for
|
||||
|
@ -224,6 +302,7 @@ class DefaultValue<T&> {
|
|||
return address_ == NULL ?
|
||||
internal::BuiltInDefaultValue<T&>::Get() : *address_;
|
||||
}
|
||||
|
||||
private:
|
||||
static T* address_;
|
||||
};
|
||||
|
@ -239,7 +318,7 @@ class DefaultValue<void> {
|
|||
|
||||
// Points to the user-set default value for type T.
|
||||
template <typename T>
|
||||
const T* DefaultValue<T>::value_ = NULL;
|
||||
typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL;
|
||||
|
||||
// Points to the user-set default value for type T&.
|
||||
template <typename T>
|
||||
|
@ -282,15 +361,21 @@ class Action {
|
|||
|
||||
// Constructs a null Action. Needed for storing Action objects in
|
||||
// STL containers.
|
||||
Action() : impl_(NULL) {}
|
||||
Action() {}
|
||||
|
||||
// Constructs an Action from its implementation. A NULL impl is
|
||||
// used to represent the "do-default" action.
|
||||
#if GTEST_LANG_CXX11
|
||||
// Construct an Action from a specified callable.
|
||||
// This cannot take std::function directly, because then Action would not be
|
||||
// directly constructible from lambda (it would require two conversions).
|
||||
template <typename G,
|
||||
typename = typename ::std::enable_if<
|
||||
::std::is_constructible<::std::function<F>, G>::value>::type>
|
||||
Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
|
||||
#endif
|
||||
|
||||
// Constructs an Action from its implementation.
|
||||
explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
|
||||
|
||||
// Copy constructor.
|
||||
Action(const Action& action) : impl_(action.impl_) {}
|
||||
|
||||
// This constructor allows us to turn an Action<Func> object into an
|
||||
// Action<F>, as long as F's arguments can be implicitly converted
|
||||
// to Func's and Func's return type can be implicitly converted to
|
||||
|
@ -299,7 +384,13 @@ class Action {
|
|||
explicit Action(const Action<Func>& action);
|
||||
|
||||
// Returns true iff this is the DoDefault() action.
|
||||
bool IsDoDefault() const { return impl_.get() == NULL; }
|
||||
bool IsDoDefault() const {
|
||||
#if GTEST_LANG_CXX11
|
||||
return impl_ == nullptr && fun_ == nullptr;
|
||||
#else
|
||||
return impl_ == NULL;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Performs the action. Note that this method is const even though
|
||||
// the corresponding method in ActionInterface is not. The reason
|
||||
|
@ -307,14 +398,15 @@ class Action {
|
|||
// another concrete action, not that the concrete action it binds to
|
||||
// cannot change state. (Think of the difference between a const
|
||||
// pointer and a pointer to const.)
|
||||
Result Perform(const ArgumentTuple& args) const {
|
||||
internal::Assert(
|
||||
!IsDoDefault(), __FILE__, __LINE__,
|
||||
"You are using DoDefault() inside a composite action like "
|
||||
"DoAll() or WithArgs(). This is not supported for technical "
|
||||
"reasons. Please instead spell out the default action, or "
|
||||
"assign the default action to an Action variable and use "
|
||||
"the variable in various places.");
|
||||
Result Perform(ArgumentTuple args) const {
|
||||
if (IsDoDefault()) {
|
||||
internal::IllegalDoDefault(__FILE__, __LINE__);
|
||||
}
|
||||
#if GTEST_LANG_CXX11
|
||||
if (fun_ != nullptr) {
|
||||
return internal::Apply(fun_, ::std::move(args));
|
||||
}
|
||||
#endif
|
||||
return impl_->Perform(args);
|
||||
}
|
||||
|
||||
|
@ -322,6 +414,18 @@ class Action {
|
|||
template <typename F1, typename F2>
|
||||
friend class internal::ActionAdaptor;
|
||||
|
||||
template <typename G>
|
||||
friend class Action;
|
||||
|
||||
// In C++11, Action can be implemented either as a generic functor (through
|
||||
// std::function), or legacy ActionInterface. In C++98, only ActionInterface
|
||||
// is available. The invariants are as follows:
|
||||
// * in C++98, impl_ is null iff this is the default action
|
||||
// * in C++11, at most one of fun_ & impl_ may be nonnull; both are null iff
|
||||
// this is the default action
|
||||
#if GTEST_LANG_CXX11
|
||||
::std::function<F> fun_;
|
||||
#endif
|
||||
internal::linked_ptr<ActionInterface<F> > impl_;
|
||||
};
|
||||
|
||||
|
@ -421,6 +525,14 @@ class ActionAdaptor : public ActionInterface<F1> {
|
|||
GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
|
||||
};
|
||||
|
||||
// Helper struct to specialize ReturnAction to execute a move instead of a copy
|
||||
// on return. Useful for move-only types, but could be used on any type.
|
||||
template <typename T>
|
||||
struct ByMoveWrapper {
|
||||
explicit ByMoveWrapper(T value) : payload(internal::move(value)) {}
|
||||
T payload;
|
||||
};
|
||||
|
||||
// Implements the polymorphic Return(x) action, which can be used in
|
||||
// any function that returns the type of x, regardless of the argument
|
||||
// types.
|
||||
|
@ -445,13 +557,16 @@ class ActionAdaptor : public ActionInterface<F1> {
|
|||
// statement, and conversion of the result of Return to Action<T(U)> is a
|
||||
// good place for that.
|
||||
//
|
||||
// The real life example of the above scenario happens when an invocation
|
||||
// of gtl::Container() is passed into Return.
|
||||
//
|
||||
template <typename R>
|
||||
class ReturnAction {
|
||||
public:
|
||||
// Constructs a ReturnAction object from the value to be returned.
|
||||
// 'value' is passed by value instead of by const reference in order
|
||||
// to allow Return("string literal") to compile.
|
||||
explicit ReturnAction(R value) : value_(value) {}
|
||||
explicit ReturnAction(R value) : value_(new R(internal::move(value))) {}
|
||||
|
||||
// This template type conversion operator allows Return(x) to be
|
||||
// used in ANY function that returns x's type.
|
||||
|
@ -467,14 +582,14 @@ class ReturnAction {
|
|||
// in the Impl class. But both definitions must be the same.
|
||||
typedef typename Function<F>::Result Result;
|
||||
GTEST_COMPILE_ASSERT_(
|
||||
!internal::is_reference<Result>::value,
|
||||
!is_reference<Result>::value,
|
||||
use_ReturnRef_instead_of_Return_to_return_a_reference);
|
||||
return Action<F>(new Impl<F>(value_));
|
||||
return Action<F>(new Impl<R, F>(value_));
|
||||
}
|
||||
|
||||
private:
|
||||
// Implements the Return(x) action for a particular function type F.
|
||||
template <typename F>
|
||||
template <typename R_, typename F>
|
||||
class Impl : public ActionInterface<F> {
|
||||
public:
|
||||
typedef typename Function<F>::Result Result;
|
||||
|
@ -487,20 +602,49 @@ class ReturnAction {
|
|||
// Result to call. ImplicitCast_ forces the compiler to convert R to
|
||||
// Result without considering explicit constructors, thus resolving the
|
||||
// ambiguity. value_ is then initialized using its copy constructor.
|
||||
explicit Impl(R value)
|
||||
: value_(::testing::internal::ImplicitCast_<Result>(value)) {}
|
||||
explicit Impl(const linked_ptr<R>& value)
|
||||
: value_before_cast_(*value),
|
||||
value_(ImplicitCast_<Result>(value_before_cast_)) {}
|
||||
|
||||
virtual Result Perform(const ArgumentTuple&) { return value_; }
|
||||
|
||||
private:
|
||||
GTEST_COMPILE_ASSERT_(!internal::is_reference<Result>::value,
|
||||
GTEST_COMPILE_ASSERT_(!is_reference<Result>::value,
|
||||
Result_cannot_be_a_reference_type);
|
||||
// We save the value before casting just in case it is being cast to a
|
||||
// wrapper type.
|
||||
R value_before_cast_;
|
||||
Result value_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
|
||||
};
|
||||
|
||||
// Partially specialize for ByMoveWrapper. This version of ReturnAction will
|
||||
// move its contents instead.
|
||||
template <typename R_, typename F>
|
||||
class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
|
||||
public:
|
||||
typedef typename Function<F>::Result Result;
|
||||
typedef typename Function<F>::ArgumentTuple ArgumentTuple;
|
||||
|
||||
explicit Impl(const linked_ptr<R>& wrapper)
|
||||
: performed_(false), wrapper_(wrapper) {}
|
||||
|
||||
virtual Result Perform(const ArgumentTuple&) {
|
||||
GTEST_CHECK_(!performed_)
|
||||
<< "A ByMove() action should only be performed once.";
|
||||
performed_ = true;
|
||||
return internal::move(wrapper_->payload);
|
||||
}
|
||||
|
||||
private:
|
||||
bool performed_;
|
||||
const linked_ptr<R> wrapper_;
|
||||
|
||||
GTEST_DISALLOW_ASSIGN_(Impl);
|
||||
};
|
||||
|
||||
R value_;
|
||||
const linked_ptr<R> value_;
|
||||
|
||||
GTEST_DISALLOW_ASSIGN_(ReturnAction);
|
||||
};
|
||||
|
@ -508,12 +652,18 @@ class ReturnAction {
|
|||
// Implements the ReturnNull() action.
|
||||
class ReturnNullAction {
|
||||
public:
|
||||
// Allows ReturnNull() to be used in any pointer-returning function.
|
||||
// Allows ReturnNull() to be used in any pointer-returning function. In C++11
|
||||
// this is enforced by returning nullptr, and in non-C++11 by asserting a
|
||||
// pointer type on compile time.
|
||||
template <typename Result, typename ArgumentTuple>
|
||||
static Result Perform(const ArgumentTuple&) {
|
||||
#if GTEST_LANG_CXX11
|
||||
return nullptr;
|
||||
#else
|
||||
GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
|
||||
ReturnNull_can_be_used_to_return_a_pointer_only);
|
||||
return NULL;
|
||||
#endif // GTEST_LANG_CXX11
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -629,7 +779,7 @@ class DoDefaultAction {
|
|||
// This template type conversion operator allows DoDefault() to be
|
||||
// used in any function.
|
||||
template <typename F>
|
||||
operator Action<F>() const { return Action<F>(NULL); }
|
||||
operator Action<F>() const { return Action<F>(); } // NOLINT
|
||||
};
|
||||
|
||||
// Implements the Assign action to set a given pointer referent to a
|
||||
|
@ -690,7 +840,7 @@ class SetArgumentPointeeAction {
|
|||
template <typename Result, typename ArgumentTuple>
|
||||
void Perform(const ArgumentTuple& args) const {
|
||||
CompileAssertTypesEqual<void, Result>();
|
||||
*::std::tr1::get<N>(args) = value_;
|
||||
*::testing::get<N>(args) = value_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
@ -713,7 +863,7 @@ class SetArgumentPointeeAction<N, Proto, true> {
|
|||
template <typename Result, typename ArgumentTuple>
|
||||
void Perform(const ArgumentTuple& args) const {
|
||||
CompileAssertTypesEqual<void, Result>();
|
||||
::std::tr1::get<N>(args)->CopyFrom(*proto_);
|
||||
::testing::get<N>(args)->CopyFrom(*proto_);
|
||||
}
|
||||
|
||||
private:
|
||||
|
@ -765,6 +915,28 @@ class InvokeMethodWithoutArgsAction {
|
|||
GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction);
|
||||
};
|
||||
|
||||
// Implements the InvokeWithoutArgs(callback) action.
|
||||
template <typename CallbackType>
|
||||
class InvokeCallbackWithoutArgsAction {
|
||||
public:
|
||||
// The c'tor takes ownership of the callback.
|
||||
explicit InvokeCallbackWithoutArgsAction(CallbackType* callback)
|
||||
: callback_(callback) {
|
||||
callback->CheckIsRepeatable(); // Makes sure the callback is permanent.
|
||||
}
|
||||
|
||||
// This type conversion operator template allows Invoke(callback) to
|
||||
// be used wherever the callback's return type can be implicitly
|
||||
// converted to that of the mock function.
|
||||
template <typename Result, typename ArgumentTuple>
|
||||
Result Perform(const ArgumentTuple&) const { return callback_->Run(); }
|
||||
|
||||
private:
|
||||
const internal::linked_ptr<CallbackType> callback_;
|
||||
|
||||
GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction);
|
||||
};
|
||||
|
||||
// Implements the IgnoreResult(action) action.
|
||||
template <typename A>
|
||||
class IgnoreResultAction {
|
||||
|
@ -909,9 +1081,9 @@ class DoBothAction {
|
|||
// return sqrt(x*x + y*y);
|
||||
// }
|
||||
// ...
|
||||
// EXEPCT_CALL(mock, Foo("abc", _, _))
|
||||
// EXPECT_CALL(mock, Foo("abc", _, _))
|
||||
// .WillOnce(Invoke(DistanceToOriginWithLabel));
|
||||
// EXEPCT_CALL(mock, Bar(5, _, _))
|
||||
// EXPECT_CALL(mock, Bar(5, _, _))
|
||||
// .WillOnce(Invoke(DistanceToOriginWithIndex));
|
||||
//
|
||||
// you could write
|
||||
|
@ -921,8 +1093,8 @@ class DoBothAction {
|
|||
// return sqrt(x*x + y*y);
|
||||
// }
|
||||
// ...
|
||||
// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
|
||||
// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
|
||||
// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
|
||||
// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
|
||||
typedef internal::IgnoredValue Unused;
|
||||
|
||||
// This constructor allows us to turn an Action<From> object into an
|
||||
|
@ -932,14 +1104,20 @@ typedef internal::IgnoredValue Unused;
|
|||
template <typename To>
|
||||
template <typename From>
|
||||
Action<To>::Action(const Action<From>& from)
|
||||
: impl_(new internal::ActionAdaptor<To, From>(from)) {}
|
||||
:
|
||||
#if GTEST_LANG_CXX11
|
||||
fun_(from.fun_),
|
||||
#endif
|
||||
impl_(from.impl_ == NULL ? NULL
|
||||
: new internal::ActionAdaptor<To, From>(from)) {
|
||||
}
|
||||
|
||||
// Creates an action that returns 'value'. 'value' is passed by value
|
||||
// instead of const reference - otherwise Return("string literal")
|
||||
// will trigger a compiler error about using array as initializer.
|
||||
template <typename R>
|
||||
internal::ReturnAction<R> Return(R value) {
|
||||
return internal::ReturnAction<R>(value);
|
||||
return internal::ReturnAction<R>(internal::move(value));
|
||||
}
|
||||
|
||||
// Creates an action that returns NULL.
|
||||
|
@ -966,6 +1144,15 @@ inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
|
|||
return internal::ReturnRefOfCopyAction<R>(x);
|
||||
}
|
||||
|
||||
// Modifies the parent action (a Return() action) to perform a move of the
|
||||
// argument instead of a copy.
|
||||
// Return(ByMove()) actions can only be executed once and will assert this
|
||||
// invariant.
|
||||
template <typename R>
|
||||
internal::ByMoveWrapper<R> ByMove(R x) {
|
||||
return internal::ByMoveWrapper<R>(internal::move(x));
|
||||
}
|
||||
|
||||
// Creates an action that does the default action for the give mock function.
|
||||
inline internal::DoDefaultAction DoDefault() {
|
||||
return internal::DoDefaultAction();
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -35,6 +34,8 @@
|
|||
// cardinalities can be defined by the user implementing the
|
||||
// CardinalityInterface interface if necessary.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
|
||||
|
||||
|
@ -43,6 +44,9 @@
|
|||
#include "gmock/internal/gmock-port.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 {
|
||||
|
||||
// To implement a cardinality Foo, define:
|
||||
|
@ -80,7 +84,7 @@ class CardinalityInterface {
|
|||
// be called. The implementation of Cardinality is just a linked_ptr
|
||||
// to const CardinalityInterface, so copying is fairly cheap.
|
||||
// Don't inherit from Cardinality!
|
||||
class Cardinality {
|
||||
class GTEST_API_ Cardinality {
|
||||
public:
|
||||
// Constructs a null cardinality. Needed for storing Cardinality
|
||||
// objects in STL containers.
|
||||
|
@ -117,24 +121,25 @@ class Cardinality {
|
|||
// Describes the given actual call count to an ostream.
|
||||
static void DescribeActualCallCountTo(int actual_call_count,
|
||||
::std::ostream* os);
|
||||
|
||||
private:
|
||||
internal::linked_ptr<const CardinalityInterface> impl_;
|
||||
};
|
||||
|
||||
// Creates a cardinality that allows at least n calls.
|
||||
Cardinality AtLeast(int n);
|
||||
GTEST_API_ Cardinality AtLeast(int n);
|
||||
|
||||
// Creates a cardinality that allows at most n calls.
|
||||
Cardinality AtMost(int n);
|
||||
GTEST_API_ Cardinality AtMost(int n);
|
||||
|
||||
// Creates a cardinality that allows any number of calls.
|
||||
Cardinality AnyNumber();
|
||||
GTEST_API_ Cardinality AnyNumber();
|
||||
|
||||
// Creates a cardinality that allows between min and max calls.
|
||||
Cardinality Between(int min, int max);
|
||||
GTEST_API_ Cardinality Between(int min, int max);
|
||||
|
||||
// Creates a cardinality that allows exactly n calls.
|
||||
Cardinality Exactly(int n);
|
||||
GTEST_API_ Cardinality Exactly(int n);
|
||||
|
||||
// Creates a cardinality from its implementation.
|
||||
inline Cardinality MakeCardinality(const CardinalityInterface* c) {
|
||||
|
@ -143,4 +148,6 @@ inline Cardinality MakeCardinality(const CardinalityInterface* c) {
|
|||
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,5 +1,5 @@
|
|||
$$ -*- mode: c++; -*-
|
||||
$$ This is a Pump source file. Please use Pump to convert it to
|
||||
$$ This is a Pump source file. Please use Pump to convert it to
|
||||
$$ gmock-generated-actions.h.
|
||||
$$
|
||||
$var n = 10 $$ The maximum arity we support.
|
||||
|
@ -32,13 +32,14 @@ $$}} This meta comment fixes auto-indentation in editors.
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file implements some commonly used variadic actions.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
|
||||
|
||||
|
@ -49,100 +50,79 @@ namespace testing {
|
|||
namespace internal {
|
||||
|
||||
// InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary
|
||||
// function or method with the unpacked values, where F is a function
|
||||
// type that takes N arguments.
|
||||
// function, method, or callback with the unpacked values, where F is
|
||||
// a function type that takes N arguments.
|
||||
template <typename Result, typename ArgumentTuple>
|
||||
class InvokeHelper;
|
||||
|
||||
|
||||
$var max_callback_arity = 5
|
||||
$range i 0..n
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$var types = [[$for j [[, typename A$j]]]]
|
||||
$var as = [[$for j, [[A$j]]]]
|
||||
$var args = [[$if i==0 [[]] $else [[ args]]]]
|
||||
$var import = [[$if i==0 [[]] $else [[
|
||||
using ::std::tr1::get;
|
||||
|
||||
]]]]
|
||||
$var gets = [[$for j, [[get<$(j - 1)>(args)]]]]
|
||||
template <typename R$types>
|
||||
class InvokeHelper<R, ::std::tr1::tuple<$as> > {
|
||||
class InvokeHelper<R, ::testing::tuple<$as> > {
|
||||
public:
|
||||
template <typename Function>
|
||||
static R Invoke(Function function, const ::std::tr1::tuple<$as>&$args) {
|
||||
$import return function($gets);
|
||||
static R Invoke(Function function, const ::testing::tuple<$as>&$args) {
|
||||
return function($gets);
|
||||
}
|
||||
|
||||
template <class Class, typename MethodPtr>
|
||||
static R InvokeMethod(Class* obj_ptr,
|
||||
MethodPtr method_ptr,
|
||||
const ::std::tr1::tuple<$as>&$args) {
|
||||
$import return (obj_ptr->*method_ptr)($gets);
|
||||
const ::testing::tuple<$as>&$args) {
|
||||
return (obj_ptr->*method_ptr)($gets);
|
||||
}
|
||||
|
||||
|
||||
$if i <= max_callback_arity [[
|
||||
template <typename CallbackType>
|
||||
static R InvokeCallback(CallbackType* callback,
|
||||
const ::testing::tuple<$as>&$args) {
|
||||
return callback->Run($gets);
|
||||
}
|
||||
]] $else [[
|
||||
// There is no InvokeCallback() for $i-tuples
|
||||
]]
|
||||
|
||||
};
|
||||
|
||||
|
||||
]]
|
||||
// CallableHelper has static methods for invoking "callables",
|
||||
// i.e. function pointers and functors. It uses overloading to
|
||||
// provide a uniform interface for invoking different kinds of
|
||||
// callables. In particular, you can use:
|
||||
//
|
||||
// CallableHelper<R>::Call(callable, a1, a2, ..., an)
|
||||
//
|
||||
// to invoke an n-ary callable, where R is its return type. If an
|
||||
// argument, say a2, needs to be passed by reference, you should write
|
||||
// ByRef(a2) instead of a2 in the above expression.
|
||||
template <typename R>
|
||||
class CallableHelper {
|
||||
// Implements the Invoke(callback) action.
|
||||
template <typename CallbackType>
|
||||
class InvokeCallbackAction {
|
||||
public:
|
||||
// Calls a nullary callable.
|
||||
template <typename Function>
|
||||
static R Call(Function function) { return function(); }
|
||||
|
||||
// Calls a unary callable.
|
||||
|
||||
// We deliberately pass a1 by value instead of const reference here
|
||||
// in case it is a C-string literal. If we had declared the
|
||||
// parameter as 'const A1& a1' and write Call(function, "Hi"), the
|
||||
// compiler would've thought A1 is 'char[3]', which causes trouble
|
||||
// when you need to copy a value of type A1. By declaring the
|
||||
// parameter as 'A1 a1', the compiler will correctly infer that A1
|
||||
// is 'const char*' when it sees Call(function, "Hi").
|
||||
//
|
||||
// Since this function is defined inline, the compiler can get rid
|
||||
// of the copying of the arguments. Therefore the performance won't
|
||||
// be hurt.
|
||||
template <typename Function, typename A1>
|
||||
static R Call(Function function, A1 a1) { return function(a1); }
|
||||
|
||||
$range i 2..n
|
||||
$for i
|
||||
[[
|
||||
$var arity = [[$if i==2 [[binary]] $elif i==3 [[ternary]] $else [[$i-ary]]]]
|
||||
|
||||
// Calls a $arity callable.
|
||||
|
||||
$range j 1..i
|
||||
$var typename_As = [[$for j, [[typename A$j]]]]
|
||||
$var Aas = [[$for j, [[A$j a$j]]]]
|
||||
$var as = [[$for j, [[a$j]]]]
|
||||
$var typename_Ts = [[$for j, [[typename T$j]]]]
|
||||
$var Ts = [[$for j, [[T$j]]]]
|
||||
template <typename Function, $typename_As>
|
||||
static R Call(Function function, $Aas) {
|
||||
return function($as);
|
||||
// The c'tor takes ownership of the callback.
|
||||
explicit InvokeCallbackAction(CallbackType* callback)
|
||||
: callback_(callback) {
|
||||
callback->CheckIsRepeatable(); // Makes sure the callback is permanent.
|
||||
}
|
||||
|
||||
]]
|
||||
|
||||
}; // class CallableHelper
|
||||
// This type conversion operator template allows Invoke(callback) to
|
||||
// be used wherever the callback's type is compatible with that of
|
||||
// the mock function, i.e. if the mock function's arguments can be
|
||||
// implicitly converted to the callback's arguments and the
|
||||
// callback's result can be implicitly converted to the mock
|
||||
// function's result.
|
||||
template <typename Result, typename ArgumentTuple>
|
||||
Result Perform(const ArgumentTuple& args) const {
|
||||
return InvokeHelper<Result, ArgumentTuple>::InvokeCallback(
|
||||
callback_.get(), args);
|
||||
}
|
||||
private:
|
||||
const linked_ptr<CallbackType> callback_;
|
||||
};
|
||||
|
||||
// An INTERNAL macro for extracting the type of a tuple field. It's
|
||||
// subject to change without notice - DO NOT USE IN USER CODE!
|
||||
#define GMOCK_FIELD_(Tuple, N) \
|
||||
typename ::std::tr1::tuple_element<N, Tuple>::type
|
||||
typename ::testing::tuple_element<N, Tuple>::type
|
||||
|
||||
$range i 1..n
|
||||
|
||||
|
@ -150,15 +130,15 @@ $range i 1..n
|
|||
// type of an n-ary function whose i-th (1-based) argument type is the
|
||||
// k{i}-th (0-based) field of ArgumentTuple, which must be a tuple
|
||||
// type, and whose return type is Result. For example,
|
||||
// SelectArgs<int, ::std::tr1::tuple<bool, char, double, long>, 0, 3>::type
|
||||
// SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type
|
||||
// is int(bool, long).
|
||||
//
|
||||
// SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args)
|
||||
// returns the selected fields (k1, k2, ..., k_n) of args as a tuple.
|
||||
// For example,
|
||||
// SelectArgs<int, ::std::tr1::tuple<bool, char, double>, 2, 0>::Select(
|
||||
// ::std::tr1::make_tuple(true, 'a', 2.5))
|
||||
// returns ::std::tr1::tuple (2.5, true).
|
||||
// SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select(
|
||||
// ::testing::make_tuple(true, 'a', 2.5))
|
||||
// returns tuple (2.5, true).
|
||||
//
|
||||
// The numbers in list k1, k2, ..., k_n must be >= 0, where n can be
|
||||
// in the range [0, $n]. Duplicates are allowed and they don't have
|
||||
|
@ -170,7 +150,6 @@ class SelectArgs {
|
|||
typedef Result type($for i, [[GMOCK_FIELD_(ArgumentTuple, k$i)]]);
|
||||
typedef typename Function<type>::ArgumentTuple SelectedArgs;
|
||||
static SelectedArgs Select(const ArgumentTuple& args) {
|
||||
using ::std::tr1::get;
|
||||
return SelectedArgs($for i, [[get<k$i>(args)]]);
|
||||
}
|
||||
};
|
||||
|
@ -187,7 +166,6 @@ class SelectArgs<Result, ArgumentTuple,
|
|||
typedef typename Function<type>::ArgumentTuple SelectedArgs;
|
||||
static SelectedArgs Select(const ArgumentTuple& [[]]
|
||||
$if i == 1 [[/* args */]] $else [[args]]) {
|
||||
using ::std::tr1::get;
|
||||
return SelectedArgs($for j1, [[get<k$j1>(args)]]);
|
||||
}
|
||||
};
|
||||
|
@ -267,8 +245,7 @@ $range k 1..n-i
|
|||
$var eas = [[$for k, [[ExcessiveArg()]]]]
|
||||
$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]]
|
||||
$template
|
||||
static Result Perform(Impl* impl, const ::std::tr1::tuple<$As>& args) {
|
||||
using ::std::tr1::get;
|
||||
static Result Perform(Impl* impl, const ::testing::tuple<$As>& args) {
|
||||
return impl->template gmock_PerformImpl<$As>(args, $arg_list);
|
||||
}
|
||||
|
||||
|
@ -419,7 +396,7 @@ $range j2 2..i
|
|||
// MORE INFORMATION:
|
||||
//
|
||||
// To learn more about using these macros, please search for 'ACTION'
|
||||
// on http://code.google.com/p/googlemock/wiki/CookBook.
|
||||
// on https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md
|
||||
|
||||
$range i 0..n
|
||||
$range k 0..n-1
|
||||
|
@ -427,7 +404,7 @@ $range k 0..n-1
|
|||
// An internal macro needed for implementing ACTION*().
|
||||
#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\
|
||||
const args_type& args GTEST_ATTRIBUTE_UNUSED_
|
||||
$for k [[,\
|
||||
$for k [[, \
|
||||
arg$k[[]]_type arg$k GTEST_ATTRIBUTE_UNUSED_]]
|
||||
|
||||
|
||||
|
@ -455,7 +432,7 @@ $for k [[,\
|
|||
// ACTION_TEMPLATE(DuplicateArg,
|
||||
// HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
|
||||
// AND_1_VALUE_PARAMS(output)) {
|
||||
// *output = T(std::tr1::get<k>(args));
|
||||
// *output = T(::testing::get<k>(args));
|
||||
// }
|
||||
// ...
|
||||
// int n;
|
||||
|
@ -548,7 +525,7 @@ _VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]]
|
|||
$for i [[
|
||||
$range j 0..i-1
|
||||
#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\
|
||||
($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(gmock_p$j)]]
|
||||
($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::testing::internal::move(gmock_p$j))]]
|
||||
|
||||
|
||||
]]
|
||||
|
@ -614,7 +591,7 @@ $range k 0..n-1
|
|||
GMOCK_INTERNAL_DECL_TYPE_##value_params>\
|
||||
class GMOCK_ACTION_CLASS_(name, value_params) {\
|
||||
public:\
|
||||
GMOCK_ACTION_CLASS_(name, value_params)\
|
||||
explicit GMOCK_ACTION_CLASS_(name, value_params)\
|
||||
GMOCK_INTERNAL_INIT_##value_params {}\
|
||||
template <typename F>\
|
||||
class gmock_Impl : public ::testing::ActionInterface<F> {\
|
||||
|
@ -657,9 +634,9 @@ $for k [[, arg$k[[]]_type arg$k]]) const;\
|
|||
template <GMOCK_INTERNAL_DECL_##template_params\
|
||||
GMOCK_INTERNAL_DECL_TYPE_##value_params>\
|
||||
template <typename F>\
|
||||
template <typename arg0_type, typename arg1_type, typename arg2_type,\
|
||||
typename arg3_type, typename arg4_type, typename arg5_type,\
|
||||
typename arg6_type, typename arg7_type, typename arg8_type,\
|
||||
template <typename arg0_type, typename arg1_type, typename arg2_type, \
|
||||
typename arg3_type, typename arg4_type, typename arg5_type, \
|
||||
typename arg6_type, typename arg7_type, typename arg8_type, \
|
||||
typename arg9_type>\
|
||||
typename ::testing::internal::Function<F>::Result\
|
||||
GMOCK_ACTION_CLASS_(name, value_params)<\
|
||||
|
@ -681,7 +658,7 @@ $var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]]
|
|||
$range j 0..i-1
|
||||
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
|
||||
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
|
||||
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
|
||||
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::forward<p$j##_type>(gmock_p$j))]]]]]]
|
||||
$var param_field_decls = [[$for j
|
||||
[[
|
||||
|
||||
|
@ -702,7 +679,7 @@ $var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]]
|
|||
#define $macro_name(name$for j [[, p$j]])\$template
|
||||
class $class_name {\
|
||||
public:\
|
||||
$class_name($ctor_param_list)$inits {}\
|
||||
[[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\
|
||||
template <typename F>\
|
||||
class gmock_Impl : public ::testing::ActionInterface<F> {\
|
||||
public:\
|
||||
|
@ -740,11 +717,9 @@ $$ } // This meta comment fixes auto-indentation in Emacs. It won't
|
|||
$$ // show up in the generated code.
|
||||
|
||||
|
||||
// TODO(wan@google.com): move the following to a different .h file
|
||||
// such that we don't have to run 'pump' every time the code is
|
||||
// updated.
|
||||
namespace testing {
|
||||
|
||||
|
||||
// The ACTION*() macros trigger warning C4100 (unreferenced formal
|
||||
// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in
|
||||
// the macro definition, as the warnings are generated when the macro
|
||||
|
@ -785,6 +760,32 @@ namespace testing {
|
|||
// InvokeArgument action from temporary values and have it performed
|
||||
// later.
|
||||
|
||||
namespace internal {
|
||||
namespace invoke_argument {
|
||||
|
||||
// Appears in InvokeArgumentAdl's argument list to help avoid
|
||||
// accidental calls to user functions of the same name.
|
||||
struct AdlTag {};
|
||||
|
||||
// InvokeArgumentAdl - a helper for InvokeArgument.
|
||||
// The basic overloads are provided here for generic functors.
|
||||
// Overloads for other custom-callables are provided in the
|
||||
// internal/custom/callback-actions.h header.
|
||||
|
||||
$range i 0..n
|
||||
$for i
|
||||
[[
|
||||
$range j 1..i
|
||||
|
||||
template <typename R, typename F[[$for j [[, typename A$j]]]]>
|
||||
R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) {
|
||||
return f([[$for j, [[a$j]]]]);
|
||||
}
|
||||
]]
|
||||
|
||||
} // namespace invoke_argument
|
||||
} // namespace internal
|
||||
|
||||
$range i 0..n
|
||||
$for i [[
|
||||
$range j 0..i-1
|
||||
|
@ -792,8 +793,10 @@ $range j 0..i-1
|
|||
ACTION_TEMPLATE(InvokeArgument,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) {
|
||||
return internal::CallableHelper<return_type>::Call(
|
||||
::std::tr1::get<k>(args)$for j [[, p$j]]);
|
||||
using internal::invoke_argument::InvokeArgumentAdl;
|
||||
return InvokeArgumentAdl<return_type>(
|
||||
internal::invoke_argument::AdlTag(),
|
||||
::testing::get<k>(args)$for j [[, p$j]]);
|
||||
}
|
||||
|
||||
]]
|
||||
|
@ -822,4 +825,9 @@ ACTION_TEMPLATE(ReturnNew,
|
|||
|
||||
} // namespace testing
|
||||
|
||||
// Include any custom callback actions added by the local installation.
|
||||
// We must include this header at the end to make sure it can use the
|
||||
// declarations from this file.
|
||||
#include "gmock/internal/custom/gmock-generated-actions.h"
|
||||
|
||||
#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,6 +1,6 @@
|
|||
$$ -*- mode: c++; -*-
|
||||
$$ This is a Pump source file. Please use Pump to convert it to
|
||||
$$ gmock-generated-function-mockers.h.
|
||||
$$ This is a Pump source file. Please use Pump to convert
|
||||
$$ it to gmock-generated-function-mockers.h.
|
||||
$$
|
||||
$var n = 10 $$ The maximum arity we support.
|
||||
// Copyright 2007, Google Inc.
|
||||
|
@ -31,19 +31,24 @@ $var n = 10 $$ The maximum arity we support.
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file implements function mockers of various arities.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
|
||||
|
||||
#include "gmock/gmock-spec-builders.h"
|
||||
#include "gmock/internal/gmock-internal-utils.h"
|
||||
|
||||
#if GTEST_HAS_STD_FUNCTION_
|
||||
# include <functional>
|
||||
#endif
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
|
@ -64,7 +69,7 @@ $for i [[
|
|||
$range j 1..i
|
||||
$var typename_As = [[$for j [[, typename A$j]]]]
|
||||
$var As = [[$for j, [[A$j]]]]
|
||||
$var as = [[$for j, [[a$j]]]]
|
||||
$var as = [[$for j, [[internal::forward<A$j>(a$j)]]]]
|
||||
$var Aas = [[$for j, [[A$j a$j]]]]
|
||||
$var ms = [[$for j, [[m$j]]]]
|
||||
$var matchers = [[$for j, [[const Matcher<A$j>& m$j]]]]
|
||||
|
@ -75,13 +80,8 @@ class FunctionMocker<R($As)> : public
|
|||
typedef R F($As);
|
||||
typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
|
||||
|
||||
MockSpec<F>& With($matchers) {
|
||||
|
||||
$if i >= 1 [[
|
||||
this->current_spec().SetMatchers(::std::tr1::make_tuple($ms));
|
||||
|
||||
]]
|
||||
return this->current_spec();
|
||||
MockSpec<F> With($matchers) {
|
||||
return MockSpec<F>(this, ::testing::make_tuple($ms));
|
||||
}
|
||||
|
||||
R Invoke($Aas) {
|
||||
|
@ -95,6 +95,58 @@ $if i >= 1 [[
|
|||
|
||||
|
||||
]]
|
||||
// Removes the given pointer; this is a helper for the expectation setter method
|
||||
// for parameterless matchers.
|
||||
//
|
||||
// We want to make sure that the user cannot set a parameterless expectation on
|
||||
// overloaded methods, including methods which are overloaded on const. Example:
|
||||
//
|
||||
// class MockClass {
|
||||
// MOCK_METHOD0(GetName, string&());
|
||||
// MOCK_CONST_METHOD0(GetName, const string&());
|
||||
// };
|
||||
//
|
||||
// TEST() {
|
||||
// // This should be an error, as it's not clear which overload is expected.
|
||||
// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value));
|
||||
// }
|
||||
//
|
||||
// Here are the generated expectation-setter methods:
|
||||
//
|
||||
// class MockClass {
|
||||
// // Overload 1
|
||||
// MockSpec<string&()> gmock_GetName() { ... }
|
||||
// // Overload 2. Declared const so that the compiler will generate an
|
||||
// // error when trying to resolve between this and overload 4 in
|
||||
// // 'gmock_GetName(WithoutMatchers(), nullptr)'.
|
||||
// MockSpec<string&()> gmock_GetName(
|
||||
// const WithoutMatchers&, const Function<string&()>*) const {
|
||||
// // Removes const from this, calls overload 1
|
||||
// return AdjustConstness_(this)->gmock_GetName();
|
||||
// }
|
||||
//
|
||||
// // Overload 3
|
||||
// const string& gmock_GetName() const { ... }
|
||||
// // Overload 4
|
||||
// MockSpec<const string&()> gmock_GetName(
|
||||
// const WithoutMatchers&, const Function<const string&()>*) const {
|
||||
// // Does not remove const, calls overload 3
|
||||
// return AdjustConstness_const(this)->gmock_GetName();
|
||||
// }
|
||||
// }
|
||||
//
|
||||
template <typename MockType>
|
||||
const MockType* AdjustConstness_const(const MockType* mock) {
|
||||
return mock;
|
||||
}
|
||||
|
||||
// Removes const from and returns the given pointer; this is a helper for the
|
||||
// expectation setter method for parameterless matchers.
|
||||
template <typename MockType>
|
||||
MockType* AdjustConstness_(const MockType* mock) {
|
||||
return const_cast<MockType*>(mock);
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// The style guide prohibits "using" statements in a namespace scope
|
||||
|
@ -104,17 +156,23 @@ $if i >= 1 [[
|
|||
// cannot handle it if we define FunctionMocker in ::testing.
|
||||
using internal::FunctionMocker;
|
||||
|
||||
// The result type of function type F.
|
||||
// GMOCK_RESULT_(tn, F) expands to the result type of function type F.
|
||||
// We define this as a variadic macro in case F contains unprotected
|
||||
// commas (the same reason that we use variadic macros in other places
|
||||
// in this file).
|
||||
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
|
||||
#define GMOCK_RESULT_(tn, F) tn ::testing::internal::Function<F>::Result
|
||||
#define GMOCK_RESULT_(tn, ...) \
|
||||
tn ::testing::internal::Function<__VA_ARGS__>::Result
|
||||
|
||||
// The type of argument N of function type F.
|
||||
// The type of argument N of the given function type.
|
||||
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
|
||||
#define GMOCK_ARG_(tn, F, N) tn ::testing::internal::Function<F>::Argument##N
|
||||
#define GMOCK_ARG_(tn, N, ...) \
|
||||
tn ::testing::internal::Function<__VA_ARGS__>::Argument##N
|
||||
|
||||
// The matcher type for argument N of function type F.
|
||||
// The matcher type for argument N of the given function type.
|
||||
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
|
||||
#define GMOCK_MATCHER_(tn, F, N) const ::testing::Matcher<GMOCK_ARG_(tn, F, N)>&
|
||||
#define GMOCK_MATCHER_(tn, N, ...) \
|
||||
const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>&
|
||||
|
||||
// The variable for mocking the given method.
|
||||
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
|
||||
|
@ -124,78 +182,88 @@ using internal::FunctionMocker;
|
|||
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$var arg_as = [[$for j, \
|
||||
[[GMOCK_ARG_(tn, F, $j) gmock_a$j]]]]
|
||||
$var as = [[$for j, [[gmock_a$j]]]]
|
||||
$var matcher_as = [[$for j, \
|
||||
[[GMOCK_MATCHER_(tn, F, $j) gmock_a$j]]]]
|
||||
$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
|
||||
$var as = [[$for j, \
|
||||
[[::testing::internal::forward<GMOCK_ARG_(tn, $j, __VA_ARGS__)>(gmock_a$j)]]]]
|
||||
$var matcher_arg_as = [[$for j, \
|
||||
[[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]]
|
||||
$var matcher_as = [[$for j, [[gmock_a$j]]]]
|
||||
$var anything_matchers = [[$for j, \
|
||||
[[::testing::A<GMOCK_ARG_(tn, $j, __VA_ARGS__)>()]]]]
|
||||
// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!!
|
||||
#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, F) \
|
||||
GMOCK_RESULT_(tn, F) ct Method($arg_as) constness { \
|
||||
GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \
|
||||
tn ::testing::internal::Function<F>::ArgumentTuple>::value == $i, \
|
||||
#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \
|
||||
GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \
|
||||
$arg_as) constness { \
|
||||
GTEST_COMPILE_ASSERT_((::testing::tuple_size< \
|
||||
tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value == $i), \
|
||||
this_method_does_not_take_$i[[]]_argument[[$if i != 1 [[s]]]]); \
|
||||
GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \
|
||||
return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \
|
||||
} \
|
||||
::testing::MockSpec<F>& \
|
||||
gmock_##Method($matcher_as) constness { \
|
||||
::testing::MockSpec<__VA_ARGS__> \
|
||||
gmock_##Method($matcher_arg_as) constness { \
|
||||
GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \
|
||||
return GMOCK_MOCKER_($i, constness, Method).With($as); \
|
||||
return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \
|
||||
} \
|
||||
mutable ::testing::FunctionMocker<F> GMOCK_MOCKER_($i, constness, Method)
|
||||
::testing::MockSpec<__VA_ARGS__> gmock_##Method( \
|
||||
const ::testing::internal::WithoutMatchers&, \
|
||||
constness ::testing::internal::Function<__VA_ARGS__>* ) const { \
|
||||
return ::testing::internal::AdjustConstness_##constness(this)-> \
|
||||
gmock_##Method($anything_matchers); \
|
||||
} \
|
||||
mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method)
|
||||
|
||||
|
||||
]]
|
||||
$for i [[
|
||||
#define MOCK_METHOD$i(m, F) GMOCK_METHOD$i[[]]_(, , , m, F)
|
||||
#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
||||
$for i [[
|
||||
#define MOCK_CONST_METHOD$i(m, F) GMOCK_METHOD$i[[]]_(, const, , m, F)
|
||||
#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
||||
$for i [[
|
||||
#define MOCK_METHOD$i[[]]_T(m, F) GMOCK_METHOD$i[[]]_(typename, , , m, F)
|
||||
#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
||||
$for i [[
|
||||
#define MOCK_CONST_METHOD$i[[]]_T(m, F) [[]]
|
||||
GMOCK_METHOD$i[[]]_(typename, const, , m, F)
|
||||
#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \
|
||||
GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
||||
$for i [[
|
||||
#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, F) [[]]
|
||||
GMOCK_METHOD$i[[]]_(, , ct, m, F)
|
||||
#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
||||
$for i [[
|
||||
#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, F) \
|
||||
GMOCK_METHOD$i[[]]_(, const, ct, m, F)
|
||||
#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
||||
$for i [[
|
||||
#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, F) \
|
||||
GMOCK_METHOD$i[[]]_(typename, , ct, m, F)
|
||||
#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
||||
$for i [[
|
||||
#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, F) \
|
||||
GMOCK_METHOD$i[[]]_(typename, const, ct, m, F)
|
||||
#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__)
|
||||
|
||||
]]
|
||||
|
||||
|
@ -234,18 +302,40 @@ $for i [[
|
|||
// point "2", and nothing should happen between the two check
|
||||
// points. The explicit check points make it easy to tell which
|
||||
// Bar("a") is called by which call to Foo().
|
||||
//
|
||||
// MockFunction<F> can also be used to exercise code that accepts
|
||||
// std::function<F> callbacks. To do so, use AsStdFunction() method
|
||||
// to create std::function proxy forwarding to original object's Call.
|
||||
// Example:
|
||||
//
|
||||
// TEST(FooTest, RunsCallbackWithBarArgument) {
|
||||
// MockFunction<int(string)> callback;
|
||||
// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
|
||||
// Foo(callback.AsStdFunction());
|
||||
// }
|
||||
template <typename F>
|
||||
class MockFunction;
|
||||
|
||||
|
||||
$for i [[
|
||||
$range j 0..i-1
|
||||
$var ArgTypes = [[$for j, [[A$j]]]]
|
||||
$var ArgValues = [[$for j, [[::std::move(a$j)]]]]
|
||||
$var ArgDecls = [[$for j, [[A$j a$j]]]]
|
||||
template <typename R$for j [[, typename A$j]]>
|
||||
class MockFunction<R($for j, [[A$j]])> {
|
||||
class MockFunction<R($ArgTypes)> {
|
||||
public:
|
||||
MockFunction() {}
|
||||
|
||||
MOCK_METHOD$i[[]]_T(Call, R($for j, [[A$j]]));
|
||||
MOCK_METHOD$i[[]]_T(Call, R($ArgTypes));
|
||||
|
||||
#if GTEST_HAS_STD_FUNCTION_
|
||||
::std::function<R($ArgTypes)> AsStdFunction() {
|
||||
return [this]($ArgDecls) -> R {
|
||||
return this->Call($ArgValues);
|
||||
};
|
||||
}
|
||||
#endif // GTEST_HAS_STD_FUNCTION_
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction);
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,6 +1,6 @@
|
|||
$$ -*- mode: c++; -*-
|
||||
$$ This is a Pump source file. Please use Pump to convert it to
|
||||
$$ gmock-generated-actions.h.
|
||||
$$ This is a Pump source file. Please use Pump to convert
|
||||
$$ it to gmock-generated-matchers.h.
|
||||
$$
|
||||
$var n = 10 $$ The maximum arity we support.
|
||||
$$ }} This line fixes auto-indentation of the following code in Emacs.
|
||||
|
@ -37,9 +37,12 @@ $$ }} This line fixes auto-indentation of the following code in Emacs.
|
|||
//
|
||||
// This file implements some commonly used variadic matchers.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
|
||||
|
||||
#include <iterator>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
@ -52,7 +55,7 @@ $range i 0..n-1
|
|||
|
||||
// The type of the i-th (0-based) field of Tuple.
|
||||
#define GMOCK_FIELD_TYPE_(Tuple, i) \
|
||||
typename ::std::tr1::tuple_element<i, Tuple>::type
|
||||
typename ::testing::tuple_element<i, Tuple>::type
|
||||
|
||||
// TupleFields<Tuple, k0, ..., kn> is for selecting fields from a
|
||||
// tuple of type Tuple. It has two members:
|
||||
|
@ -72,9 +75,8 @@ class TupleFields;
|
|||
template <class Tuple$for i [[, int k$i]]>
|
||||
class TupleFields {
|
||||
public:
|
||||
typedef ::std::tr1::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type;
|
||||
typedef ::testing::tuple<$for i, [[GMOCK_FIELD_TYPE_(Tuple, k$i)]]> type;
|
||||
static type GetSelectedFields(const Tuple& t) {
|
||||
using ::std::tr1::get;
|
||||
return type($for i, [[get<k$i>(t)]]);
|
||||
}
|
||||
};
|
||||
|
@ -89,9 +91,8 @@ $range k 0..n-1
|
|||
template <class Tuple$for j [[, int k$j]]>
|
||||
class TupleFields<Tuple, $for k, [[$if k < i [[k$k]] $else [[-1]]]]> {
|
||||
public:
|
||||
typedef ::std::tr1::tuple<$for j, [[GMOCK_FIELD_TYPE_(Tuple, k$j)]]> type;
|
||||
typedef ::testing::tuple<$for j, [[GMOCK_FIELD_TYPE_(Tuple, k$j)]]> type;
|
||||
static type GetSelectedFields(const Tuple& $if i==0 [[/* t */]] $else [[t]]) {
|
||||
using ::std::tr1::get;
|
||||
return type($for j, [[get<k$j>(t)]]);
|
||||
}
|
||||
};
|
||||
|
@ -186,62 +187,66 @@ class ArgsMatcher {
|
|||
GTEST_DISALLOW_ASSIGN_(ArgsMatcher);
|
||||
};
|
||||
|
||||
// Implements ElementsAre() of 1-$n arguments.
|
||||
// A set of metafunctions for computing the result type of AllOf.
|
||||
// AllOf(m1, ..., mN) returns
|
||||
// AllOfResultN<decltype(m1), ..., decltype(mN)>::type.
|
||||
|
||||
|
||||
$range i 1..n
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
template <$for j, [[typename T$j]]>
|
||||
class ElementsAreMatcher$i {
|
||||
public:
|
||||
$if i==1 [[explicit ]]ElementsAreMatcher$i($for j, [[const T$j& e$j]])$if i > 0 [[ : ]]
|
||||
$for j, [[e$j[[]]_(e$j)]] {}
|
||||
|
||||
template <typename Container>
|
||||
operator Matcher<Container>() const {
|
||||
typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
|
||||
typedef typename internal::StlContainerView<RawContainer>::type::value_type
|
||||
Element;
|
||||
|
||||
$if i==1 [[
|
||||
|
||||
// Nokia's Symbian Compiler has a nasty bug where the object put
|
||||
// in a one-element local array is not destructed when the array
|
||||
// goes out of scope. This leads to obvious badness as we've
|
||||
// added the linked_ptr in it to our other linked_ptrs list.
|
||||
// Hence we implement ElementsAreMatcher1 specially to avoid using
|
||||
// a local array.
|
||||
const Matcher<const Element&> matcher =
|
||||
MatcherCast<const Element&>(e1_);
|
||||
return MakeMatcher(new ElementsAreMatcherImpl<Container>(&matcher, 1));
|
||||
]] $else [[
|
||||
|
||||
const Matcher<const Element&> matchers[] = {
|
||||
|
||||
$for j [[
|
||||
MatcherCast<const Element&>(e$j[[]]_),
|
||||
|
||||
]]
|
||||
};
|
||||
|
||||
return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, $i));
|
||||
]]
|
||||
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
$for j [[
|
||||
const T$j& e$j[[]]_;
|
||||
|
||||
]]
|
||||
|
||||
GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher$i);
|
||||
// Although AllOf isn't defined for one argument, AllOfResult1 is defined
|
||||
// to simplify the implementation.
|
||||
template <typename M1>
|
||||
struct AllOfResult1 {
|
||||
typedef M1 type;
|
||||
};
|
||||
|
||||
$range i 1..n
|
||||
|
||||
$range i 2..n
|
||||
$for i [[
|
||||
$range j 2..i
|
||||
$var m = i/2
|
||||
$range k 1..m
|
||||
$range t m+1..i
|
||||
|
||||
template <typename M1$for j [[, typename M$j]]>
|
||||
struct AllOfResult$i {
|
||||
typedef BothOfMatcher<
|
||||
typename AllOfResult$m<$for k, [[M$k]]>::type,
|
||||
typename AllOfResult$(i-m)<$for t, [[M$t]]>::type
|
||||
> type;
|
||||
};
|
||||
|
||||
]]
|
||||
|
||||
// A set of metafunctions for computing the result type of AnyOf.
|
||||
// AnyOf(m1, ..., mN) returns
|
||||
// AnyOfResultN<decltype(m1), ..., decltype(mN)>::type.
|
||||
|
||||
// Although AnyOf isn't defined for one argument, AnyOfResult1 is defined
|
||||
// to simplify the implementation.
|
||||
template <typename M1>
|
||||
struct AnyOfResult1 {
|
||||
typedef M1 type;
|
||||
};
|
||||
|
||||
$range i 1..n
|
||||
|
||||
$range i 2..n
|
||||
$for i [[
|
||||
$range j 2..i
|
||||
$var m = i/2
|
||||
$range k 1..m
|
||||
$range t m+1..i
|
||||
|
||||
template <typename M1$for j [[, typename M$j]]>
|
||||
struct AnyOfResult$i {
|
||||
typedef EitherOfMatcher<
|
||||
typename AnyOfResult$m<$for k, [[M$k]]>::type,
|
||||
typename AnyOfResult$(i-m)<$for t, [[M$t]]>::type
|
||||
> type;
|
||||
};
|
||||
|
||||
]]
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected
|
||||
|
@ -259,48 +264,75 @@ Args(const InnerMatcher& matcher) {
|
|||
|
||||
|
||||
]]
|
||||
// ElementsAre(e0, e1, ..., e_n) matches an STL-style container with
|
||||
// (n + 1) elements, where the i-th element in the container must
|
||||
// ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with
|
||||
// n elements, where the i-th element in the container must
|
||||
// match the i-th argument in the list. Each argument of
|
||||
// ElementsAre() can be either a value or a matcher. We support up to
|
||||
// $n arguments.
|
||||
//
|
||||
// The use of DecayArray in the implementation allows ElementsAre()
|
||||
// to accept string literals, whose type is const char[N], but we
|
||||
// want to treat them as const char*.
|
||||
//
|
||||
// NOTE: Since ElementsAre() cares about the order of the elements, it
|
||||
// must not be used with containers whose elements's order is
|
||||
// undefined (e.g. hash_map).
|
||||
|
||||
inline internal::ElementsAreMatcher0 ElementsAre() {
|
||||
return internal::ElementsAreMatcher0();
|
||||
}
|
||||
|
||||
$range i 1..n
|
||||
$range i 0..n
|
||||
$for i [[
|
||||
|
||||
$range j 1..i
|
||||
|
||||
$if i>0 [[
|
||||
|
||||
template <$for j, [[typename T$j]]>
|
||||
inline internal::ElementsAreMatcher$i<$for j, [[T$j]]> ElementsAre($for j, [[const T$j& e$j]]) {
|
||||
return internal::ElementsAreMatcher$i<$for j, [[T$j]]>($for j, [[e$j]]);
|
||||
]]
|
||||
|
||||
inline internal::ElementsAreMatcher<
|
||||
::testing::tuple<
|
||||
$for j, [[
|
||||
|
||||
typename internal::DecayArray<T$j[[]]>::type]]> >
|
||||
ElementsAre($for j, [[const T$j& e$j]]) {
|
||||
typedef ::testing::tuple<
|
||||
$for j, [[
|
||||
|
||||
typename internal::DecayArray<T$j[[]]>::type]]> Args;
|
||||
return internal::ElementsAreMatcher<Args>(Args($for j, [[e$j]]));
|
||||
}
|
||||
|
||||
]]
|
||||
|
||||
// ElementsAreArray(array) and ElementAreArray(array, count) are like
|
||||
// ElementsAre(), except that they take an array of values or
|
||||
// matchers. The former form infers the size of 'array', which must
|
||||
// be a static C-style array. In the latter form, 'array' can either
|
||||
// be a static array or a pointer to a dynamically created array.
|
||||
// UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension
|
||||
// that matches n elements in any order. We support up to n=$n arguments.
|
||||
//
|
||||
// If you have >$n elements, consider UnorderedElementsAreArray() or
|
||||
// UnorderedPointwise() instead.
|
||||
|
||||
template <typename T>
|
||||
inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
|
||||
const T* first, size_t count) {
|
||||
return internal::ElementsAreArrayMatcher<T>(first, count);
|
||||
$range i 0..n
|
||||
$for i [[
|
||||
|
||||
$range j 1..i
|
||||
|
||||
$if i>0 [[
|
||||
|
||||
template <$for j, [[typename T$j]]>
|
||||
]]
|
||||
|
||||
inline internal::UnorderedElementsAreMatcher<
|
||||
::testing::tuple<
|
||||
$for j, [[
|
||||
|
||||
typename internal::DecayArray<T$j[[]]>::type]]> >
|
||||
UnorderedElementsAre($for j, [[const T$j& e$j]]) {
|
||||
typedef ::testing::tuple<
|
||||
$for j, [[
|
||||
|
||||
typename internal::DecayArray<T$j[[]]>::type]]> Args;
|
||||
return internal::UnorderedElementsAreMatcher<Args>(Args($for j, [[e$j]]));
|
||||
}
|
||||
|
||||
template <typename T, size_t N>
|
||||
inline internal::ElementsAreArrayMatcher<T>
|
||||
ElementsAreArray(const T (&array)[N]) {
|
||||
return internal::ElementsAreArrayMatcher<T>(array, N);
|
||||
}
|
||||
]]
|
||||
|
||||
// AllOf(m1, m2, ..., mk) matches any value that matches all of the given
|
||||
// sub-matchers. AllOf is called fully qualified to prevent ADL from firing.
|
||||
|
@ -308,19 +340,16 @@ ElementsAreArray(const T (&array)[N]) {
|
|||
$range i 2..n
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$range k 1..i-1
|
||||
|
||||
template <$for j, [[typename Matcher$j]]>
|
||||
inline $for k[[internal::BothOfMatcher<Matcher$k, ]]Matcher$i[[]]$for k [[> ]]
|
||||
|
||||
AllOf($for j, [[Matcher$j m$j]]) {
|
||||
|
||||
$if i == 2 [[
|
||||
return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
|
||||
]] $else [[
|
||||
return ::testing::AllOf(m1, ::testing::AllOf($for k, [[m$(k + 1)]]));
|
||||
]]
|
||||
$var m = i/2
|
||||
$range k 1..m
|
||||
$range t m+1..i
|
||||
|
||||
template <$for j, [[typename M$j]]>
|
||||
inline typename internal::AllOfResult$i<$for j, [[M$j]]>::type
|
||||
AllOf($for j, [[M$j m$j]]) {
|
||||
return typename internal::AllOfResult$i<$for j, [[M$j]]>::type(
|
||||
$if m == 1 [[m1]] $else [[::testing::AllOf($for k, [[m$k]])]],
|
||||
$if m+1 == i [[m$i]] $else [[::testing::AllOf($for t, [[m$t]])]]);
|
||||
}
|
||||
|
||||
]]
|
||||
|
@ -331,19 +360,16 @@ $if i == 2 [[
|
|||
$range i 2..n
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
$range k 1..i-1
|
||||
|
||||
template <$for j, [[typename Matcher$j]]>
|
||||
inline $for k[[internal::EitherOfMatcher<Matcher$k, ]]Matcher$i[[]]$for k [[> ]]
|
||||
|
||||
AnyOf($for j, [[Matcher$j m$j]]) {
|
||||
|
||||
$if i == 2 [[
|
||||
return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
|
||||
]] $else [[
|
||||
return ::testing::AnyOf(m1, ::testing::AnyOf($for k, [[m$(k + 1)]]));
|
||||
]]
|
||||
$var m = i/2
|
||||
$range k 1..m
|
||||
$range t m+1..i
|
||||
|
||||
template <$for j, [[typename M$j]]>
|
||||
inline typename internal::AnyOfResult$i<$for j, [[M$j]]>::type
|
||||
AnyOf($for j, [[M$j m$j]]) {
|
||||
return typename internal::AnyOfResult$i<$for j, [[M$j]]>::type(
|
||||
$if m == 1 [[m1]] $else [[::testing::AnyOf($for k, [[m$k]])]],
|
||||
$if m+1 == i [[m$i]] $else [[::testing::AnyOf($for t, [[m$t]])]]);
|
||||
}
|
||||
|
||||
]]
|
||||
|
@ -458,7 +484,7 @@ $$ // show up in the generated code.
|
|||
// using testing::PrintToString;
|
||||
//
|
||||
// MATCHER_P2(InClosedRange, low, hi,
|
||||
// string(negation ? "is not" : "is") + " in range [" +
|
||||
// std::string(negation ? "is not" : "is") + " in range [" +
|
||||
// PrintToString(low) + ", " + PrintToString(hi) + "]") {
|
||||
// return low <= arg && arg <= hi;
|
||||
// }
|
||||
|
@ -566,7 +592,8 @@ $$ // show up in the generated code.
|
|||
// ================
|
||||
//
|
||||
// To learn more about using these macros, please search for 'MATCHER'
|
||||
// on http://code.google.com/p/googlemock/wiki/CookBook.
|
||||
// on
|
||||
// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md
|
||||
|
||||
$range i 0..n
|
||||
$for i
|
||||
|
@ -583,32 +610,34 @@ $var template = [[$if i==0 [[]] $else [[
|
|||
]]]]
|
||||
$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
|
||||
$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]]
|
||||
$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
|
||||
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(gmock_p$j)]]]]]]
|
||||
$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]]
|
||||
$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::testing::internal::move(gmock_p$j))]]]]]]
|
||||
$var params = [[$for j, [[p$j]]]]
|
||||
$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]]
|
||||
$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]]
|
||||
$var param_field_decls = [[$for j
|
||||
[[
|
||||
|
||||
p$j##_type p$j;\
|
||||
p$j##_type const p$j;\
|
||||
]]]]
|
||||
$var param_field_decls2 = [[$for j
|
||||
[[
|
||||
|
||||
p$j##_type p$j;\
|
||||
p$j##_type const p$j;\
|
||||
]]]]
|
||||
|
||||
#define $macro_name(name$for j [[, p$j]], description)\$template
|
||||
class $class_name {\
|
||||
public:\
|
||||
template <typename arg_type>\
|
||||
class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\
|
||||
class gmock_Impl : public ::testing::MatcherInterface<\
|
||||
GTEST_REFERENCE_TO_CONST_(arg_type)> {\
|
||||
public:\
|
||||
[[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\
|
||||
$impl_inits {}\
|
||||
virtual bool MatchAndExplain(\
|
||||
arg_type arg, ::testing::MatchResultListener* result_listener) const;\
|
||||
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
|
||||
::testing::MatchResultListener* result_listener) const;\
|
||||
virtual void DescribeTo(::std::ostream* gmock_os) const {\
|
||||
*gmock_os << FormatDescription(false);\
|
||||
}\
|
||||
|
@ -616,33 +645,31 @@ $var param_field_decls2 = [[$for j
|
|||
*gmock_os << FormatDescription(true);\
|
||||
}\$param_field_decls
|
||||
private:\
|
||||
::testing::internal::string FormatDescription(bool negation) const {\
|
||||
const ::testing::internal::string gmock_description = (description);\
|
||||
::std::string FormatDescription(bool negation) const {\
|
||||
::std::string gmock_description = (description);\
|
||||
if (!gmock_description.empty())\
|
||||
return gmock_description;\
|
||||
return ::testing::internal::FormatMatcherDescription(\
|
||||
negation, #name,\
|
||||
negation, #name, \
|
||||
::testing::internal::UniversalTersePrintTupleFieldsToStrings(\
|
||||
::std::tr1::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
|
||||
::testing::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\
|
||||
}\
|
||||
GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
|
||||
};\
|
||||
template <typename arg_type>\
|
||||
operator ::testing::Matcher<arg_type>() const {\
|
||||
return ::testing::Matcher<arg_type>(\
|
||||
new gmock_Impl<arg_type>($params));\
|
||||
}\
|
||||
$class_name($ctor_param_list)$inits {\
|
||||
[[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\
|
||||
}\$param_field_decls2
|
||||
private:\
|
||||
GTEST_DISALLOW_ASSIGN_($class_name);\
|
||||
};\$template
|
||||
inline $class_name$param_types name($param_types_and_names) {\
|
||||
return $class_name$param_types($params);\
|
||||
}\$template
|
||||
template <typename arg_type>\
|
||||
bool $class_name$param_types::gmock_Impl<arg_type>::MatchAndExplain(\
|
||||
arg_type arg,\
|
||||
GTEST_REFERENCE_TO_CONST_(arg_type) arg,\
|
||||
::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\
|
||||
const
|
||||
]]
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
// This file was GENERATED by a script. DO NOT EDIT BY HAND!!!
|
||||
// This file was GENERATED by command:
|
||||
// pump.py gmock-generated-nice-strict.h.pump
|
||||
// DO NOT EDIT BY HAND!!!
|
||||
|
||||
// Copyright 2008, Google Inc.
|
||||
// All rights reserved.
|
||||
|
@ -28,33 +30,39 @@
|
|||
// 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)
|
||||
|
||||
// Implements class templates NiceMock and StrictMock.
|
||||
|
||||
// Implements class templates NiceMock, NaggyMock, and StrictMock.
|
||||
//
|
||||
// Given a mock class MockFoo that is created using Google Mock,
|
||||
// NiceMock<MockFoo> is a subclass of MockFoo that allows
|
||||
// uninteresting calls (i.e. calls to mock methods that have no
|
||||
// EXPECT_CALL specs), and StrictMock<MockFoo> is a subclass of
|
||||
// MockFoo that treats all uninteresting calls as errors.
|
||||
// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
|
||||
// that prints a warning when an uninteresting call occurs, and
|
||||
// StrictMock<MockFoo> is a subclass of MockFoo that treats all
|
||||
// uninteresting calls as errors.
|
||||
//
|
||||
// NiceMock and StrictMock "inherits" the constructors of their
|
||||
// respective base class, with up-to 10 arguments. Therefore you can
|
||||
// write NiceMock<MockFoo>(5, "a") to construct a nice mock where
|
||||
// MockFoo has a constructor that accepts (int, const char*), for
|
||||
// example.
|
||||
// Currently a mock is naggy by default, so MockFoo and
|
||||
// NaggyMock<MockFoo> behave like the same. However, we will soon
|
||||
// switch the default behavior of mocks to be nice, as that in general
|
||||
// leads to more maintainable tests. When that happens, MockFoo will
|
||||
// stop behaving like NaggyMock<MockFoo> and start behaving like
|
||||
// NiceMock<MockFoo>.
|
||||
//
|
||||
// A known limitation is that NiceMock<MockFoo> and
|
||||
// StrictMock<MockFoo> only works for mock methods defined using the
|
||||
// MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. If a
|
||||
// mock method is defined in a base class of MockFoo, the "nice" or
|
||||
// "strict" modifier may not affect it, depending on the compiler. In
|
||||
// particular, nesting NiceMock and StrictMock is NOT supported.
|
||||
// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
|
||||
// their respective base class. Therefore you can write
|
||||
// NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo
|
||||
// has a constructor that accepts (int, const char*), for example.
|
||||
//
|
||||
// Another known limitation is that the constructors of the base mock
|
||||
// cannot have arguments passed by non-const reference, which are
|
||||
// banned by the Google C++ style guide anyway.
|
||||
// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
|
||||
// and StrictMock<MockFoo> only works for mock methods defined using
|
||||
// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
|
||||
// If a mock method is defined in a base class of MockFoo, the "nice"
|
||||
// or "strict" modifier may not affect it, depending on the compiler.
|
||||
// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
|
||||
// supported.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
|
||||
|
@ -67,15 +75,35 @@ namespace testing {
|
|||
template <class MockClass>
|
||||
class NiceMock : public MockClass {
|
||||
public:
|
||||
// We don't factor out the constructor body to a common method, as
|
||||
// we have to avoid a possible clash with members of MockClass.
|
||||
NiceMock() {
|
||||
NiceMock() : MockClass() {
|
||||
::testing::Mock::AllowUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
// C++ doesn't (yet) allow inheritance of constructors, so we have
|
||||
// to define it for each arity.
|
||||
#if GTEST_LANG_CXX11
|
||||
// Ideally, we would inherit base class's constructors through a using
|
||||
// declaration, which would preserve their visibility. However, many existing
|
||||
// tests rely on the fact that current implementation reexports protected
|
||||
// constructors as public. These tests would need to be cleaned up first.
|
||||
|
||||
// Single argument constructor is special-cased so that it can be
|
||||
// made explicit.
|
||||
template <typename A>
|
||||
explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {
|
||||
::testing::Mock::AllowUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename... An>
|
||||
NiceMock(A1&& arg1, A2&& arg2, An&&... args)
|
||||
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
|
||||
std::forward<An>(args)...) {
|
||||
::testing::Mock::AllowUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
#else
|
||||
// C++98 doesn't have variadic templates, so we have to define one
|
||||
// for each arity.
|
||||
template <typename A1>
|
||||
explicit NiceMock(const A1& a1) : MockClass(a1) {
|
||||
::testing::Mock::AllowUninterestingCalls(
|
||||
|
@ -151,7 +179,9 @@ class NiceMock : public MockClass {
|
|||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
virtual ~NiceMock() {
|
||||
#endif // GTEST_LANG_CXX11
|
||||
|
||||
~NiceMock() {
|
||||
::testing::Mock::UnregisterCallReaction(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
@ -160,16 +190,156 @@ class NiceMock : public MockClass {
|
|||
GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
|
||||
};
|
||||
|
||||
template <class MockClass>
|
||||
class NaggyMock : public MockClass {
|
||||
public:
|
||||
NaggyMock() : MockClass() {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
#if GTEST_LANG_CXX11
|
||||
// Ideally, we would inherit base class's constructors through a using
|
||||
// declaration, which would preserve their visibility. However, many existing
|
||||
// tests rely on the fact that current implementation reexports protected
|
||||
// constructors as public. These tests would need to be cleaned up first.
|
||||
|
||||
// Single argument constructor is special-cased so that it can be
|
||||
// made explicit.
|
||||
template <typename A>
|
||||
explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename... An>
|
||||
NaggyMock(A1&& arg1, A2&& arg2, An&&... args)
|
||||
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
|
||||
std::forward<An>(args)...) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
#else
|
||||
// C++98 doesn't have variadic templates, so we have to define one
|
||||
// for each arity.
|
||||
template <typename A1>
|
||||
explicit NaggyMock(const A1& a1) : MockClass(a1) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
template <typename A1, typename A2>
|
||||
NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3,
|
||||
const A4& a4) : MockClass(a1, a2, a3, a4) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
|
||||
const A5& a5) : MockClass(a1, a2, a3, a4, a5) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
|
||||
const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
|
||||
const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5,
|
||||
a6, a7) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7, typename A8>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
|
||||
const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1,
|
||||
a2, a3, a4, a5, a6, a7, a8) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7, typename A8, typename A9>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
|
||||
const A5& a5, const A6& a6, const A7& a7, const A8& a8,
|
||||
const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7, typename A8, typename A9, typename A10>
|
||||
NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4,
|
||||
const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9,
|
||||
const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
|
||||
::testing::Mock::WarnUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
#endif // GTEST_LANG_CXX11
|
||||
|
||||
~NaggyMock() {
|
||||
::testing::Mock::UnregisterCallReaction(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock);
|
||||
};
|
||||
|
||||
template <class MockClass>
|
||||
class StrictMock : public MockClass {
|
||||
public:
|
||||
// We don't factor out the constructor body to a common method, as
|
||||
// we have to avoid a possible clash with members of MockClass.
|
||||
StrictMock() {
|
||||
StrictMock() : MockClass() {
|
||||
::testing::Mock::FailUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
#if GTEST_LANG_CXX11
|
||||
// Ideally, we would inherit base class's constructors through a using
|
||||
// declaration, which would preserve their visibility. However, many existing
|
||||
// tests rely on the fact that current implementation reexports protected
|
||||
// constructors as public. These tests would need to be cleaned up first.
|
||||
|
||||
// Single argument constructor is special-cased so that it can be
|
||||
// made explicit.
|
||||
template <typename A>
|
||||
explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {
|
||||
::testing::Mock::FailUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename... An>
|
||||
StrictMock(A1&& arg1, A2&& arg2, An&&... args)
|
||||
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
|
||||
std::forward<An>(args)...) {
|
||||
::testing::Mock::FailUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
#else
|
||||
// C++98 doesn't have variadic templates, so we have to define one
|
||||
// for each arity.
|
||||
template <typename A1>
|
||||
explicit StrictMock(const A1& a1) : MockClass(a1) {
|
||||
::testing::Mock::FailUninterestingCalls(
|
||||
|
@ -245,7 +415,9 @@ class StrictMock : public MockClass {
|
|||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
virtual ~StrictMock() {
|
||||
#endif // GTEST_LANG_CXX11
|
||||
|
||||
~StrictMock() {
|
||||
::testing::Mock::UnregisterCallReaction(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
@ -258,15 +430,28 @@ class StrictMock : public MockClass {
|
|||
// user errors of nesting nice and strict mocks. They do NOT catch
|
||||
// all possible errors.
|
||||
|
||||
// These specializations are declared but not defined, as NiceMock and
|
||||
// StrictMock cannot be nested.
|
||||
// These specializations are declared but not defined, as NiceMock,
|
||||
// NaggyMock, and StrictMock cannot be nested.
|
||||
|
||||
template <typename MockClass>
|
||||
class NiceMock<NiceMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NiceMock<NaggyMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NiceMock<StrictMock<MockClass> >;
|
||||
|
||||
template <typename MockClass>
|
||||
class NaggyMock<NiceMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NaggyMock<NaggyMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NaggyMock<StrictMock<MockClass> >;
|
||||
|
||||
template <typename MockClass>
|
||||
class StrictMock<NiceMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class StrictMock<NaggyMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class StrictMock<StrictMock<MockClass> >;
|
||||
|
||||
} // namespace testing
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
$$ -*- mode: c++; -*-
|
||||
$$ This is a Pump source file. Please use Pump to convert it to
|
||||
$$ gmock-generated-nice-strict.h.
|
||||
$$ This is a Pump source file. Please use Pump to convert
|
||||
$$ it to gmock-generated-nice-strict.h.
|
||||
$$
|
||||
$var n = 10 $$ The maximum arity we support.
|
||||
// Copyright 2008, Google Inc.
|
||||
|
@ -31,33 +31,39 @@ $var n = 10 $$ The maximum arity we support.
|
|||
// 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)
|
||||
|
||||
// Implements class templates NiceMock and StrictMock.
|
||||
|
||||
// Implements class templates NiceMock, NaggyMock, and StrictMock.
|
||||
//
|
||||
// Given a mock class MockFoo that is created using Google Mock,
|
||||
// NiceMock<MockFoo> is a subclass of MockFoo that allows
|
||||
// uninteresting calls (i.e. calls to mock methods that have no
|
||||
// EXPECT_CALL specs), and StrictMock<MockFoo> is a subclass of
|
||||
// MockFoo that treats all uninteresting calls as errors.
|
||||
// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo
|
||||
// that prints a warning when an uninteresting call occurs, and
|
||||
// StrictMock<MockFoo> is a subclass of MockFoo that treats all
|
||||
// uninteresting calls as errors.
|
||||
//
|
||||
// NiceMock and StrictMock "inherits" the constructors of their
|
||||
// respective base class, with up-to $n arguments. Therefore you can
|
||||
// write NiceMock<MockFoo>(5, "a") to construct a nice mock where
|
||||
// MockFoo has a constructor that accepts (int, const char*), for
|
||||
// example.
|
||||
// Currently a mock is naggy by default, so MockFoo and
|
||||
// NaggyMock<MockFoo> behave like the same. However, we will soon
|
||||
// switch the default behavior of mocks to be nice, as that in general
|
||||
// leads to more maintainable tests. When that happens, MockFoo will
|
||||
// stop behaving like NaggyMock<MockFoo> and start behaving like
|
||||
// NiceMock<MockFoo>.
|
||||
//
|
||||
// A known limitation is that NiceMock<MockFoo> and
|
||||
// StrictMock<MockFoo> only works for mock methods defined using the
|
||||
// MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. If a
|
||||
// mock method is defined in a base class of MockFoo, the "nice" or
|
||||
// "strict" modifier may not affect it, depending on the compiler. In
|
||||
// particular, nesting NiceMock and StrictMock is NOT supported.
|
||||
// NiceMock, NaggyMock, and StrictMock "inherit" the constructors of
|
||||
// their respective base class. Therefore you can write
|
||||
// NiceMock<MockFoo>(5, "a") to construct a nice mock where MockFoo
|
||||
// has a constructor that accepts (int, const char*), for example.
|
||||
//
|
||||
// Another known limitation is that the constructors of the base mock
|
||||
// cannot have arguments passed by non-const reference, which are
|
||||
// banned by the Google C++ style guide anyway.
|
||||
// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,
|
||||
// and StrictMock<MockFoo> only works for mock methods defined using
|
||||
// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.
|
||||
// If a mock method is defined in a base class of MockFoo, the "nice"
|
||||
// or "strict" modifier may not affect it, depending on the compiler.
|
||||
// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT
|
||||
// supported.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
|
||||
|
@ -67,21 +73,52 @@ $var n = 10 $$ The maximum arity we support.
|
|||
|
||||
namespace testing {
|
||||
|
||||
$range kind 0..2
|
||||
$for kind [[
|
||||
|
||||
$var clazz=[[$if kind==0 [[NiceMock]]
|
||||
$elif kind==1 [[NaggyMock]]
|
||||
$else [[StrictMock]]]]
|
||||
|
||||
$var method=[[$if kind==0 [[AllowUninterestingCalls]]
|
||||
$elif kind==1 [[WarnUninterestingCalls]]
|
||||
$else [[FailUninterestingCalls]]]]
|
||||
|
||||
template <class MockClass>
|
||||
class NiceMock : public MockClass {
|
||||
class $clazz : public MockClass {
|
||||
public:
|
||||
// We don't factor out the constructor body to a common method, as
|
||||
// we have to avoid a possible clash with members of MockClass.
|
||||
NiceMock() {
|
||||
::testing::Mock::AllowUninterestingCalls(
|
||||
$clazz() : MockClass() {
|
||||
::testing::Mock::$method(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
// C++ doesn't (yet) allow inheritance of constructors, so we have
|
||||
// to define it for each arity.
|
||||
#if GTEST_LANG_CXX11
|
||||
// Ideally, we would inherit base class's constructors through a using
|
||||
// declaration, which would preserve their visibility. However, many existing
|
||||
// tests rely on the fact that current implementation reexports protected
|
||||
// constructors as public. These tests would need to be cleaned up first.
|
||||
|
||||
// Single argument constructor is special-cased so that it can be
|
||||
// made explicit.
|
||||
template <typename A>
|
||||
explicit $clazz(A&& arg) : MockClass(std::forward<A>(arg)) {
|
||||
::testing::Mock::$method(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1, typename A2, typename... An>
|
||||
$clazz(A1&& arg1, A2&& arg2, An&&... args)
|
||||
: MockClass(std::forward<A1>(arg1), std::forward<A2>(arg2),
|
||||
std::forward<An>(args)...) {
|
||||
::testing::Mock::$method(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
#else
|
||||
// C++98 doesn't have variadic templates, so we have to define one
|
||||
// for each arity.
|
||||
template <typename A1>
|
||||
explicit NiceMock(const A1& a1) : MockClass(a1) {
|
||||
::testing::Mock::AllowUninterestingCalls(
|
||||
explicit $clazz(const A1& a1) : MockClass(a1) {
|
||||
::testing::Mock::$method(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
|
@ -89,70 +126,52 @@ $range i 2..n
|
|||
$for i [[
|
||||
$range j 1..i
|
||||
template <$for j, [[typename A$j]]>
|
||||
NiceMock($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) {
|
||||
::testing::Mock::AllowUninterestingCalls(
|
||||
$clazz($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) {
|
||||
::testing::Mock::$method(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
|
||||
]]
|
||||
virtual ~NiceMock() {
|
||||
#endif // GTEST_LANG_CXX11
|
||||
|
||||
~$clazz() {
|
||||
::testing::Mock::UnregisterCallReaction(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock);
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_($clazz);
|
||||
};
|
||||
|
||||
template <class MockClass>
|
||||
class StrictMock : public MockClass {
|
||||
public:
|
||||
// We don't factor out the constructor body to a common method, as
|
||||
// we have to avoid a possible clash with members of MockClass.
|
||||
StrictMock() {
|
||||
::testing::Mock::FailUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
template <typename A1>
|
||||
explicit StrictMock(const A1& a1) : MockClass(a1) {
|
||||
::testing::Mock::FailUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
$for i [[
|
||||
$range j 1..i
|
||||
template <$for j, [[typename A$j]]>
|
||||
StrictMock($for j, [[const A$j& a$j]]) : MockClass($for j, [[a$j]]) {
|
||||
::testing::Mock::FailUninterestingCalls(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
|
||||
]]
|
||||
virtual ~StrictMock() {
|
||||
::testing::Mock::UnregisterCallReaction(
|
||||
internal::ImplicitCast_<MockClass*>(this));
|
||||
}
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock);
|
||||
};
|
||||
|
||||
// The following specializations catch some (relatively more common)
|
||||
// user errors of nesting nice and strict mocks. They do NOT catch
|
||||
// all possible errors.
|
||||
|
||||
// These specializations are declared but not defined, as NiceMock and
|
||||
// StrictMock cannot be nested.
|
||||
// These specializations are declared but not defined, as NiceMock,
|
||||
// NaggyMock, and StrictMock cannot be nested.
|
||||
|
||||
template <typename MockClass>
|
||||
class NiceMock<NiceMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NiceMock<NaggyMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NiceMock<StrictMock<MockClass> >;
|
||||
|
||||
template <typename MockClass>
|
||||
class NaggyMock<NiceMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NaggyMock<NaggyMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class NaggyMock<StrictMock<MockClass> >;
|
||||
|
||||
template <typename MockClass>
|
||||
class StrictMock<NiceMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class StrictMock<NaggyMock<MockClass> >;
|
||||
template <typename MockClass>
|
||||
class StrictMock<StrictMock<MockClass> >;
|
||||
|
||||
} // namespace testing
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -26,13 +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)
|
||||
|
||||
|
||||
// Google Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file implements some actions that depend on gmock-generated-actions.h.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
|
||||
|
||||
|
@ -72,7 +73,7 @@ template <class Class, typename MethodPtr>
|
|||
class InvokeMethodAction {
|
||||
public:
|
||||
InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr)
|
||||
: obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
|
||||
: method_ptr_(method_ptr), obj_ptr_(obj_ptr) {}
|
||||
|
||||
template <typename Result, typename ArgumentTuple>
|
||||
Result Perform(const ArgumentTuple& args) const {
|
||||
|
@ -81,12 +82,29 @@ class InvokeMethodAction {
|
|||
}
|
||||
|
||||
private:
|
||||
Class* const obj_ptr_;
|
||||
// The order of these members matters. Reversing the order can trigger
|
||||
// warning C4121 in MSVC (see
|
||||
// http://computer-programming-forum.com/7-vc.net/6fbc30265f860ad1.htm ).
|
||||
const MethodPtr method_ptr_;
|
||||
Class* const obj_ptr_;
|
||||
|
||||
GTEST_DISALLOW_ASSIGN_(InvokeMethodAction);
|
||||
};
|
||||
|
||||
// An internal replacement for std::copy which mimics its behavior. This is
|
||||
// necessary because Visual Studio deprecates ::std::copy, issuing warning 4996.
|
||||
// However Visual Studio 2010 and later do not honor #pragmas which disable that
|
||||
// warning.
|
||||
template<typename InputIterator, typename OutputIterator>
|
||||
inline OutputIterator CopyElements(InputIterator first,
|
||||
InputIterator last,
|
||||
OutputIterator output) {
|
||||
for (; first != last; ++first, ++output) {
|
||||
*output = *first;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// Various overloads for Invoke().
|
||||
|
@ -144,7 +162,7 @@ WithArg(const InnerAction& action) {
|
|||
ACTION_TEMPLATE(ReturnArg,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_0_VALUE_PARAMS()) {
|
||||
return std::tr1::get<k>(args);
|
||||
return ::testing::get<k>(args);
|
||||
}
|
||||
|
||||
// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
|
||||
|
@ -152,7 +170,7 @@ ACTION_TEMPLATE(ReturnArg,
|
|||
ACTION_TEMPLATE(SaveArg,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_1_VALUE_PARAMS(pointer)) {
|
||||
*pointer = ::std::tr1::get<k>(args);
|
||||
*pointer = ::testing::get<k>(args);
|
||||
}
|
||||
|
||||
// Action SaveArgPointee<k>(pointer) saves the value pointed to
|
||||
|
@ -160,7 +178,7 @@ ACTION_TEMPLATE(SaveArg,
|
|||
ACTION_TEMPLATE(SaveArgPointee,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_1_VALUE_PARAMS(pointer)) {
|
||||
*pointer = *::std::tr1::get<k>(args);
|
||||
*pointer = *::testing::get<k>(args);
|
||||
}
|
||||
|
||||
// Action SetArgReferee<k>(value) assigns 'value' to the variable
|
||||
|
@ -168,13 +186,13 @@ ACTION_TEMPLATE(SaveArgPointee,
|
|||
ACTION_TEMPLATE(SetArgReferee,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_1_VALUE_PARAMS(value)) {
|
||||
typedef typename ::std::tr1::tuple_element<k, args_type>::type argk_type;
|
||||
typedef typename ::testing::tuple_element<k, args_type>::type argk_type;
|
||||
// Ensures that argument #k is a reference. If you get a compiler
|
||||
// error on the next line, you are using SetArgReferee<k>(value) in
|
||||
// a mock function whose k-th (0-based) argument is not a reference.
|
||||
GTEST_COMPILE_ASSERT_(internal::is_reference<argk_type>::value,
|
||||
SetArgReferee_must_be_used_with_a_reference_argument);
|
||||
::std::tr1::get<k>(args) = value;
|
||||
::testing::get<k>(args) = value;
|
||||
}
|
||||
|
||||
// Action SetArrayArgument<k>(first, last) copies the elements in
|
||||
|
@ -185,15 +203,11 @@ ACTION_TEMPLATE(SetArgReferee,
|
|||
ACTION_TEMPLATE(SetArrayArgument,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_2_VALUE_PARAMS(first, last)) {
|
||||
// Microsoft compiler deprecates ::std::copy, so we want to suppress warning
|
||||
// 4996 (Function call with parameters that may be unsafe) there.
|
||||
// Visual Studio deprecates ::std::copy, so we use our own copy in that case.
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push) // Saves the current warning state.
|
||||
# pragma warning(disable:4996) // Temporarily disables warning 4996.
|
||||
#endif
|
||||
::std::copy(first, last, ::std::tr1::get<k>(args));
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(pop) // Restores the warning state.
|
||||
internal::CopyElements(first, last, ::testing::get<k>(args));
|
||||
#else
|
||||
::std::copy(first, last, ::testing::get<k>(args));
|
||||
#endif
|
||||
}
|
||||
|
||||
|
@ -202,7 +216,7 @@ ACTION_TEMPLATE(SetArrayArgument,
|
|||
ACTION_TEMPLATE(DeleteArg,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_0_VALUE_PARAMS()) {
|
||||
delete ::std::tr1::get<k>(args);
|
||||
delete ::testing::get<k>(args);
|
||||
}
|
||||
|
||||
// This action returns the value pointed to by 'pointer'.
|
||||
|
|
|
@ -0,0 +1,92 @@
|
|||
// 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.
|
||||
|
||||
|
||||
// Google Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file implements some matchers that depend on gmock-generated-matchers.h.
|
||||
//
|
||||
// Note that tests are implemented in gmock-matchers_test.cc rather than
|
||||
// gmock-more-matchers-test.cc.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
|
||||
|
||||
#include "gmock/gmock-generated-matchers.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// Silence C4100 (unreferenced formal
|
||||
// parameter) for MSVC
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4100)
|
||||
#if (_MSC_VER == 1900)
|
||||
// and silence C4800 (C4800: 'int *const ': forcing value
|
||||
// to bool 'true' or 'false') for MSVC 14
|
||||
# pragma warning(disable:4800)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Defines a matcher that matches an empty container. The container must
|
||||
// support both size() and empty(), which all STL-like containers provide.
|
||||
MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") {
|
||||
if (arg.empty()) {
|
||||
return true;
|
||||
}
|
||||
*result_listener << "whose size is " << arg.size();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Define a matcher that matches a value that evaluates in boolean
|
||||
// context to true. Useful for types that define "explicit operator
|
||||
// bool" operators and so can't be compared for equality with true
|
||||
// and false.
|
||||
MATCHER(IsTrue, negation ? "is false" : "is true") {
|
||||
return static_cast<bool>(arg);
|
||||
}
|
||||
|
||||
// Define a matcher that matches a value that evaluates in boolean
|
||||
// context to false. Useful for types that define "explicit operator
|
||||
// bool" operators and so can't be compared for equality with true
|
||||
// and false.
|
||||
MATCHER(IsFalse, negation ? "is true" : "is false") {
|
||||
return !static_cast<bool>(arg);
|
||||
}
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#endif // GMOCK_INCLUDE_GMOCK_MORE_MATCHERS_H_
|
File diff suppressed because it is too large
Load Diff
|
@ -26,13 +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)
|
||||
|
||||
|
||||
// Google Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This is the main header file a user should include.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_GMOCK_H_
|
||||
|
||||
|
@ -60,9 +61,10 @@
|
|||
#include "gmock/gmock-generated-actions.h"
|
||||
#include "gmock/gmock-generated-function-mockers.h"
|
||||
#include "gmock/gmock-generated-matchers.h"
|
||||
#include "gmock/gmock-more-actions.h"
|
||||
#include "gmock/gmock-generated-nice-strict.h"
|
||||
#include "gmock/gmock-matchers.h"
|
||||
#include "gmock/gmock-more-actions.h"
|
||||
#include "gmock/gmock-more-matchers.h"
|
||||
#include "gmock/internal/gmock-internal-utils.h"
|
||||
|
||||
namespace testing {
|
||||
|
@ -70,6 +72,7 @@ namespace testing {
|
|||
// Declares Google Mock flags that we want a user to use programmatically.
|
||||
GMOCK_DECLARE_bool_(catch_leaked_mocks);
|
||||
GMOCK_DECLARE_string_(verbose);
|
||||
GMOCK_DECLARE_int32_(default_mock_behavior);
|
||||
|
||||
// Initializes Google Mock. This must be called before running the
|
||||
// tests. In particular, it parses the command line for the flags
|
||||
|
@ -82,11 +85,11 @@ GMOCK_DECLARE_string_(verbose);
|
|||
// Since Google Test is needed for Google Mock to work, this function
|
||||
// also initializes Google Test and parses its flags, if that hasn't
|
||||
// been done.
|
||||
void InitGoogleMock(int* argc, char** argv);
|
||||
GTEST_API_ void InitGoogleMock(int* argc, char** argv);
|
||||
|
||||
// This overloaded version can be used in Windows programs compiled in
|
||||
// UNICODE mode.
|
||||
void InitGoogleMock(int* argc, wchar_t** argv);
|
||||
GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);
|
||||
|
||||
} // namespace testing
|
||||
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
# Customization Points
|
||||
|
||||
The custom directory is an injection point for custom user configurations.
|
||||
|
||||
## Header `gmock-port.h`
|
||||
|
||||
The following macros can be defined:
|
||||
|
||||
### Flag related macros:
|
||||
|
||||
* `GMOCK_DECLARE_bool_(name)`
|
||||
* `GMOCK_DECLARE_int32_(name)`
|
||||
* `GMOCK_DECLARE_string_(name)`
|
||||
* `GMOCK_DEFINE_bool_(name, default_val, doc)`
|
||||
* `GMOCK_DEFINE_int32_(name, default_val, doc)`
|
||||
* `GMOCK_DEFINE_string_(name, default_val, doc)`
|
|
@ -0,0 +1,10 @@
|
|||
// This file was GENERATED by command:
|
||||
// pump.py gmock-generated-actions.h.pump
|
||||
// DO NOT EDIT BY HAND!!!
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
||||
|
||||
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
|
@ -0,0 +1,12 @@
|
|||
$$ -*- mode: c++; -*-
|
||||
$$ This is a Pump source file. Please use Pump to convert
|
||||
$$ it to callback-actions.h.
|
||||
$$
|
||||
$var max_callback_arity = 5
|
||||
$$}} This meta comment fixes auto-indentation in editors.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
||||
|
||||
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
|
|
@ -0,0 +1,36 @@
|
|||
// Copyright 2015, 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.
|
||||
//
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
|
||||
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_
|
|
@ -0,0 +1,39 @@
|
|||
// Copyright 2015, 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.
|
||||
//
|
||||
// Injection point for custom user configurations. See README for details
|
||||
//
|
||||
// ** Custom implementation starts here **
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
|
||||
|
||||
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
|
|
@ -1,4 +1,6 @@
|
|||
// This file was GENERATED by a script. DO NOT EDIT BY HAND!!!
|
||||
// This file was GENERATED by command:
|
||||
// pump.py gmock-generated-internal-utils.h.pump
|
||||
// DO NOT EDIT BY HAND!!!
|
||||
|
||||
// Copyright 2007, Google Inc.
|
||||
// All rights reserved.
|
||||
|
@ -28,14 +30,15 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file contains template meta-programming utility classes needed
|
||||
// for implementing Google Mock.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
|
||||
|
||||
|
@ -58,7 +61,7 @@ class IgnoredValue {
|
|||
// deliberately omit the 'explicit' keyword in order to allow the
|
||||
// conversion to be implicit.
|
||||
template <typename T>
|
||||
IgnoredValue(const T&) {}
|
||||
IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
|
||||
};
|
||||
|
||||
// MatcherTuple<T>::type is a tuple type where each field is a Matcher
|
||||
|
@ -67,72 +70,79 @@ template <typename Tuple>
|
|||
struct MatcherTuple;
|
||||
|
||||
template <>
|
||||
struct MatcherTuple< ::std::tr1::tuple<> > {
|
||||
typedef ::std::tr1::tuple< > type;
|
||||
struct MatcherTuple< ::testing::tuple<> > {
|
||||
typedef ::testing::tuple< > type;
|
||||
};
|
||||
|
||||
template <typename A1>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1> > {
|
||||
typedef ::testing::tuple<Matcher<A1> > type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2> > type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3, A4> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>,
|
||||
Matcher<A4> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4> >
|
||||
type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3, A4, A5> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5> >
|
||||
type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3, A4, A5, A6> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6> >
|
||||
type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7> >
|
||||
type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7, typename A8>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> >
|
||||
type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7, typename A8, typename A9>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type;
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > {
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>,
|
||||
Matcher<A9> >
|
||||
type;
|
||||
};
|
||||
|
||||
template <typename A1, typename A2, typename A3, typename A4, typename A5,
|
||||
typename A6, typename A7, typename A8, typename A9, typename A10>
|
||||
struct MatcherTuple< ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
|
||||
struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
|
||||
A10> > {
|
||||
typedef ::std::tr1::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>,
|
||||
Matcher<A10> > type;
|
||||
typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>,
|
||||
Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>,
|
||||
Matcher<A9>, Matcher<A10> >
|
||||
type;
|
||||
};
|
||||
|
||||
// Template struct Function<F>, where F must be a function type, contains
|
||||
|
@ -154,7 +164,7 @@ struct Function;
|
|||
template <typename R>
|
||||
struct Function<R()> {
|
||||
typedef R Result;
|
||||
typedef ::std::tr1::tuple<> ArgumentTuple;
|
||||
typedef ::testing::tuple<> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid();
|
||||
typedef IgnoredValue MakeResultIgnoredValue();
|
||||
|
@ -164,7 +174,7 @@ template <typename R, typename A1>
|
|||
struct Function<R(A1)>
|
||||
: Function<R()> {
|
||||
typedef A1 Argument1;
|
||||
typedef ::std::tr1::tuple<A1> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1);
|
||||
|
@ -174,7 +184,7 @@ template <typename R, typename A1, typename A2>
|
|||
struct Function<R(A1, A2)>
|
||||
: Function<R(A1)> {
|
||||
typedef A2 Argument2;
|
||||
typedef ::std::tr1::tuple<A1, A2> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2);
|
||||
|
@ -184,7 +194,7 @@ template <typename R, typename A1, typename A2, typename A3>
|
|||
struct Function<R(A1, A2, A3)>
|
||||
: Function<R(A1, A2)> {
|
||||
typedef A3 Argument3;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2, A3> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3);
|
||||
|
@ -194,7 +204,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4>
|
|||
struct Function<R(A1, A2, A3, A4)>
|
||||
: Function<R(A1, A2, A3)> {
|
||||
typedef A4 Argument4;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3, A4> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2, A3, A4> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3, A4);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4);
|
||||
|
@ -205,7 +215,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4,
|
|||
struct Function<R(A1, A2, A3, A4, A5)>
|
||||
: Function<R(A1, A2, A3, A4)> {
|
||||
typedef A5 Argument5;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3, A4, A5> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2, A3, A4, A5> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3, A4, A5);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5);
|
||||
|
@ -216,7 +226,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4,
|
|||
struct Function<R(A1, A2, A3, A4, A5, A6)>
|
||||
: Function<R(A1, A2, A3, A4, A5)> {
|
||||
typedef A6 Argument6;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6);
|
||||
|
@ -227,7 +237,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4,
|
|||
struct Function<R(A1, A2, A3, A4, A5, A6, A7)>
|
||||
: Function<R(A1, A2, A3, A4, A5, A6)> {
|
||||
typedef A7 Argument7;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7);
|
||||
|
@ -238,7 +248,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4,
|
|||
struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8)>
|
||||
: Function<R(A1, A2, A3, A4, A5, A6, A7)> {
|
||||
typedef A8 Argument8;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8);
|
||||
|
@ -249,7 +259,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4,
|
|||
struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)>
|
||||
: Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> {
|
||||
typedef A9 Argument9;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple;
|
||||
typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9);
|
||||
typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8,
|
||||
|
@ -262,7 +272,7 @@ template <typename R, typename A1, typename A2, typename A3, typename A4,
|
|||
struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)>
|
||||
: Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> {
|
||||
typedef A10 Argument10;
|
||||
typedef ::std::tr1::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
|
||||
typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9,
|
||||
A10> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
|
||||
|
|
|
@ -31,14 +31,15 @@ $var n = 10 $$ The maximum arity we support.
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file contains template meta-programming utility classes needed
|
||||
// for implementing Google Mock.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
|
||||
|
||||
|
@ -61,7 +62,7 @@ class IgnoredValue {
|
|||
// deliberately omit the 'explicit' keyword in order to allow the
|
||||
// conversion to be implicit.
|
||||
template <typename T>
|
||||
IgnoredValue(const T&) {}
|
||||
IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit)
|
||||
};
|
||||
|
||||
// MatcherTuple<T>::type is a tuple type where each field is a Matcher
|
||||
|
@ -77,8 +78,8 @@ $var typename_As = [[$for j, [[typename A$j]]]]
|
|||
$var As = [[$for j, [[A$j]]]]
|
||||
$var matcher_As = [[$for j, [[Matcher<A$j>]]]]
|
||||
template <$typename_As>
|
||||
struct MatcherTuple< ::std::tr1::tuple<$As> > {
|
||||
typedef ::std::tr1::tuple<$matcher_As > type;
|
||||
struct MatcherTuple< ::testing::tuple<$As> > {
|
||||
typedef ::testing::tuple<$matcher_As > type;
|
||||
};
|
||||
|
||||
|
||||
|
@ -102,7 +103,7 @@ struct Function;
|
|||
template <typename R>
|
||||
struct Function<R()> {
|
||||
typedef R Result;
|
||||
typedef ::std::tr1::tuple<> ArgumentTuple;
|
||||
typedef ::testing::tuple<> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid();
|
||||
typedef IgnoredValue MakeResultIgnoredValue();
|
||||
|
@ -121,7 +122,7 @@ template <typename R$typename_As>
|
|||
struct Function<R($As)>
|
||||
: Function<R($prev_As)> {
|
||||
typedef A$i Argument$i;
|
||||
typedef ::std::tr1::tuple<$As> ArgumentTuple;
|
||||
typedef ::testing::tuple<$As> ArgumentTuple;
|
||||
typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple;
|
||||
typedef void MakeResultVoid($As);
|
||||
typedef IgnoredValue MakeResultIgnoredValue($As);
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -35,13 +34,14 @@
|
|||
// Mock. They are subject to change without notice, so please DO NOT
|
||||
// USE THEM IN USER CODE.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
|
||||
|
||||
#include <stdio.h>
|
||||
#include <ostream> // NOLINT
|
||||
#include <string>
|
||||
|
||||
#include "gmock/internal/gmock-generated-internal-utils.h"
|
||||
#include "gmock/internal/gmock-port.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
@ -49,11 +49,23 @@
|
|||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// Silence MSVC C4100 (unreferenced formal parameter) and
|
||||
// C4805('==': unsafe mix of type 'const int' and type 'const bool')
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4100)
|
||||
# pragma warning(disable:4805)
|
||||
#endif
|
||||
|
||||
// Joins a vector of strings as if they are fields of a tuple; returns
|
||||
// the joined string.
|
||||
GTEST_API_ std::string JoinAsTuple(const Strings& fields);
|
||||
|
||||
// Converts an identifier name to a space-separated list of lower-case
|
||||
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
|
||||
// treated as one word. For example, both "FooBar123" and
|
||||
// "foo_bar_123" are converted to "foo bar 123".
|
||||
string ConvertIdentifierNameToWords(const char* id_name);
|
||||
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
|
||||
|
||||
// PointeeOf<Pointer>::type is the type of a value pointed to by a
|
||||
// Pointer, which can be either a smart pointer or a raw pointer. The
|
||||
|
@ -73,7 +85,7 @@ struct PointeeOf<T*> { typedef T type; }; // NOLINT
|
|||
// smart pointer, or returns p itself when p is already a raw pointer.
|
||||
// The following default implementation is for the smart pointer case.
|
||||
template <typename Pointer>
|
||||
inline typename Pointer::element_type* GetRawPointer(const Pointer& p) {
|
||||
inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
|
||||
return p.get();
|
||||
}
|
||||
// This overloaded version is for the raw pointer case.
|
||||
|
@ -114,9 +126,11 @@ struct LinkedPtrLessThan {
|
|||
// To gcc,
|
||||
// wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
|
||||
#ifdef __GNUC__
|
||||
#if !defined(__WCHAR_UNSIGNED__)
|
||||
// signed/unsigned wchar_t are valid types.
|
||||
# define GMOCK_HAS_SIGNED_WCHAR_T_ 1
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// In what follows, we use the term "kind" to indicate whether a type
|
||||
// is bool, an integer type (excluding bool), a floating-point type,
|
||||
|
@ -260,18 +274,18 @@ class FailureReporterInterface {
|
|||
public:
|
||||
// The type of a failure (either non-fatal or fatal).
|
||||
enum FailureType {
|
||||
NONFATAL, FATAL
|
||||
kNonfatal, kFatal
|
||||
};
|
||||
|
||||
virtual ~FailureReporterInterface() {}
|
||||
|
||||
// Reports a failure that occurred at the given source file location.
|
||||
virtual void ReportFailure(FailureType type, const char* file, int line,
|
||||
const string& message) = 0;
|
||||
const std::string& message) = 0;
|
||||
};
|
||||
|
||||
// Returns the failure reporter used by Google Mock.
|
||||
FailureReporterInterface* GetFailureReporter();
|
||||
GTEST_API_ FailureReporterInterface* GetFailureReporter();
|
||||
|
||||
// Asserts that condition is true; aborts the process with the given
|
||||
// message if condition is false. We cannot use LOG(FATAL) or CHECK()
|
||||
|
@ -279,9 +293,9 @@ FailureReporterInterface* GetFailureReporter();
|
|||
// inline this function to prevent it from showing up in the stack
|
||||
// trace.
|
||||
inline void Assert(bool condition, const char* file, int line,
|
||||
const string& msg) {
|
||||
const std::string& msg) {
|
||||
if (!condition) {
|
||||
GetFailureReporter()->ReportFailure(FailureReporterInterface::FATAL,
|
||||
GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
|
||||
file, line, msg);
|
||||
}
|
||||
}
|
||||
|
@ -292,9 +306,9 @@ inline void Assert(bool condition, const char* file, int line) {
|
|||
// Verifies that condition is true; generates a non-fatal failure if
|
||||
// condition is false.
|
||||
inline void Expect(bool condition, const char* file, int line,
|
||||
const string& msg) {
|
||||
const std::string& msg) {
|
||||
if (!condition) {
|
||||
GetFailureReporter()->ReportFailure(FailureReporterInterface::NONFATAL,
|
||||
GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
|
||||
file, line, msg);
|
||||
}
|
||||
}
|
||||
|
@ -304,8 +318,8 @@ inline void Expect(bool condition, const char* file, int line) {
|
|||
|
||||
// Severity level of a log.
|
||||
enum LogSeverity {
|
||||
INFO = 0,
|
||||
WARNING = 1
|
||||
kInfo = 0,
|
||||
kWarning = 1
|
||||
};
|
||||
|
||||
// Valid values for the --gmock_verbose flag.
|
||||
|
@ -319,7 +333,7 @@ const char kErrorVerbosity[] = "error";
|
|||
|
||||
// Returns true iff a log with the given severity is visible according
|
||||
// to the --gmock_verbose flag.
|
||||
bool LogIsVisible(LogSeverity severity);
|
||||
GTEST_API_ bool LogIsVisible(LogSeverity severity);
|
||||
|
||||
// Prints the given message to stdout iff 'severity' >= the level
|
||||
// specified by the --gmock_verbose flag. If stack_frames_to_skip >=
|
||||
|
@ -328,9 +342,25 @@ bool LogIsVisible(LogSeverity severity);
|
|||
// stack_frames_to_skip is treated as 0, since we don't know which
|
||||
// function calls will be inlined by the compiler and need to be
|
||||
// conservative.
|
||||
void Log(LogSeverity severity, const string& message, int stack_frames_to_skip);
|
||||
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
|
||||
int stack_frames_to_skip);
|
||||
|
||||
// TODO(wan@google.com): group all type utilities together.
|
||||
// A marker class that is used to resolve parameterless expectations to the
|
||||
// correct overload. This must not be instantiable, to prevent client code from
|
||||
// accidentally resolving to the overload; for example:
|
||||
//
|
||||
// ON_CALL(mock, Method({}, nullptr))...
|
||||
//
|
||||
class WithoutMatchers {
|
||||
private:
|
||||
WithoutMatchers() {}
|
||||
friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
|
||||
};
|
||||
|
||||
// Internal use only: access the singleton instance of WithoutMatchers.
|
||||
GTEST_API_ WithoutMatchers GetWithoutMatchers();
|
||||
|
||||
// FIXME: group all type utilities together.
|
||||
|
||||
// Type traits.
|
||||
|
||||
|
@ -346,16 +376,43 @@ template <typename T> struct type_equals<T, T> : public true_type {};
|
|||
template <typename T> struct remove_reference { typedef T type; }; // NOLINT
|
||||
template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
|
||||
|
||||
// Invalid<T>() returns an invalid value of type T. This is useful
|
||||
// DecayArray<T>::type turns an array type U[N] to const U* and preserves
|
||||
// other types. Useful for saving a copy of a function argument.
|
||||
template <typename T> struct DecayArray { typedef T type; }; // NOLINT
|
||||
template <typename T, size_t N> struct DecayArray<T[N]> {
|
||||
typedef const T* type;
|
||||
};
|
||||
// Sometimes people use arrays whose size is not available at the use site
|
||||
// (e.g. extern const char kNamePrefix[]). This specialization covers that
|
||||
// case.
|
||||
template <typename T> struct DecayArray<T[]> {
|
||||
typedef const T* type;
|
||||
};
|
||||
|
||||
// Disable MSVC warnings for infinite recursion, since in this case the
|
||||
// the recursion is unreachable.
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4717)
|
||||
#endif
|
||||
|
||||
// Invalid<T>() is usable as an expression of type T, but will terminate
|
||||
// the program with an assertion failure if actually run. This is useful
|
||||
// when a value of type T is needed for compilation, but the statement
|
||||
// will not really be executed (or we don't care if the statement
|
||||
// crashes).
|
||||
template <typename T>
|
||||
inline T Invalid() {
|
||||
return *static_cast<typename remove_reference<T>::type*>(NULL);
|
||||
Assert(false, "", -1, "Internal error: attempt to return invalid value");
|
||||
// This statement is unreachable, and would never terminate even if it
|
||||
// could be reached. It is provided only to placate compiler warnings
|
||||
// about missing return statements.
|
||||
return Invalid<T>();
|
||||
}
|
||||
template <>
|
||||
inline void Invalid<void>() {}
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
// Given a raw type (i.e. having no top-level reference or const
|
||||
// modifier) RawContainer that's either an STL-style container or a
|
||||
|
@ -418,16 +475,17 @@ class StlContainerView<Element[N]> {
|
|||
// ConstReference(const char * (&)[4])')
|
||||
// (and though the N parameter type is mismatched in the above explicit
|
||||
// conversion of it doesn't help - only the conversion of the array).
|
||||
return type(const_cast<Element*>(&array[0]), N, kReference);
|
||||
return type(const_cast<Element*>(&array[0]), N,
|
||||
RelationToSourceReference());
|
||||
#else
|
||||
return type(array, N, kReference);
|
||||
return type(array, N, RelationToSourceReference());
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
}
|
||||
static type Copy(const Element (&array)[N]) {
|
||||
#if GTEST_OS_SYMBIAN
|
||||
return type(const_cast<Element*>(&array[0]), N, kCopy);
|
||||
return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
|
||||
#else
|
||||
return type(array, N, kCopy);
|
||||
return type(array, N, RelationToSourceCopy());
|
||||
#endif // GTEST_OS_SYMBIAN
|
||||
}
|
||||
};
|
||||
|
@ -435,7 +493,7 @@ class StlContainerView<Element[N]> {
|
|||
// This specialization is used when RawContainer is a native array
|
||||
// represented as a (pointer, size) tuple.
|
||||
template <typename ElementPointer, typename Size>
|
||||
class StlContainerView< ::std::tr1::tuple<ElementPointer, Size> > {
|
||||
class StlContainerView< ::testing::tuple<ElementPointer, Size> > {
|
||||
public:
|
||||
typedef GTEST_REMOVE_CONST_(
|
||||
typename internal::PointeeOf<ElementPointer>::type) RawElement;
|
||||
|
@ -443,13 +501,11 @@ class StlContainerView< ::std::tr1::tuple<ElementPointer, Size> > {
|
|||
typedef const type const_reference;
|
||||
|
||||
static const_reference ConstReference(
|
||||
const ::std::tr1::tuple<ElementPointer, Size>& array) {
|
||||
using ::std::tr1::get;
|
||||
return type(get<0>(array), get<1>(array), kReference);
|
||||
const ::testing::tuple<ElementPointer, Size>& array) {
|
||||
return type(get<0>(array), get<1>(array), RelationToSourceReference());
|
||||
}
|
||||
static type Copy(const ::std::tr1::tuple<ElementPointer, Size>& array) {
|
||||
using ::std::tr1::get;
|
||||
return type(get<0>(array), get<1>(array), kCopy);
|
||||
static type Copy(const ::testing::tuple<ElementPointer, Size>& array) {
|
||||
return type(get<0>(array), get<1>(array), RelationToSourceCopy());
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -457,6 +513,62 @@ class StlContainerView< ::std::tr1::tuple<ElementPointer, Size> > {
|
|||
// StlContainer with a reference type.
|
||||
template <typename T> class StlContainerView<T&>;
|
||||
|
||||
// A type transform to remove constness from the first part of a pair.
|
||||
// Pairs like that are used as the value_type of associative containers,
|
||||
// and this transform produces a similar but assignable pair.
|
||||
template <typename T>
|
||||
struct RemoveConstFromKey {
|
||||
typedef T type;
|
||||
};
|
||||
|
||||
// Partially specialized to remove constness from std::pair<const K, V>.
|
||||
template <typename K, typename V>
|
||||
struct RemoveConstFromKey<std::pair<const K, V> > {
|
||||
typedef std::pair<K, V> type;
|
||||
};
|
||||
|
||||
// Mapping from booleans to types. Similar to boost::bool_<kValue> and
|
||||
// std::integral_constant<bool, kValue>.
|
||||
template <bool kValue>
|
||||
struct BooleanConstant {};
|
||||
|
||||
// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
|
||||
// reduce code size.
|
||||
GTEST_API_ void IllegalDoDefault(const char* file, int line);
|
||||
|
||||
#if GTEST_LANG_CXX11
|
||||
// Helper types for Apply() below.
|
||||
template <size_t... Is> struct int_pack { typedef int_pack type; };
|
||||
|
||||
template <class Pack, size_t I> struct append;
|
||||
template <size_t... Is, size_t I>
|
||||
struct append<int_pack<Is...>, I> : int_pack<Is..., I> {};
|
||||
|
||||
template <size_t C>
|
||||
struct make_int_pack : append<typename make_int_pack<C - 1>::type, C - 1> {};
|
||||
template <> struct make_int_pack<0> : int_pack<> {};
|
||||
|
||||
template <typename F, typename Tuple, size_t... Idx>
|
||||
auto ApplyImpl(F&& f, Tuple&& args, int_pack<Idx...>) -> decltype(
|
||||
std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
|
||||
return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
|
||||
}
|
||||
|
||||
// Apply the function to a tuple of arguments.
|
||||
template <typename F, typename Tuple>
|
||||
auto Apply(F&& f, Tuple&& args)
|
||||
-> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
|
||||
make_int_pack<std::tuple_size<Tuple>::value>())) {
|
||||
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
|
||||
make_int_pack<std::tuple_size<Tuple>::value>());
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
||||
|
|
|
@ -26,12 +26,16 @@
|
|||
// 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: vadimb@google.com (Vadim Berman)
|
||||
|
||||
//
|
||||
// Low-level types and utilities for porting Google Mock to various
|
||||
// platforms. They are subject to change without notice. DO NOT USE
|
||||
// THEM IN USER CODE.
|
||||
// platforms. All macros ending with _ and symbols defined in an
|
||||
// internal namespace are subject to change without notice. Code
|
||||
// outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't
|
||||
// end with _ are part of Google Mock's public API and can be used by
|
||||
// code outside Google Mock.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
|
||||
#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
|
||||
|
@ -40,15 +44,17 @@
|
|||
#include <stdlib.h>
|
||||
#include <iostream>
|
||||
|
||||
// Most of the types needed for porting Google Mock are also required
|
||||
// for Google Test and are defined in gtest-port.h.
|
||||
// Most of the utilities needed for porting Google Mock are also
|
||||
// required for Google Test and are defined in gtest-port.h.
|
||||
//
|
||||
// Note to maintainers: to reduce code duplication, prefer adding
|
||||
// portability utilities to Google Test's gtest-port.h instead of
|
||||
// here, as Google Mock depends on Google Test. Only add a utility
|
||||
// here if it's truly specific to Google Mock.
|
||||
|
||||
#include "gtest/internal/gtest-linked_ptr.h"
|
||||
#include "gtest/internal/gtest-port.h"
|
||||
|
||||
// To avoid conditional compilation everywhere, we make it
|
||||
// gmock-port.h's responsibility to #include the header implementing
|
||||
// tr1/tuple. gmock-port.h does this via gtest-port.h, which is
|
||||
// guaranteed to pull in the tuple header.
|
||||
#include "gmock/internal/custom/gmock-port.h"
|
||||
|
||||
// For MS Visual C++, check the compiler version. At least VS 2003 is
|
||||
// required to compile Google Mock.
|
||||
|
@ -60,19 +66,23 @@
|
|||
// use this syntax to reference Google Mock flags.
|
||||
#define GMOCK_FLAG(name) FLAGS_gmock_##name
|
||||
|
||||
#if !defined(GMOCK_DECLARE_bool_)
|
||||
|
||||
// Macros for declaring flags.
|
||||
#define GMOCK_DECLARE_bool_(name) extern bool GMOCK_FLAG(name)
|
||||
#define GMOCK_DECLARE_int32_(name) \
|
||||
extern ::testing::internal::Int32 GMOCK_FLAG(name)
|
||||
#define GMOCK_DECLARE_string_(name) \
|
||||
extern ::testing::internal::String GMOCK_FLAG(name)
|
||||
# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name)
|
||||
# define GMOCK_DECLARE_int32_(name) \
|
||||
extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name)
|
||||
# define GMOCK_DECLARE_string_(name) \
|
||||
extern GTEST_API_ ::std::string GMOCK_FLAG(name)
|
||||
|
||||
// Macros for defining flags.
|
||||
#define GMOCK_DEFINE_bool_(name, default_val, doc) \
|
||||
bool GMOCK_FLAG(name) = (default_val)
|
||||
#define GMOCK_DEFINE_int32_(name, default_val, doc) \
|
||||
::testing::internal::Int32 GMOCK_FLAG(name) = (default_val)
|
||||
#define GMOCK_DEFINE_string_(name, default_val, doc) \
|
||||
::testing::internal::String GMOCK_FLAG(name) = (default_val)
|
||||
# define GMOCK_DEFINE_bool_(name, default_val, doc) \
|
||||
GTEST_API_ bool GMOCK_FLAG(name) = (default_val)
|
||||
# define GMOCK_DEFINE_int32_(name, default_val, doc) \
|
||||
GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val)
|
||||
# define GMOCK_DEFINE_string_(name, default_val, doc) \
|
||||
GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val)
|
||||
|
||||
#endif // !defined(GMOCK_DECLARE_bool_)
|
||||
|
||||
#endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
|
||||
|
|
|
@ -17,7 +17,7 @@
|
|||
# Points to the root of Google Test, relative to where this file is.
|
||||
# Remember to tweak this if you move this file, or if you want to use
|
||||
# a copy of Google Test at a different location.
|
||||
GTEST_DIR = ../gtest
|
||||
GTEST_DIR = ../../googletest
|
||||
|
||||
# Points to the root of Google Mock, relative to where this file is.
|
||||
# Remember to tweak this if you move this file.
|
||||
|
@ -27,10 +27,13 @@ GMOCK_DIR = ..
|
|||
USER_DIR = ../test
|
||||
|
||||
# Flags passed to the preprocessor.
|
||||
CPPFLAGS += -I$(GTEST_DIR)/include -I$(GMOCK_DIR)/include
|
||||
# Set Google Test and Google Mock's header directories as system
|
||||
# directories, such that the compiler doesn't generate warnings in
|
||||
# these headers.
|
||||
CPPFLAGS += -isystem $(GTEST_DIR)/include -isystem $(GMOCK_DIR)/include
|
||||
|
||||
# Flags passed to the C++ compiler.
|
||||
CXXFLAGS += -g -Wall -Wextra
|
||||
CXXFLAGS += -g -Wall -Wextra -pthread
|
||||
|
||||
# All tests produced by this Makefile. Remember to add new tests you
|
||||
# created to the list.
|
||||
|
|
|
@ -10,6 +10,6 @@
|
|||
/>
|
||||
<UserMacro
|
||||
Name="GTestDir"
|
||||
Value="../../gtest"
|
||||
Value="../../../googletest"
|
||||
/>
|
||||
</VisualStudioPropertySheet>
|
||||
|
|
|
@ -10,21 +10,35 @@ EndProject
|
|||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Win32 = Debug|Win32
|
||||
Debug|x64 = Debug|x64
|
||||
Release|Win32 = Release|Win32
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.Build.0 = Debug|x64
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.ActiveCfg = Release|x64
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.Build.0 = Release|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.Build.0 = Debug|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.ActiveCfg = Release|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.Build.0 = Release|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.Build.0 = Debug|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.ActiveCfg = Release|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
|
@ -1,14 +1,22 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}</ProjectGuid>
|
||||
|
@ -20,10 +28,23 @@
|
|||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
|
@ -32,23 +53,39 @@
|
|||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
|
@ -58,10 +95,34 @@
|
|||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
|
@ -73,7 +134,9 @@
|
|||
<ClCompile Include="..\..\src\gmock-all.cc" />
|
||||
<ClCompile Include="$(GTestDir)\src\gtest-all.cc">
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="UserMacros">
|
||||
<GTestDir>../../gtest</GTestDir>
|
||||
<GTestDir>../../../googletest</GTestDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
|
|
|
@ -1,14 +1,22 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{E4EF614B-30DF-4954-8C53-580A0BF6B589}</ProjectGuid>
|
||||
|
@ -20,10 +28,23 @@
|
|||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
|
@ -32,23 +53,39 @@
|
|||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
|
@ -58,10 +95,34 @@
|
|||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
|
@ -79,7 +140,9 @@
|
|||
<ItemGroup>
|
||||
<ClCompile Include="..\..\src\gmock_main.cc">
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
|
|
|
@ -1,14 +1,22 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{F10D22F8-AC7B-4213-8720-608E7D878CD2}</ProjectGuid>
|
||||
|
@ -20,10 +28,23 @@
|
|||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v100</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
|
@ -32,26 +53,44 @@
|
|||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
|
@ -66,11 +105,29 @@
|
|||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
|
@ -85,6 +142,24 @@
|
|||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_VARIADIC_MAX=10;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="gmock_main.vcxproj">
|
||||
<Project>{e4ef614b-30df-4954-8c53-580a0bf6b589}</Project>
|
||||
|
|
|
@ -0,0 +1,46 @@
|
|||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 14
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock", "gmock.vcxproj", "{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_test", "gmock_test.vcxproj", "{F10D22F8-AC7B-4213-8720-608E7D878CD2}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "gmock_main", "gmock_main.vcxproj", "{E4EF614B-30DF-4954-8C53-580A0BF6B589}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Win32 = Debug|Win32
|
||||
Debug|x64 = Debug|x64
|
||||
Release|Win32 = Release|Win32
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Debug|x64.Build.0 = Debug|x64
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|Win32.Build.0 = Release|Win32
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.ActiveCfg = Release|x64
|
||||
{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}.Release|x64.Build.0 = Release|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Debug|x64.Build.0 = Debug|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|Win32.Build.0 = Release|Win32
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.ActiveCfg = Release|x64
|
||||
{F10D22F8-AC7B-4213-8720-608E7D878CD2}.Release|x64.Build.0 = Release|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Debug|x64.Build.0 = Debug|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|Win32.Build.0 = Release|Win32
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.ActiveCfg = Release|x64
|
||||
{E4EF614B-30DF-4954-8C53-580A0BF6B589}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
|
@ -0,0 +1,145 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{34681F0D-CE45-415D-B5F2-5C662DFE3BD5}</ProjectGuid>
|
||||
<RootNamespace>gmock</RootNamespace>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\..\src\gmock-all.cc" />
|
||||
<ClCompile Include="$(GTestDir)\src\gtest-all.cc">
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="UserMacros">
|
||||
<GTestDir>../../../googletest</GTestDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup>
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>$(GTestDir)/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<BuildMacro Include="GTestDir">
|
||||
<Value>$(GTestDir)</Value>
|
||||
</BuildMacro>
|
||||
</ItemGroup>
|
||||
</Project>
|
|
@ -0,0 +1,151 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{E4EF614B-30DF-4954-8C53-580A0BF6B589}</ProjectGuid>
|
||||
<RootNamespace>gmock_main</RootNamespace>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>StaticLibrary</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalIncludeDirectories>../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="gmock.vcxproj">
|
||||
<Project>{34681f0d-ce45-415d-b5f2-5c662dfe3bd5}</Project>
|
||||
<CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
|
||||
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\..\src\gmock_main.cc">
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release|x64'">../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
|
@ -0,0 +1,176 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{F10D22F8-AC7B-4213-8720-608E7D878CD2}</ProjectGuid>
|
||||
<RootNamespace>gmock_test</RootNamespace>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
<Import Project="gmock_config.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(OutDir)$(ProjectName)\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)-$(Configuration)\</OutDir>
|
||||
<IntDir>$(OutDir)$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalIncludeDirectories>..\..\include;..\..;$(GTestDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="gmock_main.vcxproj">
|
||||
<Project>{e4ef614b-30df-4954-8c53-580a0bf6b589}</Project>
|
||||
<CopyLocalSatelliteAssemblies>true</CopyLocalSatelliteAssemblies>
|
||||
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\..\test\gmock_all_test.cc" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
|
@ -36,8 +36,8 @@ SYNOPSIS
|
|||
fuse_gmock_files.py [GMOCK_ROOT_DIR] OUTPUT_DIR
|
||||
|
||||
Scans GMOCK_ROOT_DIR for Google Mock and Google Test source
|
||||
code, assuming Google Test is in the GMOCK_ROOT_DIR/gtest
|
||||
sub-directory, and generates three files:
|
||||
code, assuming Google Test is in the GMOCK_ROOT_DIR/../googletest
|
||||
directory, and generates three files:
|
||||
OUTPUT_DIR/gtest/gtest.h, OUTPUT_DIR/gmock/gmock.h, and
|
||||
OUTPUT_DIR/gmock-gtest-all.cc. Then you can build your tests
|
||||
by adding OUTPUT_DIR to the include search path and linking
|
||||
|
@ -55,7 +55,7 @@ EXAMPLES
|
|||
This tool is experimental. In particular, it assumes that there is no
|
||||
conditional inclusion of Google Mock or Google Test headers. Please
|
||||
report any problems to googlemock@googlegroups.com. You can read
|
||||
http://code.google.com/p/googlemock/wiki/CookBook for more
|
||||
https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md for more
|
||||
information.
|
||||
"""
|
||||
|
||||
|
@ -70,8 +70,8 @@ import sys
|
|||
# Mock root directory.
|
||||
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
|
||||
|
||||
# We need to call into gtest/scripts/fuse_gtest_files.py.
|
||||
sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, 'gtest/scripts'))
|
||||
# We need to call into googletest/scripts/fuse_gtest_files.py.
|
||||
sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, '../googletest/scripts'))
|
||||
import fuse_gtest_files
|
||||
gtest = fuse_gtest_files
|
||||
|
||||
|
@ -91,7 +91,7 @@ GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc'
|
|||
def GetGTestRootDir(gmock_root):
|
||||
"""Returns the root directory of Google Test."""
|
||||
|
||||
return os.path.join(gmock_root, 'gtest')
|
||||
return os.path.join(gmock_root, '../googletest')
|
||||
|
||||
|
||||
def ValidateGMockRootDir(gmock_root):
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
|
||||
The Google Mock class generator is an application that is part of cppclean.
|
||||
For more information about cppclean, see the README.cppclean file or
|
||||
visit http://code.google.com/p/cppclean/
|
||||
For more information about cppclean, visit http://code.google.com/p/cppclean/
|
||||
|
||||
cppclean requires Python 2.3.5 or later. If you don't have Python installed
|
||||
on your system, you will also need to install it. You can download Python
|
||||
from: http://www.python.org/download/releases/
|
||||
The mock generator requires Python 2.3.5 or later. If you don't have Python
|
||||
installed on your system, you will also need to install it. You can download
|
||||
Python from: http://www.python.org/download/releases/
|
||||
|
||||
To use the Google Mock class generator, you need to call it
|
||||
on the command line passing the header file and class for which you want
|
||||
|
|
|
@ -70,6 +70,7 @@ FUNCTION_DTOR = 0x10
|
|||
FUNCTION_ATTRIBUTE = 0x20
|
||||
FUNCTION_UNKNOWN_ANNOTATION = 0x40
|
||||
FUNCTION_THROW = 0x80
|
||||
FUNCTION_OVERRIDE = 0x100
|
||||
|
||||
"""
|
||||
These are currently unused. Should really handle these properly at some point.
|
||||
|
@ -337,7 +338,7 @@ class Class(_GenericDeclaration):
|
|||
# TODO(nnorwitz): handle namespaces, etc.
|
||||
if self.bases:
|
||||
for token_list in self.bases:
|
||||
# TODO(nnorwitz): bases are tokens, do name comparision.
|
||||
# TODO(nnorwitz): bases are tokens, do name comparison.
|
||||
for token in token_list:
|
||||
if token.name == node.name:
|
||||
return True
|
||||
|
@ -380,7 +381,7 @@ class Function(_GenericDeclaration):
|
|||
|
||||
def Requires(self, node):
|
||||
if self.parameters:
|
||||
# TODO(nnorwitz): parameters are tokens, do name comparision.
|
||||
# TODO(nnorwitz): parameters are tokens, do name comparison.
|
||||
for p in self.parameters:
|
||||
if p.name == node.name:
|
||||
return True
|
||||
|
@ -495,9 +496,10 @@ class TypeConverter(object):
|
|||
else:
|
||||
names.append(t.name)
|
||||
name = ''.join(names)
|
||||
result.append(Type(name_tokens[0].start, name_tokens[-1].end,
|
||||
name, templated_types, modifiers,
|
||||
reference, pointer, array))
|
||||
if name_tokens:
|
||||
result.append(Type(name_tokens[0].start, name_tokens[-1].end,
|
||||
name, templated_types, modifiers,
|
||||
reference, pointer, array))
|
||||
del name_tokens[:]
|
||||
|
||||
i = 0
|
||||
|
@ -597,10 +599,9 @@ class TypeConverter(object):
|
|||
first_token = None
|
||||
default = []
|
||||
|
||||
def AddParameter():
|
||||
def AddParameter(end):
|
||||
if default:
|
||||
del default[0] # Remove flag.
|
||||
end = type_modifiers[-1].end
|
||||
parts = self.DeclarationToParts(type_modifiers, True)
|
||||
(name, type_name, templated_types, modifiers,
|
||||
unused_default, unused_other_tokens) = parts
|
||||
|
@ -624,7 +625,7 @@ class TypeConverter(object):
|
|||
continue
|
||||
|
||||
if s.name == ',':
|
||||
AddParameter()
|
||||
AddParameter(s.start)
|
||||
name = type_name = ''
|
||||
type_modifiers = []
|
||||
pointer = reference = array = False
|
||||
|
@ -645,7 +646,7 @@ class TypeConverter(object):
|
|||
default.append(s)
|
||||
else:
|
||||
type_modifiers.append(s)
|
||||
AddParameter()
|
||||
AddParameter(tokens[-1].end)
|
||||
return result
|
||||
|
||||
def CreateReturnType(self, return_type_seq):
|
||||
|
@ -857,7 +858,7 @@ class AstBuilder(object):
|
|||
last_token = self._GetNextToken()
|
||||
return tokens, last_token
|
||||
|
||||
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necesary.
|
||||
# TODO(nnorwitz): remove _IgnoreUpTo() it shouldn't be necessary.
|
||||
def _IgnoreUpTo(self, token_type, token):
|
||||
unused_tokens = self._GetTokensUpTo(token_type, token)
|
||||
|
||||
|
@ -1027,6 +1028,8 @@ class AstBuilder(object):
|
|||
# Consume everything between the (parens).
|
||||
unused_tokens = list(self._GetMatchingChar('(', ')'))
|
||||
token = self._GetNextToken()
|
||||
elif modifier_token.name == 'override':
|
||||
modifiers |= FUNCTION_OVERRIDE
|
||||
elif modifier_token.name == modifier_token.name.upper():
|
||||
# HACK(nnorwitz): assume that all upper-case names
|
||||
# are some macro we aren't expanding.
|
||||
|
@ -1079,10 +1082,17 @@ class AstBuilder(object):
|
|||
body = None
|
||||
if token.name == '=':
|
||||
token = self._GetNextToken()
|
||||
assert token.token_type == tokenize.CONSTANT, token
|
||||
assert token.name == '0', token
|
||||
modifiers |= FUNCTION_PURE_VIRTUAL
|
||||
token = self._GetNextToken()
|
||||
|
||||
if token.name == 'default' or token.name == 'delete':
|
||||
# Ignore explicitly defaulted and deleted special members
|
||||
# in C++11.
|
||||
token = self._GetNextToken()
|
||||
else:
|
||||
# Handle pure-virtual declarations.
|
||||
assert token.token_type == tokenize.CONSTANT, token
|
||||
assert token.name == '0', token
|
||||
modifiers |= FUNCTION_PURE_VIRTUAL
|
||||
token = self._GetNextToken()
|
||||
|
||||
if token.name == '[':
|
||||
# TODO(nnorwitz): store tokens and improve parsing.
|
||||
|
@ -1254,6 +1264,9 @@ class AstBuilder(object):
|
|||
return self._GetNestedType(Union)
|
||||
|
||||
def handle_enum(self):
|
||||
token = self._GetNextToken()
|
||||
if not (token.token_type == tokenize.NAME and token.name == 'class'):
|
||||
self._AddBackToken(token)
|
||||
return self._GetNestedType(Enum)
|
||||
|
||||
def handle_auto(self):
|
||||
|
@ -1285,7 +1298,7 @@ class AstBuilder(object):
|
|||
if token2.token_type == tokenize.SYNTAX and token2.name == '~':
|
||||
return self.GetMethod(FUNCTION_VIRTUAL + FUNCTION_DTOR, None)
|
||||
assert token.token_type == tokenize.NAME or token.name == '::', token
|
||||
return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(')
|
||||
return_type_and_name = self._GetTokensUpTo(tokenize.SYNTAX, '(') # )
|
||||
return_type_and_name.insert(0, token)
|
||||
if token2 is not token:
|
||||
return_type_and_name.insert(1, token2)
|
||||
|
@ -1546,7 +1559,7 @@ class AstBuilder(object):
|
|||
self._AddBackToken(token)
|
||||
|
||||
return class_type(class_token.start, class_token.end, class_name,
|
||||
bases, None, body, self.namespace_stack)
|
||||
bases, templated_types, body, self.namespace_stack)
|
||||
|
||||
def handle_namespace(self):
|
||||
token = self._GetNextToken()
|
||||
|
|
|
@ -49,7 +49,8 @@ _INDENT = 2
|
|||
|
||||
|
||||
def _GenerateMethods(output_lines, source, class_node):
|
||||
function_type = ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL
|
||||
function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL |
|
||||
ast.FUNCTION_OVERRIDE)
|
||||
ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
|
||||
indent = ' ' * _INDENT
|
||||
|
||||
|
@ -82,20 +83,40 @@ def _GenerateMethods(output_lines, source, class_node):
|
|||
return_type += '*'
|
||||
if node.return_type.reference:
|
||||
return_type += '&'
|
||||
mock_method_macro = 'MOCK_%sMETHOD%d' % (const, len(node.parameters))
|
||||
num_parameters = len(node.parameters)
|
||||
if len(node.parameters) == 1:
|
||||
first_param = node.parameters[0]
|
||||
if source[first_param.start:first_param.end].strip() == 'void':
|
||||
# We must treat T(void) as a function with no parameters.
|
||||
num_parameters = 0
|
||||
tmpl = ''
|
||||
if class_node.templated_types:
|
||||
tmpl = '_T'
|
||||
mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl)
|
||||
|
||||
args = ''
|
||||
if node.parameters:
|
||||
# Get the full text of the parameters from the start
|
||||
# of the first parameter to the end of the last parameter.
|
||||
start = node.parameters[0].start
|
||||
end = node.parameters[-1].end
|
||||
# Remove // comments.
|
||||
args_strings = re.sub(r'//.*', '', source[start:end])
|
||||
# Condense multiple spaces and eliminate newlines putting the
|
||||
# parameters together on a single line. Ensure there is a
|
||||
# space in an argument which is split by a newline without
|
||||
# intervening whitespace, e.g.: int\nBar
|
||||
args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
|
||||
# Due to the parser limitations, it is impossible to keep comments
|
||||
# while stripping the default parameters. When defaults are
|
||||
# present, we choose to strip them and comments (and produce
|
||||
# compilable code).
|
||||
# TODO(nnorwitz@google.com): Investigate whether it is possible to
|
||||
# preserve parameter name when reconstructing parameter text from
|
||||
# the AST.
|
||||
if len([param for param in node.parameters if param.default]) > 0:
|
||||
args = ', '.join(param.type.name for param in node.parameters)
|
||||
else:
|
||||
# Get the full text of the parameters from the start
|
||||
# of the first parameter to the end of the last parameter.
|
||||
start = node.parameters[0].start
|
||||
end = node.parameters[-1].end
|
||||
# Remove // comments.
|
||||
args_strings = re.sub(r'//.*', '', source[start:end])
|
||||
# Condense multiple spaces and eliminate newlines putting the
|
||||
# parameters together on a single line. Ensure there is a
|
||||
# space in an argument which is split by a newline without
|
||||
# intervening whitespace, e.g.: int\nBar
|
||||
args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
|
||||
|
||||
# Create the mock method definition.
|
||||
output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
|
||||
|
@ -110,6 +131,7 @@ def _GenerateMocks(filename, source, ast_list, desired_class_names):
|
|||
# desired_class_names being None means that all classes are selected.
|
||||
(not desired_class_names or node.name in desired_class_names)):
|
||||
class_name = node.name
|
||||
parent_name = class_name
|
||||
processed_class_names.add(class_name)
|
||||
class_node = node
|
||||
# Add namespace before the class.
|
||||
|
@ -117,8 +139,21 @@ def _GenerateMocks(filename, source, ast_list, desired_class_names):
|
|||
lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
|
||||
lines.append('')
|
||||
|
||||
# Add template args for templated classes.
|
||||
if class_node.templated_types:
|
||||
# TODO(paulchang): The AST doesn't preserve template argument order,
|
||||
# so we have to make up names here.
|
||||
# TODO(paulchang): Handle non-type template arguments (e.g.
|
||||
# template<typename T, int N>).
|
||||
template_arg_count = len(class_node.templated_types.keys())
|
||||
template_args = ['T%d' % n for n in range(template_arg_count)]
|
||||
template_decls = ['typename ' + arg for arg in template_args]
|
||||
lines.append('template <' + ', '.join(template_decls) + '>')
|
||||
parent_name += '<' + ', '.join(template_args) + '>'
|
||||
|
||||
# Add the class prolog.
|
||||
lines.append('class Mock%s : public %s {' % (class_name, class_name)) # }
|
||||
lines.append('class Mock%s : public %s {' # }
|
||||
% (class_name, parent_name))
|
||||
lines.append('%spublic:' % (' ' * (_INDENT // 2)))
|
||||
|
||||
# Add all the methods.
|
||||
|
@ -182,7 +217,7 @@ def main(argv=sys.argv):
|
|||
return
|
||||
except:
|
||||
# An error message was already printed since we couldn't parse.
|
||||
pass
|
||||
sys.exit(1)
|
||||
else:
|
||||
lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
|
||||
sys.stdout.write('\n'.join(lines))
|
||||
|
|
|
@ -0,0 +1,466 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2009 Neal Norwitz All Rights Reserved.
|
||||
# Portions Copyright 2009 Google Inc. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Tests for gmock.scripts.generator.cpp.gmock_class."""
|
||||
|
||||
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
|
||||
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
# Allow the cpp imports below to work when run as a standalone script.
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from cpp import ast
|
||||
from cpp import gmock_class
|
||||
|
||||
|
||||
class TestCase(unittest.TestCase):
|
||||
"""Helper class that adds assert methods."""
|
||||
|
||||
def StripLeadingWhitespace(self, lines):
|
||||
"""Strip leading whitespace in each line in 'lines'."""
|
||||
return '\n'.join([s.lstrip() for s in lines.split('\n')])
|
||||
|
||||
def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines):
|
||||
"""Specialized assert that ignores the indent level."""
|
||||
self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines))
|
||||
|
||||
|
||||
class GenerateMethodsTest(TestCase):
|
||||
|
||||
def GenerateMethodSource(self, cpp_source):
|
||||
"""Convert C++ source to Google Mock output source lines."""
|
||||
method_source_lines = []
|
||||
# <test> is a pseudo-filename, it is not read or written.
|
||||
builder = ast.BuilderFromSource(cpp_source, '<test>')
|
||||
ast_list = list(builder.Generate())
|
||||
gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0])
|
||||
return '\n'.join(method_source_lines)
|
||||
|
||||
def testSimpleMethod(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual int Bar();
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0(Bar,\nint());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testSimpleConstructorsAndDestructor(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
Foo();
|
||||
Foo(int x);
|
||||
Foo(const Foo& f);
|
||||
Foo(Foo&& f);
|
||||
~Foo();
|
||||
virtual int Bar() = 0;
|
||||
};
|
||||
"""
|
||||
# The constructors and destructor should be ignored.
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0(Bar,\nint());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testVirtualDestructor(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual ~Foo();
|
||||
virtual int Bar() = 0;
|
||||
};
|
||||
"""
|
||||
# The destructor should be ignored.
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0(Bar,\nint());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testExplicitlyDefaultedConstructorsAndDestructor(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
Foo() = default;
|
||||
Foo(const Foo& f) = default;
|
||||
Foo(Foo&& f) = default;
|
||||
~Foo() = default;
|
||||
virtual int Bar() = 0;
|
||||
};
|
||||
"""
|
||||
# The constructors and destructor should be ignored.
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0(Bar,\nint());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testExplicitlyDeletedConstructorsAndDestructor(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
Foo() = delete;
|
||||
Foo(const Foo& f) = delete;
|
||||
Foo(Foo&& f) = delete;
|
||||
~Foo() = delete;
|
||||
virtual int Bar() = 0;
|
||||
};
|
||||
"""
|
||||
# The constructors and destructor should be ignored.
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0(Bar,\nint());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testSimpleOverrideMethod(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
int Bar() override;
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0(Bar,\nint());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testSimpleConstMethod(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual void Bar(bool flag) const;
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testExplicitVoid(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual int Bar(void);
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0(Bar,\nint(void));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testStrangeNewlineInParameter(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual void Bar(int
|
||||
a) = 0;
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD1(Bar,\nvoid(int a));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testDefaultParameters(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual void Bar(int a, char c = 'x') = 0;
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD2(Bar,\nvoid(int, char));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testMultipleDefaultParameters(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual void Bar(int a = 42, char c = 'x') = 0;
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD2(Bar,\nvoid(int, char));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testRemovesCommentsWhenDefaultsArePresent(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual void Bar(int a = 42 /* a comment */,
|
||||
char /* other comment */ c= 'x') = 0;
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD2(Bar,\nvoid(int, char));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testDoubleSlashCommentsInParameterListAreRemoved(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual void Bar(int a, // inline comments should be elided.
|
||||
int b // inline comments should be elided.
|
||||
) const = 0;
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testCStyleCommentsInParameterListAreNotRemoved(self):
|
||||
# NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these
|
||||
# comments. Also note that C style comments after the last parameter
|
||||
# are still elided.
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual const string& Bar(int /* keeper */, int b);
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD2(Bar,\nconst string&(int /* keeper */, int b));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testArgsOfTemplateTypes(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual int Bar(const vector<int>& v, map<int, string>* output);
|
||||
};"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD2(Bar,\n'
|
||||
'int(const vector<int>& v, map<int, string>* output));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testReturnTypeWithOneTemplateArg(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual vector<int>* Bar(int n);
|
||||
};"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD1(Bar,\nvector<int>*(int n));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testReturnTypeWithManyTemplateArgs(self):
|
||||
source = """
|
||||
class Foo {
|
||||
public:
|
||||
virtual map<int, string> Bar();
|
||||
};"""
|
||||
# Comparing the comment text is brittle - we'll think of something
|
||||
# better in case this gets annoying, but for now let's keep it simple.
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'// The following line won\'t really compile, as the return\n'
|
||||
'// type has multiple template arguments. To fix it, use a\n'
|
||||
'// typedef for the return type.\n'
|
||||
'MOCK_METHOD0(Bar,\nmap<int, string>());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testSimpleMethodInTemplatedClass(self):
|
||||
source = """
|
||||
template<class T>
|
||||
class Foo {
|
||||
public:
|
||||
virtual int Bar();
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD0_T(Bar,\nint());',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testPointerArgWithoutNames(self):
|
||||
source = """
|
||||
class Foo {
|
||||
virtual int Bar(C*);
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD1(Bar,\nint(C*));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testReferenceArgWithoutNames(self):
|
||||
source = """
|
||||
class Foo {
|
||||
virtual int Bar(C&);
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD1(Bar,\nint(C&));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
def testArrayArgWithoutNames(self):
|
||||
source = """
|
||||
class Foo {
|
||||
virtual int Bar(C[]);
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
'MOCK_METHOD1(Bar,\nint(C[]));',
|
||||
self.GenerateMethodSource(source))
|
||||
|
||||
|
||||
class GenerateMocksTest(TestCase):
|
||||
|
||||
def GenerateMocks(self, cpp_source):
|
||||
"""Convert C++ source to complete Google Mock output source."""
|
||||
# <test> is a pseudo-filename, it is not read or written.
|
||||
filename = '<test>'
|
||||
builder = ast.BuilderFromSource(cpp_source, filename)
|
||||
ast_list = list(builder.Generate())
|
||||
lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None)
|
||||
return '\n'.join(lines)
|
||||
|
||||
def testNamespaces(self):
|
||||
source = """
|
||||
namespace Foo {
|
||||
namespace Bar { class Forward; }
|
||||
namespace Baz {
|
||||
|
||||
class Test {
|
||||
public:
|
||||
virtual void Foo();
|
||||
};
|
||||
|
||||
} // namespace Baz
|
||||
} // namespace Foo
|
||||
"""
|
||||
expected = """\
|
||||
namespace Foo {
|
||||
namespace Baz {
|
||||
|
||||
class MockTest : public Test {
|
||||
public:
|
||||
MOCK_METHOD0(Foo,
|
||||
void());
|
||||
};
|
||||
|
||||
} // namespace Baz
|
||||
} // namespace Foo
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
expected, self.GenerateMocks(source))
|
||||
|
||||
def testClassWithStorageSpecifierMacro(self):
|
||||
source = """
|
||||
class STORAGE_SPECIFIER Test {
|
||||
public:
|
||||
virtual void Foo();
|
||||
};
|
||||
"""
|
||||
expected = """\
|
||||
class MockTest : public Test {
|
||||
public:
|
||||
MOCK_METHOD0(Foo,
|
||||
void());
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
expected, self.GenerateMocks(source))
|
||||
|
||||
def testTemplatedForwardDeclaration(self):
|
||||
source = """
|
||||
template <class T> class Forward; // Forward declaration should be ignored.
|
||||
class Test {
|
||||
public:
|
||||
virtual void Foo();
|
||||
};
|
||||
"""
|
||||
expected = """\
|
||||
class MockTest : public Test {
|
||||
public:
|
||||
MOCK_METHOD0(Foo,
|
||||
void());
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
expected, self.GenerateMocks(source))
|
||||
|
||||
def testTemplatedClass(self):
|
||||
source = """
|
||||
template <typename S, typename T>
|
||||
class Test {
|
||||
public:
|
||||
virtual void Foo();
|
||||
};
|
||||
"""
|
||||
expected = """\
|
||||
template <typename T0, typename T1>
|
||||
class MockTest : public Test<T0, T1> {
|
||||
public:
|
||||
MOCK_METHOD0_T(Foo,
|
||||
void());
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
expected, self.GenerateMocks(source))
|
||||
|
||||
def testTemplateInATemplateTypedef(self):
|
||||
source = """
|
||||
class Test {
|
||||
public:
|
||||
typedef std::vector<std::list<int>> FooType;
|
||||
virtual void Bar(const FooType& test_arg);
|
||||
};
|
||||
"""
|
||||
expected = """\
|
||||
class MockTest : public Test {
|
||||
public:
|
||||
MOCK_METHOD1(Bar,
|
||||
void(const FooType& test_arg));
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
expected, self.GenerateMocks(source))
|
||||
|
||||
def testTemplateInATemplateTypedefWithComma(self):
|
||||
source = """
|
||||
class Test {
|
||||
public:
|
||||
typedef std::function<void(
|
||||
const vector<std::list<int>>&, int> FooType;
|
||||
virtual void Bar(const FooType& test_arg);
|
||||
};
|
||||
"""
|
||||
expected = """\
|
||||
class MockTest : public Test {
|
||||
public:
|
||||
MOCK_METHOD1(Bar,
|
||||
void(const FooType& test_arg));
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
expected, self.GenerateMocks(source))
|
||||
|
||||
def testEnumClass(self):
|
||||
source = """
|
||||
class Test {
|
||||
public:
|
||||
enum class Baz { BAZINGA };
|
||||
virtual void Bar(const FooType& test_arg);
|
||||
};
|
||||
"""
|
||||
expected = """\
|
||||
class MockTest : public Test {
|
||||
public:
|
||||
MOCK_METHOD1(Bar,
|
||||
void(const FooType& test_arg));
|
||||
};
|
||||
"""
|
||||
self.assertEqualIgnoreLeadingWhitespace(
|
||||
expected, self.GenerateMocks(source))
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
|
@ -173,7 +173,7 @@ def GetTokens(source):
|
|||
token_type = SYNTAX
|
||||
i += 1
|
||||
new_ch = source[i]
|
||||
if new_ch == c:
|
||||
if new_ch == c and c != '>': # Treat ">>" as two tokens.
|
||||
i += 1
|
||||
elif c == '-' and new_ch == '>':
|
||||
i += 1
|
||||
|
|
|
@ -0,0 +1,640 @@
|
|||
#!/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.
|
||||
|
||||
"""Converts compiler's errors in code using Google Mock to plain English."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
_VERSION = '1.0.3'
|
||||
|
||||
_EMAIL = 'googlemock@googlegroups.com'
|
||||
|
||||
_COMMON_GMOCK_SYMBOLS = [
|
||||
# Matchers
|
||||
'_',
|
||||
'A',
|
||||
'AddressSatisfies',
|
||||
'AllOf',
|
||||
'An',
|
||||
'AnyOf',
|
||||
'ContainerEq',
|
||||
'Contains',
|
||||
'ContainsRegex',
|
||||
'DoubleEq',
|
||||
'ElementsAre',
|
||||
'ElementsAreArray',
|
||||
'EndsWith',
|
||||
'Eq',
|
||||
'Field',
|
||||
'FloatEq',
|
||||
'Ge',
|
||||
'Gt',
|
||||
'HasSubstr',
|
||||
'IsInitializedProto',
|
||||
'Le',
|
||||
'Lt',
|
||||
'MatcherCast',
|
||||
'Matches',
|
||||
'MatchesRegex',
|
||||
'NanSensitiveDoubleEq',
|
||||
'NanSensitiveFloatEq',
|
||||
'Ne',
|
||||
'Not',
|
||||
'NotNull',
|
||||
'Pointee',
|
||||
'Property',
|
||||
'Ref',
|
||||
'ResultOf',
|
||||
'SafeMatcherCast',
|
||||
'StartsWith',
|
||||
'StrCaseEq',
|
||||
'StrCaseNe',
|
||||
'StrEq',
|
||||
'StrNe',
|
||||
'Truly',
|
||||
'TypedEq',
|
||||
'Value',
|
||||
|
||||
# Actions
|
||||
'Assign',
|
||||
'ByRef',
|
||||
'DeleteArg',
|
||||
'DoAll',
|
||||
'DoDefault',
|
||||
'IgnoreResult',
|
||||
'Invoke',
|
||||
'InvokeArgument',
|
||||
'InvokeWithoutArgs',
|
||||
'Return',
|
||||
'ReturnNew',
|
||||
'ReturnNull',
|
||||
'ReturnRef',
|
||||
'SaveArg',
|
||||
'SetArgReferee',
|
||||
'SetArgPointee',
|
||||
'SetArgumentPointee',
|
||||
'SetArrayArgument',
|
||||
'SetErrnoAndReturn',
|
||||
'Throw',
|
||||
'WithArg',
|
||||
'WithArgs',
|
||||
'WithoutArgs',
|
||||
|
||||
# Cardinalities
|
||||
'AnyNumber',
|
||||
'AtLeast',
|
||||
'AtMost',
|
||||
'Between',
|
||||
'Exactly',
|
||||
|
||||
# Sequences
|
||||
'InSequence',
|
||||
'Sequence',
|
||||
|
||||
# Misc
|
||||
'DefaultValue',
|
||||
'Mock',
|
||||
]
|
||||
|
||||
# Regex for matching source file path and line number in the compiler's errors.
|
||||
_GCC_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(\d+:)?\s+'
|
||||
_CLANG_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(?P<column>\d+):\s+'
|
||||
_CLANG_NON_GMOCK_FILE_LINE_RE = (
|
||||
r'(?P<file>.*[/\\^](?!gmock-)[^/\\]+):(?P<line>\d+):(?P<column>\d+):\s+')
|
||||
|
||||
|
||||
def _FindAllMatches(regex, s):
|
||||
"""Generates all matches of regex in string s."""
|
||||
|
||||
r = re.compile(regex)
|
||||
return r.finditer(s)
|
||||
|
||||
|
||||
def _GenericDiagnoser(short_name, long_name, diagnoses, msg):
|
||||
"""Diagnoses the given disease by pattern matching.
|
||||
|
||||
Can provide different diagnoses for different patterns.
|
||||
|
||||
Args:
|
||||
short_name: Short name of the disease.
|
||||
long_name: Long name of the disease.
|
||||
diagnoses: A list of pairs (regex, pattern for formatting the diagnosis
|
||||
for matching regex).
|
||||
msg: Compiler's error messages.
|
||||
Yields:
|
||||
Tuples of the form
|
||||
(short name of disease, long name of disease, diagnosis).
|
||||
"""
|
||||
for regex, diagnosis in diagnoses:
|
||||
if re.search(regex, msg):
|
||||
diagnosis = '%(file)s:%(line)s:' + diagnosis
|
||||
for m in _FindAllMatches(regex, msg):
|
||||
yield (short_name, long_name, diagnosis % m.groupdict())
|
||||
|
||||
|
||||
def _NeedToReturnReferenceDiagnoser(msg):
|
||||
"""Diagnoses the NRR disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
|
||||
+ _GCC_FILE_LINE_RE + r'instantiated from here\n'
|
||||
r'.*gmock-actions\.h.*error: creating array with negative size')
|
||||
clang_regex = (r'error:.*array.*negative.*\r?\n'
|
||||
r'(.*\n)*?' +
|
||||
_CLANG_NON_GMOCK_FILE_LINE_RE +
|
||||
r'note: in instantiation of function template specialization '
|
||||
r'\'testing::internal::ReturnAction<(?P<type>.*)>'
|
||||
r'::operator Action<.*>\' requested here')
|
||||
clang11_re = (r'use_ReturnRef_instead_of_Return_to_return_a_reference.*'
|
||||
r'(.*\n)*?' + _CLANG_NON_GMOCK_FILE_LINE_RE)
|
||||
|
||||
diagnosis = """
|
||||
You are using a Return() action in a function that returns a reference to
|
||||
%(type)s. Please use ReturnRef() instead."""
|
||||
return _GenericDiagnoser('NRR', 'Need to Return Reference',
|
||||
[(clang_regex, diagnosis),
|
||||
(clang11_re, diagnosis % {'type': 'a type'}),
|
||||
(gcc_regex, diagnosis % {'type': 'a type'})],
|
||||
msg)
|
||||
|
||||
|
||||
def _NeedToReturnSomethingDiagnoser(msg):
|
||||
"""Diagnoses the NRS disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.'
|
||||
r'*gmock.*actions\.h.*error: void value not ignored)'
|
||||
r'|(error: control reaches end of non-void function)')
|
||||
clang_regex1 = (_CLANG_FILE_LINE_RE +
|
||||
r'error: cannot initialize return object '
|
||||
r'of type \'Result\' \(aka \'(?P<return_type>.*)\'\) '
|
||||
r'with an rvalue of type \'void\'')
|
||||
clang_regex2 = (_CLANG_FILE_LINE_RE +
|
||||
r'error: cannot initialize return object '
|
||||
r'of type \'(?P<return_type>.*)\' '
|
||||
r'with an rvalue of type \'void\'')
|
||||
diagnosis = """
|
||||
You are using an action that returns void, but it needs to return
|
||||
%(return_type)s. Please tell it *what* to return. Perhaps you can use
|
||||
the pattern DoAll(some_action, Return(some_value))?"""
|
||||
return _GenericDiagnoser(
|
||||
'NRS',
|
||||
'Need to Return Something',
|
||||
[(gcc_regex, diagnosis % {'return_type': '*something*'}),
|
||||
(clang_regex1, diagnosis),
|
||||
(clang_regex2, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
def _NeedToReturnNothingDiagnoser(msg):
|
||||
"""Diagnoses the NRN disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
|
||||
r'.*gmock-actions\.h.*error: instantiation of '
|
||||
r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
|
||||
r'as type \'void\'')
|
||||
clang_regex1 = (r'error: field has incomplete type '
|
||||
r'\'Result\' \(aka \'void\'\)(\r)?\n'
|
||||
r'(.*\n)*?' +
|
||||
_CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
|
||||
r'of function template specialization '
|
||||
r'\'testing::internal::ReturnAction<(?P<return_type>.*)>'
|
||||
r'::operator Action<void \(.*\)>\' requested here')
|
||||
clang_regex2 = (r'error: field has incomplete type '
|
||||
r'\'Result\' \(aka \'void\'\)(\r)?\n'
|
||||
r'(.*\n)*?' +
|
||||
_CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
|
||||
r'of function template specialization '
|
||||
r'\'testing::internal::DoBothAction<.*>'
|
||||
r'::operator Action<(?P<return_type>.*) \(.*\)>\' '
|
||||
r'requested here')
|
||||
diagnosis = """
|
||||
You are using an action that returns %(return_type)s, but it needs to return
|
||||
void. Please use a void-returning action instead.
|
||||
|
||||
All actions but the last in DoAll(...) must return void. Perhaps you need
|
||||
to re-arrange the order of actions in a DoAll(), if you are using one?"""
|
||||
return _GenericDiagnoser(
|
||||
'NRN',
|
||||
'Need to Return Nothing',
|
||||
[(gcc_regex, diagnosis % {'return_type': '*something*'}),
|
||||
(clang_regex1, diagnosis),
|
||||
(clang_regex2, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
def _IncompleteByReferenceArgumentDiagnoser(msg):
|
||||
"""Diagnoses the IBRA disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
|
||||
r'.*gtest-printers\.h.*error: invalid application of '
|
||||
r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
|
||||
|
||||
clang_regex = (r'.*gtest-printers\.h.*error: invalid application of '
|
||||
r'\'sizeof\' to an incomplete type '
|
||||
r'\'(?P<type>.*)( const)?\'\r?\n'
|
||||
r'(.*\n)*?' +
|
||||
_CLANG_NON_GMOCK_FILE_LINE_RE +
|
||||
r'note: in instantiation of member function '
|
||||
r'\'testing::internal2::TypeWithoutFormatter<.*>::'
|
||||
r'PrintValue\' requested here')
|
||||
diagnosis = """
|
||||
In order to mock this function, Google Mock needs to see the definition
|
||||
of type "%(type)s" - declaration alone is not enough. Either #include
|
||||
the header that defines it, or change the argument to be passed
|
||||
by pointer."""
|
||||
|
||||
return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
|
||||
[(gcc_regex, diagnosis),
|
||||
(clang_regex, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
def _OverloadedFunctionMatcherDiagnoser(msg):
|
||||
"""Diagnoses the OFM disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
|
||||
r'call to \'Truly\(<unresolved overloaded function type>\)')
|
||||
clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function for '
|
||||
r'call to \'Truly')
|
||||
diagnosis = """
|
||||
The argument you gave to Truly() is an overloaded function. Please tell
|
||||
your compiler which overloaded version you want to use.
|
||||
|
||||
For example, if you want to use the version whose signature is
|
||||
bool Foo(int n);
|
||||
you should write
|
||||
Truly(static_cast<bool (*)(int n)>(Foo))"""
|
||||
return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
|
||||
[(gcc_regex, diagnosis),
|
||||
(clang_regex, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
def _OverloadedFunctionActionDiagnoser(msg):
|
||||
"""Diagnoses the OFA disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to '
|
||||
r'\'Invoke\(<unresolved overloaded function type>')
|
||||
clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching '
|
||||
r'function for call to \'Invoke\'\r?\n'
|
||||
r'(.*\n)*?'
|
||||
r'.*\bgmock-generated-actions\.h:\d+:\d+:\s+'
|
||||
r'note: candidate template ignored:\s+'
|
||||
r'couldn\'t infer template argument \'FunctionImpl\'')
|
||||
diagnosis = """
|
||||
Function you are passing to Invoke is overloaded. Please tell your compiler
|
||||
which overloaded version you want to use.
|
||||
|
||||
For example, if you want to use the version whose signature is
|
||||
bool MyFunction(int n, double x);
|
||||
you should write something like
|
||||
Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
|
||||
return _GenericDiagnoser('OFA', 'Overloaded Function Action',
|
||||
[(gcc_regex, diagnosis),
|
||||
(clang_regex, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
def _OverloadedMethodActionDiagnoser(msg):
|
||||
"""Diagnoses the OMA disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
|
||||
r'call to \'Invoke\(.+, <unresolved overloaded function '
|
||||
r'type>\)')
|
||||
clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function '
|
||||
r'for call to \'Invoke\'\r?\n'
|
||||
r'(.*\n)*?'
|
||||
r'.*\bgmock-generated-actions\.h:\d+:\d+: '
|
||||
r'note: candidate function template not viable: '
|
||||
r'requires .*, but 2 (arguments )?were provided')
|
||||
diagnosis = """
|
||||
The second argument you gave to Invoke() is an overloaded method. Please
|
||||
tell your compiler which overloaded version you want to use.
|
||||
|
||||
For example, if you want to use the version whose signature is
|
||||
class Foo {
|
||||
...
|
||||
bool Bar(int n, double x);
|
||||
};
|
||||
you should write something like
|
||||
Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
|
||||
return _GenericDiagnoser('OMA', 'Overloaded Method Action',
|
||||
[(gcc_regex, diagnosis),
|
||||
(clang_regex, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
def _MockObjectPointerDiagnoser(msg):
|
||||
"""Diagnoses the MOP disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'error: request for member '
|
||||
r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
|
||||
r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
|
||||
clang_regex = (_CLANG_FILE_LINE_RE + r'error: member reference type '
|
||||
r'\'(?P<class_name>.*?) *\' is a pointer; '
|
||||
r'(did you mean|maybe you meant) to use \'->\'\?')
|
||||
diagnosis = """
|
||||
The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
|
||||
not a *pointer* to it. Please write '*(%(mock_object)s)' instead of
|
||||
'%(mock_object)s' as your first argument.
|
||||
|
||||
For example, given the mock class:
|
||||
|
||||
class %(class_name)s : public ... {
|
||||
...
|
||||
MOCK_METHOD0(%(method)s, ...);
|
||||
};
|
||||
|
||||
and the following mock instance:
|
||||
|
||||
%(class_name)s* mock_ptr = ...
|
||||
|
||||
you should use the EXPECT_CALL like this:
|
||||
|
||||
EXPECT_CALL(*mock_ptr, %(method)s(...));"""
|
||||
|
||||
return _GenericDiagnoser(
|
||||
'MOP',
|
||||
'Mock Object Pointer',
|
||||
[(gcc_regex, diagnosis),
|
||||
(clang_regex, diagnosis % {'mock_object': 'mock_object',
|
||||
'method': 'method',
|
||||
'class_name': '%(class_name)s'})],
|
||||
msg)
|
||||
|
||||
|
||||
def _NeedToUseSymbolDiagnoser(msg):
|
||||
"""Diagnoses the NUS disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
|
||||
r'(was not declared in this scope|has not been declared)')
|
||||
clang_regex = (_CLANG_FILE_LINE_RE +
|
||||
r'error: (use of undeclared identifier|unknown type name|'
|
||||
r'no template named) \'(?P<symbol>[^\']+)\'')
|
||||
diagnosis = """
|
||||
'%(symbol)s' is defined by Google Mock in the testing namespace.
|
||||
Did you forget to write
|
||||
using testing::%(symbol)s;
|
||||
?"""
|
||||
for m in (list(_FindAllMatches(gcc_regex, msg)) +
|
||||
list(_FindAllMatches(clang_regex, msg))):
|
||||
symbol = m.groupdict()['symbol']
|
||||
if symbol in _COMMON_GMOCK_SYMBOLS:
|
||||
yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())
|
||||
|
||||
|
||||
def _NeedToUseReturnNullDiagnoser(msg):
|
||||
"""Diagnoses the NRNULL disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = ('instantiated from \'testing::internal::ReturnAction<R>'
|
||||
'::operator testing::Action<Func>\(\) const.*\n' +
|
||||
_GCC_FILE_LINE_RE + r'instantiated from here\n'
|
||||
r'.*error: no matching function for call to \'ImplicitCast_\('
|
||||
r'(:?long )?int&\)')
|
||||
clang_regex = (r'\bgmock-actions.h:.* error: no matching function for '
|
||||
r'call to \'ImplicitCast_\'\r?\n'
|
||||
r'(.*\n)*?' +
|
||||
_CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
|
||||
r'of function template specialization '
|
||||
r'\'testing::internal::ReturnAction<(int|long)>::operator '
|
||||
r'Action<(?P<type>.*)\(\)>\' requested here')
|
||||
diagnosis = """
|
||||
You are probably calling Return(NULL) and the compiler isn't sure how to turn
|
||||
NULL into %(type)s. Use ReturnNull() instead.
|
||||
Note: the line number may be off; please fix all instances of Return(NULL)."""
|
||||
return _GenericDiagnoser(
|
||||
'NRNULL', 'Need to use ReturnNull',
|
||||
[(clang_regex, diagnosis),
|
||||
(gcc_regex, diagnosis % {'type': 'the right type'})],
|
||||
msg)
|
||||
|
||||
|
||||
def _TypeInTemplatedBaseDiagnoser(msg):
|
||||
"""Diagnoses the TTB disease, given the error messages by the compiler."""
|
||||
|
||||
# This version works when the type is used as the mock function's return
|
||||
# type.
|
||||
gcc_4_3_1_regex_type_in_retval = (
|
||||
r'In member function \'int .*\n' + _GCC_FILE_LINE_RE +
|
||||
r'error: a function call cannot appear in a constant-expression')
|
||||
gcc_4_4_0_regex_type_in_retval = (
|
||||
r'error: a function call cannot appear in a constant-expression'
|
||||
+ _GCC_FILE_LINE_RE + r'error: template argument 1 is invalid\n')
|
||||
# This version works when the type is used as the mock function's sole
|
||||
# parameter type.
|
||||
gcc_regex_type_of_sole_param = (
|
||||
_GCC_FILE_LINE_RE +
|
||||
r'error: \'(?P<type>.+)\' was not declared in this scope\n'
|
||||
r'.*error: template argument 1 is invalid\n')
|
||||
# This version works when the type is used as a parameter of a mock
|
||||
# function that has multiple parameters.
|
||||
gcc_regex_type_of_a_param = (
|
||||
r'error: expected `;\' before \'::\' token\n'
|
||||
+ _GCC_FILE_LINE_RE +
|
||||
r'error: \'(?P<type>.+)\' was not declared in this scope\n'
|
||||
r'.*error: template argument 1 is invalid\n'
|
||||
r'.*error: \'.+\' was not declared in this scope')
|
||||
clang_regex_type_of_retval_or_sole_param = (
|
||||
_CLANG_FILE_LINE_RE +
|
||||
r'error: use of undeclared identifier \'(?P<type>.*)\'\n'
|
||||
r'(.*\n)*?'
|
||||
r'(?P=file):(?P=line):\d+: error: '
|
||||
r'non-friend class member \'Result\' cannot have a qualified name'
|
||||
)
|
||||
clang_regex_type_of_a_param = (
|
||||
_CLANG_FILE_LINE_RE +
|
||||
r'error: C\+\+ requires a type specifier for all declarations\n'
|
||||
r'(.*\n)*?'
|
||||
r'(?P=file):(?P=line):(?P=column): error: '
|
||||
r'C\+\+ requires a type specifier for all declarations'
|
||||
)
|
||||
clang_regex_unknown_type = (
|
||||
_CLANG_FILE_LINE_RE +
|
||||
r'error: unknown type name \'(?P<type>[^\']+)\''
|
||||
)
|
||||
|
||||
diagnosis = """
|
||||
In a mock class template, types or typedefs defined in the base class
|
||||
template are *not* automatically visible. This is how C++ works. Before
|
||||
you can use a type or typedef named %(type)s defined in base class Base<T>, you
|
||||
need to make it visible. One way to do it is:
|
||||
|
||||
typedef typename Base<T>::%(type)s %(type)s;"""
|
||||
|
||||
for diag in _GenericDiagnoser(
|
||||
'TTB', 'Type in Template Base',
|
||||
[(gcc_4_3_1_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
|
||||
(gcc_4_4_0_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
|
||||
(gcc_regex_type_of_sole_param, diagnosis),
|
||||
(gcc_regex_type_of_a_param, diagnosis),
|
||||
(clang_regex_type_of_retval_or_sole_param, diagnosis),
|
||||
(clang_regex_type_of_a_param, diagnosis % {'type': 'Foo'})],
|
||||
msg):
|
||||
yield diag
|
||||
# Avoid overlap with the NUS pattern.
|
||||
for m in _FindAllMatches(clang_regex_unknown_type, msg):
|
||||
type_ = m.groupdict()['type']
|
||||
if type_ not in _COMMON_GMOCK_SYMBOLS:
|
||||
yield ('TTB', 'Type in Template Base', diagnosis % m.groupdict())
|
||||
|
||||
|
||||
def _WrongMockMethodMacroDiagnoser(msg):
|
||||
"""Diagnoses the WMM disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE +
|
||||
r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
|
||||
r'.*\n'
|
||||
r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
|
||||
clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
|
||||
r'error:.*array.*negative.*r?\n'
|
||||
r'(.*\n)*?'
|
||||
r'(?P=file):(?P=line):(?P=column): error: too few arguments '
|
||||
r'to function call, expected (?P<args>\d+), '
|
||||
r'have (?P<wrong_args>\d+)')
|
||||
clang11_re = (_CLANG_NON_GMOCK_FILE_LINE_RE +
|
||||
r'.*this_method_does_not_take_'
|
||||
r'(?P<wrong_args>\d+)_argument.*')
|
||||
diagnosis = """
|
||||
You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
|
||||
%(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
|
||||
MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
|
||||
return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
|
||||
[(gcc_regex, diagnosis),
|
||||
(clang11_re, diagnosis % {'wrong_args': 'm',
|
||||
'args': 'n'}),
|
||||
(clang_regex, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
def _WrongParenPositionDiagnoser(msg):
|
||||
"""Diagnoses the WPP disease, given the error messages by the compiler."""
|
||||
|
||||
gcc_regex = (_GCC_FILE_LINE_RE +
|
||||
r'error:.*testing::internal::MockSpec<.* has no member named \''
|
||||
r'(?P<method>\w+)\'')
|
||||
clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
|
||||
r'error: no member named \'(?P<method>\w+)\' in '
|
||||
r'\'testing::internal::MockSpec<.*>\'')
|
||||
diagnosis = """
|
||||
The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
|
||||
".%(method)s". For example, you should write:
|
||||
EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
|
||||
instead of:
|
||||
EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
|
||||
return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
|
||||
[(gcc_regex, diagnosis),
|
||||
(clang_regex, diagnosis)],
|
||||
msg)
|
||||
|
||||
|
||||
_DIAGNOSERS = [
|
||||
_IncompleteByReferenceArgumentDiagnoser,
|
||||
_MockObjectPointerDiagnoser,
|
||||
_NeedToReturnNothingDiagnoser,
|
||||
_NeedToReturnReferenceDiagnoser,
|
||||
_NeedToReturnSomethingDiagnoser,
|
||||
_NeedToUseReturnNullDiagnoser,
|
||||
_NeedToUseSymbolDiagnoser,
|
||||
_OverloadedFunctionActionDiagnoser,
|
||||
_OverloadedFunctionMatcherDiagnoser,
|
||||
_OverloadedMethodActionDiagnoser,
|
||||
_TypeInTemplatedBaseDiagnoser,
|
||||
_WrongMockMethodMacroDiagnoser,
|
||||
_WrongParenPositionDiagnoser,
|
||||
]
|
||||
|
||||
|
||||
def Diagnose(msg):
|
||||
"""Generates all possible diagnoses given the compiler error message."""
|
||||
|
||||
msg = re.sub(r'\x1b\[[^m]*m', '', msg) # Strips all color formatting.
|
||||
# Assuming the string is using the UTF-8 encoding, replaces the left and
|
||||
# the right single quote characters with apostrophes.
|
||||
msg = re.sub(r'(\xe2\x80\x98|\xe2\x80\x99)', "'", msg)
|
||||
|
||||
diagnoses = []
|
||||
for diagnoser in _DIAGNOSERS:
|
||||
for diag in diagnoser(msg):
|
||||
diagnosis = '[%s - %s]\n%s' % diag
|
||||
if not diagnosis in diagnoses:
|
||||
diagnoses.append(diagnosis)
|
||||
return diagnoses
|
||||
|
||||
|
||||
def main():
|
||||
print ('Google Mock Doctor v%s - '
|
||||
'diagnoses problems in code using Google Mock.' % _VERSION)
|
||||
|
||||
if sys.stdin.isatty():
|
||||
print ('Please copy and paste the compiler errors here. Press c-D when '
|
||||
'you are done:')
|
||||
else:
|
||||
print ('Waiting for compiler errors on stdin . . .')
|
||||
|
||||
msg = sys.stdin.read().strip()
|
||||
diagnoses = Diagnose(msg)
|
||||
count = len(diagnoses)
|
||||
if not count:
|
||||
print ("""
|
||||
Your compiler complained:
|
||||
8<------------------------------------------------------------
|
||||
%s
|
||||
------------------------------------------------------------>8
|
||||
|
||||
Uh-oh, I'm not smart enough to figure out what the problem is. :-(
|
||||
However...
|
||||
If you send your source code and the compiler's error messages to
|
||||
%s, you can be helped and I can get smarter --
|
||||
win-win for us!""" % (msg, _EMAIL))
|
||||
else:
|
||||
print ('------------------------------------------------------------')
|
||||
print ('Your code appears to have the following',)
|
||||
if count > 1:
|
||||
print ('%s diseases:' % (count,))
|
||||
else:
|
||||
print ('disease:')
|
||||
i = 0
|
||||
for d in diagnoses:
|
||||
i += 1
|
||||
if count > 1:
|
||||
print ('\n#%s:' % (i,))
|
||||
print (d)
|
||||
print ("""
|
||||
How did I do? If you think I'm wrong or unhelpful, please send your
|
||||
source code and the compiler's error messages to %s.
|
||||
Then you can be helped and I can get smarter -- I promise I won't be upset!""" %
|
||||
_EMAIL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,78 @@
|
|||
#!/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_gmock.py v0.1.0 -- uploads a Google Mock patch for review.
|
||||
|
||||
This simple wrapper passes all command line flags and
|
||||
--cc=googlemock@googlegroups.com to upload.py.
|
||||
|
||||
USAGE: upload_gmock.py [options for upload.py]
|
||||
"""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
CC_FLAG = '--cc='
|
||||
GMOCK_GROUP = 'googlemock@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 Mock 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 GMOCK_GROUP not in cc_list:
|
||||
cc_list.append(GMOCK_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 + GMOCK_GROUP)
|
||||
|
||||
# Invokes upload.py with the modified command line flags.
|
||||
os.execv(upload_py_path, upload_py_argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
|
@ -26,8 +26,7 @@
|
|||
// 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++ Mocking Framework (Google Mock)
|
||||
//
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -75,7 +74,7 @@ class BetweenCardinalityImpl : public CardinalityInterface {
|
|||
virtual int ConservativeUpperBound() const { return max_; }
|
||||
|
||||
virtual bool IsSatisfiedByCallCount(int call_count) const {
|
||||
return min_ <= call_count && call_count <= max_ ;
|
||||
return min_ <= call_count && call_count <= max_;
|
||||
}
|
||||
|
||||
virtual bool IsSaturatedByCallCount(int call_count) const {
|
||||
|
@ -83,6 +82,7 @@ class BetweenCardinalityImpl : public CardinalityInterface {
|
|||
}
|
||||
|
||||
virtual void DescribeTo(::std::ostream* os) const;
|
||||
|
||||
private:
|
||||
const int min_;
|
||||
const int max_;
|
||||
|
@ -91,7 +91,7 @@ class BetweenCardinalityImpl : public CardinalityInterface {
|
|||
};
|
||||
|
||||
// Formats "n times" in a human-friendly way.
|
||||
inline internal::string FormatTimes(int n) {
|
||||
inline std::string FormatTimes(int n) {
|
||||
if (n == 1) {
|
||||
return "once";
|
||||
} else if (n == 2) {
|
||||
|
@ -136,20 +136,20 @@ void Cardinality::DescribeActualCallCountTo(int actual_call_count,
|
|||
}
|
||||
|
||||
// Creates a cardinality that allows at least n calls.
|
||||
Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
|
||||
GTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }
|
||||
|
||||
// Creates a cardinality that allows at most n calls.
|
||||
Cardinality AtMost(int n) { return Between(0, n); }
|
||||
GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }
|
||||
|
||||
// Creates a cardinality that allows any number of calls.
|
||||
Cardinality AnyNumber() { return AtLeast(0); }
|
||||
GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }
|
||||
|
||||
// Creates a cardinality that allows between min and max calls.
|
||||
Cardinality Between(int min, int max) {
|
||||
GTEST_API_ Cardinality Between(int min, int max) {
|
||||
return Cardinality(new BetweenCardinalityImpl(min, max));
|
||||
}
|
||||
|
||||
// Creates a cardinality that allows exactly n calls.
|
||||
Cardinality Exactly(int n) { return Between(n, n); }
|
||||
GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }
|
||||
|
||||
} // namespace testing
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -47,12 +46,31 @@
|
|||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// Joins a vector of strings as if they are fields of a tuple; returns
|
||||
// the joined string.
|
||||
GTEST_API_ std::string JoinAsTuple(const Strings& fields) {
|
||||
switch (fields.size()) {
|
||||
case 0:
|
||||
return "";
|
||||
case 1:
|
||||
return fields[0];
|
||||
default:
|
||||
std::string result = "(" + fields[0];
|
||||
for (size_t i = 1; i < fields.size(); i++) {
|
||||
result += ", ";
|
||||
result += fields[i];
|
||||
}
|
||||
result += ")";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// Converts an identifier name to a space-separated list of lower-case
|
||||
// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
|
||||
// treated as one word. For example, both "FooBar123" and
|
||||
// "foo_bar_123" are converted to "foo bar 123".
|
||||
string ConvertIdentifierNameToWords(const char* id_name) {
|
||||
string result;
|
||||
GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {
|
||||
std::string result;
|
||||
char prev_char = '\0';
|
||||
for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) {
|
||||
// We don't care about the current locale as the input is
|
||||
|
@ -71,19 +89,19 @@ string ConvertIdentifierNameToWords(const char* id_name) {
|
|||
}
|
||||
|
||||
// This class reports Google Mock failures as Google Test failures. A
|
||||
// user can define another class in a similar fashion if he intends to
|
||||
// user can define another class in a similar fashion if they intend to
|
||||
// use Google Mock with a testing framework other than Google Test.
|
||||
class GoogleTestFailureReporter : public FailureReporterInterface {
|
||||
public:
|
||||
virtual void ReportFailure(FailureType type, const char* file, int line,
|
||||
const string& message) {
|
||||
AssertHelper(type == FATAL ?
|
||||
const std::string& message) {
|
||||
AssertHelper(type == kFatal ?
|
||||
TestPartResult::kFatalFailure :
|
||||
TestPartResult::kNonFatalFailure,
|
||||
file,
|
||||
line,
|
||||
message.c_str()) = Message();
|
||||
if (type == FATAL) {
|
||||
if (type == kFatal) {
|
||||
posix::Abort();
|
||||
}
|
||||
}
|
||||
|
@ -91,7 +109,7 @@ class GoogleTestFailureReporter : public FailureReporterInterface {
|
|||
|
||||
// Returns the global failure reporter. Will create a
|
||||
// GoogleTestFailureReporter and return it the first time called.
|
||||
FailureReporterInterface* GetFailureReporter() {
|
||||
GTEST_API_ FailureReporterInterface* GetFailureReporter() {
|
||||
// Points to the global failure reporter used by Google Mock. gcc
|
||||
// guarantees that the following use of failure_reporter is
|
||||
// thread-safe. We may need to add additional synchronization to
|
||||
|
@ -107,7 +125,7 @@ static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);
|
|||
|
||||
// Returns true iff a log with the given severity is visible according
|
||||
// to the --gmock_verbose flag.
|
||||
bool LogIsVisible(LogSeverity severity) {
|
||||
GTEST_API_ bool LogIsVisible(LogSeverity severity) {
|
||||
if (GMOCK_FLAG(verbose) == kInfoVerbosity) {
|
||||
// Always show the log if --gmock_verbose=info.
|
||||
return true;
|
||||
|
@ -117,7 +135,7 @@ bool LogIsVisible(LogSeverity severity) {
|
|||
} else {
|
||||
// If --gmock_verbose is neither "info" nor "error", we treat it
|
||||
// as "warning" (its default value).
|
||||
return severity == WARNING;
|
||||
return severity == kWarning;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -128,8 +146,8 @@ bool LogIsVisible(LogSeverity severity) {
|
|||
// stack_frames_to_skip is treated as 0, since we don't know which
|
||||
// function calls will be inlined by the compiler and need to be
|
||||
// conservative.
|
||||
void Log(LogSeverity severity, const string& message,
|
||||
int stack_frames_to_skip) {
|
||||
GTEST_API_ void Log(LogSeverity severity, const std::string& message,
|
||||
int stack_frames_to_skip) {
|
||||
if (!LogIsVisible(severity))
|
||||
return;
|
||||
|
||||
|
@ -139,7 +157,7 @@ void Log(LogSeverity severity, const string& message,
|
|||
// "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a
|
||||
// macro.
|
||||
|
||||
if (severity == WARNING) {
|
||||
if (severity == kWarning) {
|
||||
// Prints a GMOCK WARNING marker to make the warnings easily searchable.
|
||||
std::cout << "\nGMOCK WARNING:";
|
||||
}
|
||||
|
@ -169,5 +187,17 @@ void Log(LogSeverity severity, const string& message,
|
|||
std::cout << ::std::flush;
|
||||
}
|
||||
|
||||
GTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }
|
||||
|
||||
GTEST_API_ void IllegalDoDefault(const char* file, int line) {
|
||||
internal::Assert(
|
||||
false, file, line,
|
||||
"You are using DoDefault() inside a composite action like "
|
||||
"DoAll() or WithArgs(). This is not supported for technical "
|
||||
"reasons. Please instead spell out the default action, or "
|
||||
"assign the default action to an Action variable and use "
|
||||
"the variable in various places.");
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -38,64 +37,536 @@
|
|||
#include "gmock/gmock-generated-matchers.h"
|
||||
|
||||
#include <string.h>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
namespace testing {
|
||||
|
||||
// Constructs a matcher that matches a const string& whose value is
|
||||
// Constructs a matcher that matches a const std::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const internal::string&>::Matcher(const internal::string& s) {
|
||||
Matcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
#if GTEST_HAS_GLOBAL_STRING
|
||||
// Constructs a matcher that matches a const std::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const std::string&>::Matcher(const ::string& s) {
|
||||
*this = Eq(static_cast<std::string>(s));
|
||||
}
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
// 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); }
|
||||
|
||||
#if GTEST_HAS_GLOBAL_STRING
|
||||
// Constructs a matcher that matches a std::string whose value is equal to
|
||||
// s.
|
||||
Matcher<std::string>::Matcher(const ::string& s) {
|
||||
*this = Eq(static_cast<std::string>(s));
|
||||
}
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
// 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_HAS_GLOBAL_STRING
|
||||
// Constructs a matcher that matches a const ::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const ::string&>::Matcher(const std::string& s) {
|
||||
*this = Eq(static_cast<::string>(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a const ::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const ::string&>::Matcher(const ::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a const ::string& whose value is
|
||||
// equal to s.
|
||||
Matcher<const ::string&>::Matcher(const char* s) { *this = Eq(::string(s)); }
|
||||
|
||||
// Constructs a matcher that matches a ::string whose value is equal to s.
|
||||
Matcher<::string>::Matcher(const std::string& s) {
|
||||
*this = Eq(static_cast<::string>(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a ::string whose value is equal to s.
|
||||
Matcher<::string>::Matcher(const ::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a string whose value is equal to s.
|
||||
Matcher<::string>::Matcher(const char* s) { *this = Eq(::string(s)); }
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
#if GTEST_HAS_ABSL
|
||||
// Constructs a matcher that matches a const absl::string_view& whose value is
|
||||
// equal to s.
|
||||
Matcher<const absl::string_view&>::Matcher(const std::string& s) {
|
||||
*this = Eq(s);
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a const string& whose value is
|
||||
#if GTEST_HAS_GLOBAL_STRING
|
||||
// Constructs a matcher that matches a const absl::string_view& whose value is
|
||||
// equal to s.
|
||||
Matcher<const internal::string&>::Matcher(const char* s) {
|
||||
*this = Eq(internal::string(s));
|
||||
Matcher<const absl::string_view&>::Matcher(const ::string& s) { *this = Eq(s); }
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
// Constructs a matcher that matches a const absl::string_view& whose value is
|
||||
// equal to s.
|
||||
Matcher<const absl::string_view&>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a string whose value is equal to s.
|
||||
Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); }
|
||||
|
||||
// Constructs a matcher that matches a string whose value is equal to s.
|
||||
Matcher<internal::string>::Matcher(const char* s) {
|
||||
*this = Eq(internal::string(s));
|
||||
// Constructs a matcher that matches a const absl::string_view& whose value is
|
||||
// equal to s.
|
||||
Matcher<const absl::string_view&>::Matcher(absl::string_view s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a absl::string_view whose value is equal to
|
||||
// s.
|
||||
Matcher<absl::string_view>::Matcher(const std::string& s) { *this = Eq(s); }
|
||||
|
||||
#if GTEST_HAS_GLOBAL_STRING
|
||||
// Constructs a matcher that matches a absl::string_view whose value is equal to
|
||||
// s.
|
||||
Matcher<absl::string_view>::Matcher(const ::string& s) { *this = Eq(s); }
|
||||
#endif // GTEST_HAS_GLOBAL_STRING
|
||||
|
||||
// Constructs a matcher that matches a absl::string_view whose value is equal to
|
||||
// s.
|
||||
Matcher<absl::string_view>::Matcher(const char* s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
|
||||
// Constructs a matcher that matches a absl::string_view whose value is equal to
|
||||
// s.
|
||||
Matcher<absl::string_view>::Matcher(absl::string_view s) {
|
||||
*this = Eq(std::string(s));
|
||||
}
|
||||
#endif // GTEST_HAS_ABSL
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Joins a vector of strings as if they are fields of a tuple; returns
|
||||
// the joined string.
|
||||
string JoinAsTuple(const Strings& fields) {
|
||||
switch (fields.size()) {
|
||||
case 0:
|
||||
return "";
|
||||
case 1:
|
||||
return fields[0];
|
||||
default:
|
||||
string result = "(" + fields[0];
|
||||
for (size_t i = 1; i < fields.size(); i++) {
|
||||
result += ", ";
|
||||
result += fields[i];
|
||||
}
|
||||
result += ")";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the description for a matcher defined using the MATCHER*()
|
||||
// macro where the user-supplied description string is "", if
|
||||
// 'negation' is false; otherwise returns the description of the
|
||||
// negation of the matcher. 'param_values' contains a list of strings
|
||||
// that are the print-out of the matcher's parameters.
|
||||
string FormatMatcherDescription(bool negation, const char* matcher_name,
|
||||
const Strings& param_values) {
|
||||
string result = ConvertIdentifierNameToWords(matcher_name);
|
||||
if (param_values.size() >= 1)
|
||||
result += " " + JoinAsTuple(param_values);
|
||||
GTEST_API_ std::string FormatMatcherDescription(bool negation,
|
||||
const char* matcher_name,
|
||||
const Strings& param_values) {
|
||||
std::string result = ConvertIdentifierNameToWords(matcher_name);
|
||||
if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values);
|
||||
return negation ? "not (" + result + ")" : result;
|
||||
}
|
||||
|
||||
// FindMaxBipartiteMatching and its helper class.
|
||||
//
|
||||
// Uses the well-known Ford-Fulkerson max flow method to find a maximum
|
||||
// bipartite matching. Flow is considered to be from left to right.
|
||||
// There is an implicit source node that is connected to all of the left
|
||||
// nodes, and an implicit sink node that is connected to all of the
|
||||
// right nodes. All edges have unit capacity.
|
||||
//
|
||||
// Neither the flow graph nor the residual flow graph are represented
|
||||
// explicitly. Instead, they are implied by the information in 'graph' and
|
||||
// a vector<int> called 'left_' whose elements are initialized to the
|
||||
// value kUnused. This represents the initial state of the algorithm,
|
||||
// where the flow graph is empty, and the residual flow graph has the
|
||||
// following edges:
|
||||
// - An edge from source to each left_ node
|
||||
// - An edge from each right_ node to sink
|
||||
// - An edge from each left_ node to each right_ node, if the
|
||||
// corresponding edge exists in 'graph'.
|
||||
//
|
||||
// When the TryAugment() method adds a flow, it sets left_[l] = r for some
|
||||
// nodes l and r. This induces the following changes:
|
||||
// - The edges (source, l), (l, r), and (r, sink) are added to the
|
||||
// flow graph.
|
||||
// - The same three edges are removed from the residual flow graph.
|
||||
// - The reverse edges (l, source), (r, l), and (sink, r) are added
|
||||
// to the residual flow graph, which is a directional graph
|
||||
// representing unused flow capacity.
|
||||
//
|
||||
// When the method augments a flow (moving left_[l] from some r1 to some
|
||||
// other r2), this can be thought of as "undoing" the above steps with
|
||||
// respect to r1 and "redoing" them with respect to r2.
|
||||
//
|
||||
// It bears repeating that the flow graph and residual flow graph are
|
||||
// never represented explicitly, but can be derived by looking at the
|
||||
// information in 'graph' and in left_.
|
||||
//
|
||||
// As an optimization, there is a second vector<int> called right_ which
|
||||
// does not provide any new information. Instead, it enables more
|
||||
// efficient queries about edges entering or leaving the right-side nodes
|
||||
// of the flow or residual flow graphs. The following invariants are
|
||||
// maintained:
|
||||
//
|
||||
// left[l] == kUnused or right[left[l]] == l
|
||||
// right[r] == kUnused or left[right[r]] == r
|
||||
//
|
||||
// . [ source ] .
|
||||
// . ||| .
|
||||
// . ||| .
|
||||
// . ||\--> left[0]=1 ---\ right[0]=-1 ----\ .
|
||||
// . || | | .
|
||||
// . |\---> left[1]=-1 \--> right[1]=0 ---\| .
|
||||
// . | || .
|
||||
// . \----> left[2]=2 ------> right[2]=2 --\|| .
|
||||
// . ||| .
|
||||
// . elements matchers vvv .
|
||||
// . [ sink ] .
|
||||
//
|
||||
// See Also:
|
||||
// [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method".
|
||||
// "Introduction to Algorithms (Second ed.)", pp. 651-664.
|
||||
// [2] "Ford-Fulkerson algorithm", Wikipedia,
|
||||
// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'
|
||||
class MaxBipartiteMatchState {
|
||||
public:
|
||||
explicit MaxBipartiteMatchState(const MatchMatrix& graph)
|
||||
: graph_(&graph),
|
||||
left_(graph_->LhsSize(), kUnused),
|
||||
right_(graph_->RhsSize(), kUnused) {}
|
||||
|
||||
// Returns the edges of a maximal match, each in the form {left, right}.
|
||||
ElementMatcherPairs Compute() {
|
||||
// 'seen' is used for path finding { 0: unseen, 1: seen }.
|
||||
::std::vector<char> seen;
|
||||
// Searches the residual flow graph for a path from each left node to
|
||||
// the sink in the residual flow graph, and if one is found, add flow
|
||||
// to the graph. It's okay to search through the left nodes once. The
|
||||
// edge from the implicit source node to each previously-visited left
|
||||
// node will have flow if that left node has any path to the sink
|
||||
// whatsoever. Subsequent augmentations can only add flow to the
|
||||
// network, and cannot take away that previous flow unit from the source.
|
||||
// Since the source-to-left edge can only carry one flow unit (or,
|
||||
// each element can be matched to only one matcher), there is no need
|
||||
// to visit the left nodes more than once looking for augmented paths.
|
||||
// The flow is known to be possible or impossible by looking at the
|
||||
// node once.
|
||||
for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
|
||||
// Reset the path-marking vector and try to find a path from
|
||||
// source to sink starting at the left_[ilhs] node.
|
||||
GTEST_CHECK_(left_[ilhs] == kUnused)
|
||||
<< "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs];
|
||||
// 'seen' initialized to 'graph_->RhsSize()' copies of 0.
|
||||
seen.assign(graph_->RhsSize(), 0);
|
||||
TryAugment(ilhs, &seen);
|
||||
}
|
||||
ElementMatcherPairs result;
|
||||
for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {
|
||||
size_t irhs = left_[ilhs];
|
||||
if (irhs == kUnused) continue;
|
||||
result.push_back(ElementMatcherPair(ilhs, irhs));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
static const size_t kUnused = static_cast<size_t>(-1);
|
||||
|
||||
// Perform a depth-first search from left node ilhs to the sink. If a
|
||||
// path is found, flow is added to the network by linking the left and
|
||||
// right vector elements corresponding each segment of the path.
|
||||
// Returns true if a path to sink was found, which means that a unit of
|
||||
// flow was added to the network. The 'seen' vector elements correspond
|
||||
// to right nodes and are marked to eliminate cycles from the search.
|
||||
//
|
||||
// Left nodes will only be explored at most once because they
|
||||
// are accessible from at most one right node in the residual flow
|
||||
// graph.
|
||||
//
|
||||
// Note that left_[ilhs] is the only element of left_ that TryAugment will
|
||||
// potentially transition from kUnused to another value. Any other
|
||||
// left_ element holding kUnused before TryAugment will be holding it
|
||||
// when TryAugment returns.
|
||||
//
|
||||
bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {
|
||||
for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
|
||||
if ((*seen)[irhs]) continue;
|
||||
if (!graph_->HasEdge(ilhs, irhs)) continue;
|
||||
// There's an available edge from ilhs to irhs.
|
||||
(*seen)[irhs] = 1;
|
||||
// Next a search is performed to determine whether
|
||||
// this edge is a dead end or leads to the sink.
|
||||
//
|
||||
// right_[irhs] == kUnused means that there is residual flow from
|
||||
// right node irhs to the sink, so we can use that to finish this
|
||||
// flow path and return success.
|
||||
//
|
||||
// Otherwise there is residual flow to some ilhs. We push flow
|
||||
// along that path and call ourselves recursively to see if this
|
||||
// ultimately leads to sink.
|
||||
if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {
|
||||
// Add flow from left_[ilhs] to right_[irhs].
|
||||
left_[ilhs] = irhs;
|
||||
right_[irhs] = ilhs;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const MatchMatrix* graph_; // not owned
|
||||
// Each element of the left_ vector represents a left hand side node
|
||||
// (i.e. an element) and each element of right_ is a right hand side
|
||||
// node (i.e. a matcher). The values in the left_ vector indicate
|
||||
// outflow from that node to a node on the right_ side. The values
|
||||
// in the right_ indicate inflow, and specify which left_ node is
|
||||
// feeding that right_ node, if any. For example, left_[3] == 1 means
|
||||
// there's a flow from element #3 to matcher #1. Such a flow would also
|
||||
// be redundantly represented in the right_ vector as right_[1] == 3.
|
||||
// Elements of left_ and right_ are either kUnused or mutually
|
||||
// referent. Mutually referent means that left_[right_[i]] = i and
|
||||
// right_[left_[i]] = i.
|
||||
::std::vector<size_t> left_;
|
||||
::std::vector<size_t> right_;
|
||||
|
||||
GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
|
||||
};
|
||||
|
||||
const size_t MaxBipartiteMatchState::kUnused;
|
||||
|
||||
GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {
|
||||
return MaxBipartiteMatchState(g).Compute();
|
||||
}
|
||||
|
||||
static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,
|
||||
::std::ostream* stream) {
|
||||
typedef ElementMatcherPairs::const_iterator Iter;
|
||||
::std::ostream& os = *stream;
|
||||
os << "{";
|
||||
const char* sep = "";
|
||||
for (Iter it = pairs.begin(); it != pairs.end(); ++it) {
|
||||
os << sep << "\n ("
|
||||
<< "element #" << it->first << ", "
|
||||
<< "matcher #" << it->second << ")";
|
||||
sep = ",";
|
||||
}
|
||||
os << "\n}";
|
||||
}
|
||||
|
||||
bool MatchMatrix::NextGraph() {
|
||||
for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
|
||||
for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
|
||||
char& b = matched_[SpaceIndex(ilhs, irhs)];
|
||||
if (!b) {
|
||||
b = 1;
|
||||
return true;
|
||||
}
|
||||
b = 0;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void MatchMatrix::Randomize() {
|
||||
for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {
|
||||
for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {
|
||||
char& b = matched_[SpaceIndex(ilhs, irhs)];
|
||||
b = static_cast<char>(rand() & 1); // NOLINT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string MatchMatrix::DebugString() const {
|
||||
::std::stringstream ss;
|
||||
const char* sep = "";
|
||||
for (size_t i = 0; i < LhsSize(); ++i) {
|
||||
ss << sep;
|
||||
for (size_t j = 0; j < RhsSize(); ++j) {
|
||||
ss << HasEdge(i, j);
|
||||
}
|
||||
sep = ";";
|
||||
}
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
void UnorderedElementsAreMatcherImplBase::DescribeToImpl(
|
||||
::std::ostream* os) const {
|
||||
switch (match_flags()) {
|
||||
case UnorderedMatcherRequire::ExactMatch:
|
||||
if (matcher_describers_.empty()) {
|
||||
*os << "is empty";
|
||||
return;
|
||||
}
|
||||
if (matcher_describers_.size() == 1) {
|
||||
*os << "has " << Elements(1) << " and that element ";
|
||||
matcher_describers_[0]->DescribeTo(os);
|
||||
return;
|
||||
}
|
||||
*os << "has " << Elements(matcher_describers_.size())
|
||||
<< " and there exists some permutation of elements such that:\n";
|
||||
break;
|
||||
case UnorderedMatcherRequire::Superset:
|
||||
*os << "a surjection from elements to requirements exists such that:\n";
|
||||
break;
|
||||
case UnorderedMatcherRequire::Subset:
|
||||
*os << "an injection from elements to requirements exists such that:\n";
|
||||
break;
|
||||
}
|
||||
|
||||
const char* sep = "";
|
||||
for (size_t i = 0; i != matcher_describers_.size(); ++i) {
|
||||
*os << sep;
|
||||
if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
|
||||
*os << " - element #" << i << " ";
|
||||
} else {
|
||||
*os << " - an element ";
|
||||
}
|
||||
matcher_describers_[i]->DescribeTo(os);
|
||||
if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
|
||||
sep = ", and\n";
|
||||
} else {
|
||||
sep = "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(
|
||||
::std::ostream* os) const {
|
||||
switch (match_flags()) {
|
||||
case UnorderedMatcherRequire::ExactMatch:
|
||||
if (matcher_describers_.empty()) {
|
||||
*os << "isn't empty";
|
||||
return;
|
||||
}
|
||||
if (matcher_describers_.size() == 1) {
|
||||
*os << "doesn't have " << Elements(1) << ", or has " << Elements(1)
|
||||
<< " that ";
|
||||
matcher_describers_[0]->DescribeNegationTo(os);
|
||||
return;
|
||||
}
|
||||
*os << "doesn't have " << Elements(matcher_describers_.size())
|
||||
<< ", or there exists no permutation of elements such that:\n";
|
||||
break;
|
||||
case UnorderedMatcherRequire::Superset:
|
||||
*os << "no surjection from elements to requirements exists such that:\n";
|
||||
break;
|
||||
case UnorderedMatcherRequire::Subset:
|
||||
*os << "no injection from elements to requirements exists such that:\n";
|
||||
break;
|
||||
}
|
||||
const char* sep = "";
|
||||
for (size_t i = 0; i != matcher_describers_.size(); ++i) {
|
||||
*os << sep;
|
||||
if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
|
||||
*os << " - element #" << i << " ";
|
||||
} else {
|
||||
*os << " - an element ";
|
||||
}
|
||||
matcher_describers_[i]->DescribeTo(os);
|
||||
if (match_flags() == UnorderedMatcherRequire::ExactMatch) {
|
||||
sep = ", and\n";
|
||||
} else {
|
||||
sep = "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Checks that all matchers match at least one element, and that all
|
||||
// elements match at least one matcher. This enables faster matching
|
||||
// and better error reporting.
|
||||
// Returns false, writing an explanation to 'listener', if and only
|
||||
// if the success criteria are not met.
|
||||
bool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(
|
||||
const ::std::vector<std::string>& element_printouts,
|
||||
const MatchMatrix& matrix, MatchResultListener* listener) const {
|
||||
bool result = true;
|
||||
::std::vector<char> element_matched(matrix.LhsSize(), 0);
|
||||
::std::vector<char> matcher_matched(matrix.RhsSize(), 0);
|
||||
|
||||
for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {
|
||||
for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {
|
||||
char matched = matrix.HasEdge(ilhs, irhs);
|
||||
element_matched[ilhs] |= matched;
|
||||
matcher_matched[irhs] |= matched;
|
||||
}
|
||||
}
|
||||
|
||||
if (match_flags() & UnorderedMatcherRequire::Superset) {
|
||||
const char* sep =
|
||||
"where the following matchers don't match any elements:\n";
|
||||
for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {
|
||||
if (matcher_matched[mi]) continue;
|
||||
result = false;
|
||||
if (listener->IsInterested()) {
|
||||
*listener << sep << "matcher #" << mi << ": ";
|
||||
matcher_describers_[mi]->DescribeTo(listener->stream());
|
||||
sep = ",\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (match_flags() & UnorderedMatcherRequire::Subset) {
|
||||
const char* sep =
|
||||
"where the following elements don't match any matchers:\n";
|
||||
const char* outer_sep = "";
|
||||
if (!result) {
|
||||
outer_sep = "\nand ";
|
||||
}
|
||||
for (size_t ei = 0; ei < element_matched.size(); ++ei) {
|
||||
if (element_matched[ei]) continue;
|
||||
result = false;
|
||||
if (listener->IsInterested()) {
|
||||
*listener << outer_sep << sep << "element #" << ei << ": "
|
||||
<< element_printouts[ei];
|
||||
sep = ",\n";
|
||||
outer_sep = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool UnorderedElementsAreMatcherImplBase::FindPairing(
|
||||
const MatchMatrix& matrix, MatchResultListener* listener) const {
|
||||
ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);
|
||||
|
||||
size_t max_flow = matches.size();
|
||||
if ((match_flags() & UnorderedMatcherRequire::Superset) &&
|
||||
max_flow < matrix.RhsSize()) {
|
||||
if (listener->IsInterested()) {
|
||||
*listener << "where no permutation of the elements can satisfy all "
|
||||
"matchers, and the closest match is "
|
||||
<< max_flow << " of " << matrix.RhsSize()
|
||||
<< " matchers with the pairings:\n";
|
||||
LogElementMatcherPairVec(matches, listener->stream());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if ((match_flags() & UnorderedMatcherRequire::Subset) &&
|
||||
max_flow < matrix.LhsSize()) {
|
||||
if (listener->IsInterested()) {
|
||||
*listener
|
||||
<< "where not all elements can be matched, and the closest match is "
|
||||
<< max_flow << " of " << matrix.RhsSize()
|
||||
<< " matchers with the pairings:\n";
|
||||
LogElementMatcherPairVec(matches, listener->stream());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (matches.size() > 1) {
|
||||
if (listener->IsInterested()) {
|
||||
const char* sep = "where:\n";
|
||||
for (size_t mi = 0; mi < matches.size(); ++mi) {
|
||||
*listener << sep << " - element #" << matches[mi].first
|
||||
<< " is matched by matcher #" << matches[mi].second;
|
||||
sep = ",\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace testing
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -41,6 +40,7 @@
|
|||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
|
@ -48,26 +48,34 @@
|
|||
# include <unistd.h> // NOLINT
|
||||
#endif
|
||||
|
||||
// Silence C4800 (C4800: 'int *const ': forcing value
|
||||
// to bool 'true' or 'false') for MSVC 14,15
|
||||
#ifdef _MSC_VER
|
||||
#if _MSC_VER <= 1900
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4800)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
|
||||
// Protects the mock object registry (in class Mock), all function
|
||||
// mockers, and all expectations.
|
||||
GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
|
||||
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
|
||||
|
||||
// Logs a message including file and line number information.
|
||||
void LogWithLocation(testing::internal::LogSeverity severity,
|
||||
const char* file, int line,
|
||||
const string& message) {
|
||||
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
|
||||
const char* file, int line,
|
||||
const std::string& message) {
|
||||
::std::ostringstream s;
|
||||
s << file << ":" << line << ": " << message << ::std::endl;
|
||||
Log(severity, s.str(), 0);
|
||||
}
|
||||
|
||||
// Constructs an ExpectationBase object.
|
||||
ExpectationBase::ExpectationBase(const char* a_file,
|
||||
int a_line,
|
||||
const string& a_source_text)
|
||||
ExpectationBase::ExpectationBase(const char* a_file, int a_line,
|
||||
const std::string& a_source_text)
|
||||
: file_(a_file),
|
||||
line_(a_line),
|
||||
source_text_(a_source_text),
|
||||
|
@ -92,63 +100,86 @@ void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
|
|||
}
|
||||
|
||||
// Retires all pre-requisites of this expectation.
|
||||
void ExpectationBase::RetireAllPreRequisites() {
|
||||
void ExpectationBase::RetireAllPreRequisites()
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
|
||||
if (is_retired()) {
|
||||
// We can take this short-cut as we never retire an expectation
|
||||
// until we have retired all its pre-requisites.
|
||||
return;
|
||||
}
|
||||
|
||||
for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
|
||||
it != immediate_prerequisites_.end(); ++it) {
|
||||
ExpectationBase* const prerequisite = it->expectation_base().get();
|
||||
if (!prerequisite->is_retired()) {
|
||||
prerequisite->RetireAllPreRequisites();
|
||||
prerequisite->Retire();
|
||||
::std::vector<ExpectationBase*> expectations(1, this);
|
||||
while (!expectations.empty()) {
|
||||
ExpectationBase* exp = expectations.back();
|
||||
expectations.pop_back();
|
||||
|
||||
for (ExpectationSet::const_iterator it =
|
||||
exp->immediate_prerequisites_.begin();
|
||||
it != exp->immediate_prerequisites_.end(); ++it) {
|
||||
ExpectationBase* next = it->expectation_base().get();
|
||||
if (!next->is_retired()) {
|
||||
next->Retire();
|
||||
expectations.push_back(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true iff all pre-requisites of this expectation have been
|
||||
// satisfied.
|
||||
// L >= g_gmock_mutex
|
||||
bool ExpectationBase::AllPrerequisitesAreSatisfied() const {
|
||||
bool ExpectationBase::AllPrerequisitesAreSatisfied() const
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
|
||||
g_gmock_mutex.AssertHeld();
|
||||
for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
|
||||
it != immediate_prerequisites_.end(); ++it) {
|
||||
if (!(it->expectation_base()->IsSatisfied()) ||
|
||||
!(it->expectation_base()->AllPrerequisitesAreSatisfied()))
|
||||
return false;
|
||||
::std::vector<const ExpectationBase*> expectations(1, this);
|
||||
while (!expectations.empty()) {
|
||||
const ExpectationBase* exp = expectations.back();
|
||||
expectations.pop_back();
|
||||
|
||||
for (ExpectationSet::const_iterator it =
|
||||
exp->immediate_prerequisites_.begin();
|
||||
it != exp->immediate_prerequisites_.end(); ++it) {
|
||||
const ExpectationBase* next = it->expectation_base().get();
|
||||
if (!next->IsSatisfied()) return false;
|
||||
expectations.push_back(next);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Adds unsatisfied pre-requisites of this expectation to 'result'.
|
||||
// L >= g_gmock_mutex
|
||||
void ExpectationBase::FindUnsatisfiedPrerequisites(
|
||||
ExpectationSet* result) const {
|
||||
void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
|
||||
g_gmock_mutex.AssertHeld();
|
||||
for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
|
||||
it != immediate_prerequisites_.end(); ++it) {
|
||||
if (it->expectation_base()->IsSatisfied()) {
|
||||
// If *it is satisfied and has a call count of 0, some of its
|
||||
// pre-requisites may not be satisfied yet.
|
||||
if (it->expectation_base()->call_count_ == 0) {
|
||||
it->expectation_base()->FindUnsatisfiedPrerequisites(result);
|
||||
::std::vector<const ExpectationBase*> expectations(1, this);
|
||||
while (!expectations.empty()) {
|
||||
const ExpectationBase* exp = expectations.back();
|
||||
expectations.pop_back();
|
||||
|
||||
for (ExpectationSet::const_iterator it =
|
||||
exp->immediate_prerequisites_.begin();
|
||||
it != exp->immediate_prerequisites_.end(); ++it) {
|
||||
const ExpectationBase* next = it->expectation_base().get();
|
||||
|
||||
if (next->IsSatisfied()) {
|
||||
// If *it is satisfied and has a call count of 0, some of its
|
||||
// pre-requisites may not be satisfied yet.
|
||||
if (next->call_count_ == 0) {
|
||||
expectations.push_back(next);
|
||||
}
|
||||
} else {
|
||||
// Now that we know next is unsatisfied, we are not so interested
|
||||
// in whether its pre-requisites are satisfied. Therefore we
|
||||
// don't iterate into it here.
|
||||
*result += *it;
|
||||
}
|
||||
} else {
|
||||
// Now that we know *it is unsatisfied, we are not so interested
|
||||
// in whether its pre-requisites are satisfied. Therefore we
|
||||
// don't recursively call FindUnsatisfiedPrerequisites() here.
|
||||
*result += *it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Describes how many times a function call matching this
|
||||
// expectation has occurred.
|
||||
// L >= g_gmock_mutex
|
||||
void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const {
|
||||
void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
|
||||
g_gmock_mutex.AssertHeld();
|
||||
|
||||
// Describes how many times the function is expected to be called.
|
||||
|
@ -170,8 +201,8 @@ void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const {
|
|||
// WillRepeatedly() clauses) against the cardinality if this hasn't
|
||||
// been done before. Prints a warning if there are too many or too
|
||||
// few actions.
|
||||
// L < mutex_
|
||||
void ExpectationBase::CheckActionCountIfNotDone() const {
|
||||
void ExpectationBase::CheckActionCountIfNotDone() const
|
||||
GTEST_LOCK_EXCLUDED_(mutex_) {
|
||||
bool should_check = false;
|
||||
{
|
||||
MutexLock l(&mutex_);
|
||||
|
@ -217,7 +248,7 @@ void ExpectationBase::CheckActionCountIfNotDone() const {
|
|||
ss << " and a WillRepeatedly()";
|
||||
}
|
||||
ss << ".";
|
||||
Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
|
||||
Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -240,17 +271,29 @@ void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
|
|||
|
||||
// Points to the implicit sequence introduced by a living InSequence
|
||||
// object (if any) in the current thread or NULL.
|
||||
ThreadLocal<Sequence*> g_gmock_implicit_sequence;
|
||||
GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
|
||||
|
||||
// Reports an uninteresting call (whose description is in msg) in the
|
||||
// manner specified by 'reaction'.
|
||||
void ReportUninterestingCall(CallReaction reaction, const string& msg) {
|
||||
void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
|
||||
// Include a stack trace only if --gmock_verbose=info is specified.
|
||||
const int stack_frames_to_skip =
|
||||
GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
|
||||
switch (reaction) {
|
||||
case ALLOW:
|
||||
Log(INFO, msg, 3);
|
||||
case kAllow:
|
||||
Log(kInfo, msg, stack_frames_to_skip);
|
||||
break;
|
||||
case WARN:
|
||||
Log(WARNING, msg, 3);
|
||||
case kWarn:
|
||||
Log(kWarning,
|
||||
msg +
|
||||
"\nNOTE: You can safely ignore the above warning unless this "
|
||||
"call should not happen. Do not suppress it by blindly adding "
|
||||
"an EXPECT_CALL() if you don't mean to enforce the call. "
|
||||
"See "
|
||||
"https://github.com/google/googletest/blob/master/googlemock/"
|
||||
"docs/CookBook.md#"
|
||||
"knowing-when-to-expect for details.\n",
|
||||
stack_frames_to_skip);
|
||||
break;
|
||||
default: // FAIL
|
||||
Expect(false, NULL, -1, msg);
|
||||
|
@ -266,8 +309,8 @@ UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
|
|||
// this information in the global mock registry. Will be called
|
||||
// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
|
||||
// method.
|
||||
// L < g_gmock_mutex
|
||||
void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) {
|
||||
void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
|
||||
{
|
||||
MutexLock l(&g_gmock_mutex);
|
||||
mock_obj_ = mock_obj;
|
||||
|
@ -278,9 +321,9 @@ void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) {
|
|||
// Sets the mock object this mock method belongs to, and sets the name
|
||||
// of the mock function. Will be called upon each invocation of this
|
||||
// mock function.
|
||||
// L < g_gmock_mutex
|
||||
void UntypedFunctionMockerBase::SetOwnerAndName(
|
||||
const void* mock_obj, const char* name) {
|
||||
void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
|
||||
const char* name)
|
||||
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
|
||||
// We protect name_ under g_gmock_mutex in case this mock function
|
||||
// is called from two threads concurrently.
|
||||
MutexLock l(&g_gmock_mutex);
|
||||
|
@ -290,8 +333,8 @@ void UntypedFunctionMockerBase::SetOwnerAndName(
|
|||
|
||||
// Returns the name of the function being mocked. Must be called
|
||||
// after RegisterOwner() or SetOwnerAndName() has been called.
|
||||
// L < g_gmock_mutex
|
||||
const void* UntypedFunctionMockerBase::MockObject() const {
|
||||
const void* UntypedFunctionMockerBase::MockObject() const
|
||||
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
|
||||
const void* mock_obj;
|
||||
{
|
||||
// We protect mock_obj_ under g_gmock_mutex in case this mock
|
||||
|
@ -307,8 +350,8 @@ const void* UntypedFunctionMockerBase::MockObject() const {
|
|||
|
||||
// Returns the name of this mock method. Must be called after
|
||||
// SetOwnerAndName() has been called.
|
||||
// L < g_gmock_mutex
|
||||
const char* UntypedFunctionMockerBase::Name() const {
|
||||
const char* UntypedFunctionMockerBase::Name() const
|
||||
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
|
||||
const char* name;
|
||||
{
|
||||
// We protect name_ under g_gmock_mutex in case this mock
|
||||
|
@ -325,9 +368,10 @@ const char* UntypedFunctionMockerBase::Name() const {
|
|||
// Calculates the result of invoking this mock function with the given
|
||||
// arguments, prints it, and returns it. The caller is responsible
|
||||
// for deleting the result.
|
||||
// L < g_gmock_mutex
|
||||
const UntypedActionResultHolderBase*
|
||||
UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
|
||||
UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
|
||||
void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
|
||||
// See the definition of untyped_expectations_ for why access to it
|
||||
// is unprotected here.
|
||||
if (untyped_expectations_.size() == 0) {
|
||||
// No expectation is set on this mock method - we have an
|
||||
// uninteresting call.
|
||||
|
@ -344,18 +388,21 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
|
|||
// the behavior of ReportUninterestingCall().
|
||||
const bool need_to_report_uninteresting_call =
|
||||
// If the user allows this uninteresting call, we print it
|
||||
// only when he wants informational messages.
|
||||
reaction == ALLOW ? LogIsVisible(INFO) :
|
||||
// If the user wants this to be a warning, we print it only
|
||||
// when he wants to see warnings.
|
||||
reaction == WARN ? LogIsVisible(WARNING) :
|
||||
// Otherwise, the user wants this to be an error, and we
|
||||
// should always print detailed information in the error.
|
||||
true;
|
||||
// only when they want informational messages.
|
||||
reaction == kAllow ? LogIsVisible(kInfo) :
|
||||
// If the user wants this to be a warning, we print
|
||||
// it only when they want to see warnings.
|
||||
reaction == kWarn
|
||||
? LogIsVisible(kWarning)
|
||||
:
|
||||
// Otherwise, the user wants this to be an error, and we
|
||||
// should always print detailed information in the error.
|
||||
true;
|
||||
|
||||
if (!need_to_report_uninteresting_call) {
|
||||
// Perform the action without printing the call information.
|
||||
return this->UntypedPerformDefaultAction(untyped_args, "");
|
||||
return this->UntypedPerformDefaultAction(
|
||||
untyped_args, "Function call: " + std::string(Name()));
|
||||
}
|
||||
|
||||
// Warns about the uninteresting call.
|
||||
|
@ -363,7 +410,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
|
|||
this->UntypedDescribeUninterestingCall(untyped_args, &ss);
|
||||
|
||||
// Calculates the function result.
|
||||
const UntypedActionResultHolderBase* const result =
|
||||
UntypedActionResultHolderBase* const result =
|
||||
this->UntypedPerformDefaultAction(untyped_args, ss.str());
|
||||
|
||||
// Prints the function result.
|
||||
|
@ -391,7 +438,8 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
|
|||
// True iff we need to print the call's arguments and return value.
|
||||
// This definition must be kept in sync with the uses of Expect()
|
||||
// and Log() in this function.
|
||||
const bool need_to_report_call = !found || is_excessive || LogIsVisible(INFO);
|
||||
const bool need_to_report_call =
|
||||
!found || is_excessive || LogIsVisible(kInfo);
|
||||
if (!need_to_report_call) {
|
||||
// Perform the action without printing the call information.
|
||||
return
|
||||
|
@ -409,7 +457,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
|
|||
untyped_expectation->DescribeLocationTo(&loc);
|
||||
}
|
||||
|
||||
const UntypedActionResultHolderBase* const result =
|
||||
UntypedActionResultHolderBase* const result =
|
||||
untyped_action == NULL ?
|
||||
this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
|
||||
this->UntypedPerformAction(untyped_action, untyped_args);
|
||||
|
@ -427,7 +475,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
|
|||
} else {
|
||||
// We had an expected call and the matching expectation is
|
||||
// described in ss.
|
||||
Log(INFO, loc.str() + ss.str(), 2);
|
||||
Log(kInfo, loc.str() + ss.str(), 2);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
@ -436,6 +484,8 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
|
|||
// Returns an Expectation object that references and co-owns exp,
|
||||
// which must be an expectation on this mock function.
|
||||
Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
|
||||
// See the definition of untyped_expectations_ for why access to it
|
||||
// is unprotected here.
|
||||
for (UntypedExpectations::const_iterator it =
|
||||
untyped_expectations_.begin();
|
||||
it != untyped_expectations_.end(); ++it) {
|
||||
|
@ -453,8 +503,8 @@ Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
|
|||
// Verifies that all expectations on this mock function have been
|
||||
// satisfied. Reports one or more Google Test non-fatal failures
|
||||
// and returns false if not.
|
||||
// L >= g_gmock_mutex
|
||||
bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() {
|
||||
bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
|
||||
g_gmock_mutex.AssertHeld();
|
||||
bool expectations_met = true;
|
||||
for (UntypedExpectations::const_iterator it =
|
||||
|
@ -480,10 +530,31 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() {
|
|||
untyped_expectation->line(), ss.str());
|
||||
}
|
||||
}
|
||||
untyped_expectations_.clear();
|
||||
|
||||
// Deleting our expectations may trigger other mock objects to be deleted, for
|
||||
// example if an action contains a reference counted smart pointer to that
|
||||
// mock object, and that is the last reference. So if we delete our
|
||||
// expectations within the context of the global mutex we may deadlock when
|
||||
// this method is called again. Instead, make a copy of the set of
|
||||
// expectations to delete, clear our set within the mutex, and then clear the
|
||||
// copied set outside of it.
|
||||
UntypedExpectations expectations_to_delete;
|
||||
untyped_expectations_.swap(expectations_to_delete);
|
||||
|
||||
g_gmock_mutex.Unlock();
|
||||
expectations_to_delete.clear();
|
||||
g_gmock_mutex.Lock();
|
||||
|
||||
return expectations_met;
|
||||
}
|
||||
|
||||
CallReaction intToCallReaction(int mock_behavior) {
|
||||
if (mock_behavior >= kAllow && mock_behavior <= kFail) {
|
||||
return static_cast<internal::CallReaction>(mock_behavior);
|
||||
}
|
||||
return kWarn;
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// Class Mock.
|
||||
|
@ -535,7 +606,7 @@ class MockObjectRegistry {
|
|||
if (it->second.leakable) // The user said it's fine to leak this object.
|
||||
continue;
|
||||
|
||||
// TODO(wan@google.com): Print the type of the leaked object.
|
||||
// FIXME: Print the type of the leaked object.
|
||||
// This can help the user identify the leaked object.
|
||||
std::cout << "\n";
|
||||
const MockObjectState& state = it->second;
|
||||
|
@ -551,9 +622,15 @@ class MockObjectRegistry {
|
|||
leaked_count++;
|
||||
}
|
||||
if (leaked_count > 0) {
|
||||
std::cout << "\nERROR: " << leaked_count
|
||||
<< " leaked mock " << (leaked_count == 1 ? "object" : "objects")
|
||||
<< " found at program exit.\n";
|
||||
std::cout << "\nERROR: " << leaked_count << " leaked mock "
|
||||
<< (leaked_count == 1 ? "object" : "objects")
|
||||
<< " found at program exit. Expectations on a mock object is "
|
||||
"verified when the object is destructed. Leaking a mock "
|
||||
"means that its expectations aren't verified, which is "
|
||||
"usually a test bug. If you really intend to leak a mock, "
|
||||
"you can suppress this error using "
|
||||
"testing::Mock::AllowLeak(mock_object), or you may use a "
|
||||
"fake or stub instead of a mock.\n";
|
||||
std::cout.flush();
|
||||
::std::cerr.flush();
|
||||
// RUN_ALL_TESTS() has already returned when this destructor is
|
||||
|
@ -565,6 +642,7 @@ class MockObjectRegistry {
|
|||
}
|
||||
|
||||
StateMap& states() { return states_; }
|
||||
|
||||
private:
|
||||
StateMap states_;
|
||||
};
|
||||
|
@ -578,9 +656,9 @@ std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
|
|||
|
||||
// Sets the reaction Google Mock should have when an uninteresting
|
||||
// method of the given mock object is called.
|
||||
// L < g_gmock_mutex
|
||||
void SetReactionOnUninterestingCalls(const void* mock_obj,
|
||||
internal::CallReaction reaction) {
|
||||
internal::CallReaction reaction)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
g_uninteresting_call_reaction[mock_obj] = reaction;
|
||||
}
|
||||
|
@ -589,47 +667,48 @@ void SetReactionOnUninterestingCalls(const void* mock_obj,
|
|||
|
||||
// Tells Google Mock to allow uninteresting calls on the given mock
|
||||
// object.
|
||||
// L < g_gmock_mutex
|
||||
void Mock::AllowUninterestingCalls(const void* mock_obj) {
|
||||
SetReactionOnUninterestingCalls(mock_obj, internal::ALLOW);
|
||||
void Mock::AllowUninterestingCalls(const void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
|
||||
}
|
||||
|
||||
// Tells Google Mock to warn the user about uninteresting calls on the
|
||||
// given mock object.
|
||||
// L < g_gmock_mutex
|
||||
void Mock::WarnUninterestingCalls(const void* mock_obj) {
|
||||
SetReactionOnUninterestingCalls(mock_obj, internal::WARN);
|
||||
void Mock::WarnUninterestingCalls(const void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
|
||||
}
|
||||
|
||||
// Tells Google Mock to fail uninteresting calls on the given mock
|
||||
// object.
|
||||
// L < g_gmock_mutex
|
||||
void Mock::FailUninterestingCalls(const void* mock_obj) {
|
||||
SetReactionOnUninterestingCalls(mock_obj, internal::FAIL);
|
||||
void Mock::FailUninterestingCalls(const void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
|
||||
}
|
||||
|
||||
// Tells Google Mock the given mock object is being destroyed and its
|
||||
// entry in the call-reaction table should be removed.
|
||||
// L < g_gmock_mutex
|
||||
void Mock::UnregisterCallReaction(const void* mock_obj) {
|
||||
void Mock::UnregisterCallReaction(const void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
g_uninteresting_call_reaction.erase(mock_obj);
|
||||
}
|
||||
|
||||
// Returns the reaction Google Mock will have on uninteresting calls
|
||||
// made on the given mock object.
|
||||
// L < g_gmock_mutex
|
||||
internal::CallReaction Mock::GetReactionOnUninterestingCalls(
|
||||
const void* mock_obj) {
|
||||
const void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
|
||||
internal::WARN : g_uninteresting_call_reaction[mock_obj];
|
||||
internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
|
||||
g_uninteresting_call_reaction[mock_obj];
|
||||
}
|
||||
|
||||
// Tells Google Mock to ignore mock_obj when checking for leaked mock
|
||||
// objects.
|
||||
// L < g_gmock_mutex
|
||||
void Mock::AllowLeak(const void* mock_obj) {
|
||||
void Mock::AllowLeak(const void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
g_mock_object_registry.states()[mock_obj].leakable = true;
|
||||
}
|
||||
|
@ -637,8 +716,8 @@ void Mock::AllowLeak(const void* mock_obj) {
|
|||
// Verifies and clears all expectations on the given mock object. If
|
||||
// the expectations aren't satisfied, generates one or more Google
|
||||
// Test non-fatal failures and returns false.
|
||||
// L < g_gmock_mutex
|
||||
bool Mock::VerifyAndClearExpectations(void* mock_obj) {
|
||||
bool Mock::VerifyAndClearExpectations(void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
return VerifyAndClearExpectationsLocked(mock_obj);
|
||||
}
|
||||
|
@ -646,8 +725,8 @@ bool Mock::VerifyAndClearExpectations(void* mock_obj) {
|
|||
// Verifies all expectations on the given mock object and clears its
|
||||
// default actions and expectations. Returns true iff the
|
||||
// verification was successful.
|
||||
// L < g_gmock_mutex
|
||||
bool Mock::VerifyAndClear(void* mock_obj) {
|
||||
bool Mock::VerifyAndClear(void* mock_obj)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
ClearDefaultActionsLocked(mock_obj);
|
||||
return VerifyAndClearExpectationsLocked(mock_obj);
|
||||
|
@ -656,8 +735,8 @@ bool Mock::VerifyAndClear(void* mock_obj) {
|
|||
// Verifies and clears all expectations on the given mock object. If
|
||||
// the expectations aren't satisfied, generates one or more Google
|
||||
// Test non-fatal failures and returns false.
|
||||
// L >= g_gmock_mutex
|
||||
bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) {
|
||||
bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
|
||||
internal::g_gmock_mutex.AssertHeld();
|
||||
if (g_mock_object_registry.states().count(mock_obj) == 0) {
|
||||
// No EXPECT_CALL() was set on the given mock object.
|
||||
|
@ -682,9 +761,9 @@ bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) {
|
|||
}
|
||||
|
||||
// Registers a mock object and a mock method it owns.
|
||||
// L < g_gmock_mutex
|
||||
void Mock::Register(const void* mock_obj,
|
||||
internal::UntypedFunctionMockerBase* mocker) {
|
||||
internal::UntypedFunctionMockerBase* mocker)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
|
||||
}
|
||||
|
@ -692,9 +771,9 @@ void Mock::Register(const void* mock_obj,
|
|||
// Tells Google Mock where in the source code mock_obj is used in an
|
||||
// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
|
||||
// information helps the user identify which object it is.
|
||||
// L < g_gmock_mutex
|
||||
void Mock::RegisterUseByOnCallOrExpectCall(
|
||||
const void* mock_obj, const char* file, int line) {
|
||||
void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
|
||||
const char* file, int line)
|
||||
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
|
||||
internal::MutexLock l(&internal::g_gmock_mutex);
|
||||
MockObjectState& state = g_mock_object_registry.states()[mock_obj];
|
||||
if (state.first_used_file == NULL) {
|
||||
|
@ -703,7 +782,7 @@ void Mock::RegisterUseByOnCallOrExpectCall(
|
|||
const TestInfo* const test_info =
|
||||
UnitTest::GetInstance()->current_test_info();
|
||||
if (test_info != NULL) {
|
||||
// TODO(wan@google.com): record the test case name when the
|
||||
// FIXME: record the test case name when the
|
||||
// ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
|
||||
// TearDownTestCase().
|
||||
state.first_used_test_case = test_info->test_case_name();
|
||||
|
@ -716,8 +795,8 @@ void Mock::RegisterUseByOnCallOrExpectCall(
|
|||
// registry when the last mock method associated with it has been
|
||||
// unregistered. This is called only in the destructor of
|
||||
// FunctionMockerBase.
|
||||
// L >= g_gmock_mutex
|
||||
void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) {
|
||||
void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
|
||||
internal::g_gmock_mutex.AssertHeld();
|
||||
for (MockObjectRegistry::StateMap::iterator it =
|
||||
g_mock_object_registry.states().begin();
|
||||
|
@ -734,8 +813,8 @@ void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) {
|
|||
}
|
||||
|
||||
// Clears all ON_CALL()s set on the given mock object.
|
||||
// L >= g_gmock_mutex
|
||||
void Mock::ClearDefaultActionsLocked(void* mock_obj) {
|
||||
void Mock::ClearDefaultActionsLocked(void* mock_obj)
|
||||
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
|
||||
internal::g_gmock_mutex.AssertHeld();
|
||||
|
||||
if (g_mock_object_registry.states().count(mock_obj) == 0) {
|
||||
|
@ -795,3 +874,9 @@ InSequence::~InSequence() {
|
|||
}
|
||||
|
||||
} // namespace testing
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#if _MSC_VER <= 1900
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
#endif
|
||||
|
|
|
@ -26,15 +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)
|
||||
|
||||
|
||||
#include "gmock/gmock.h"
|
||||
#include "gmock/internal/gmock-port.h"
|
||||
|
||||
namespace testing {
|
||||
|
||||
// TODO(wan@google.com): support using environment variables to
|
||||
// FIXME: support using environment variables to
|
||||
// control the flag values, like what Google Test does.
|
||||
|
||||
GMOCK_DEFINE_bool_(catch_leaked_mocks, true,
|
||||
|
@ -48,6 +47,13 @@ GMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,
|
|||
" warning - prints warnings and errors.\n"
|
||||
" error - prints errors only.");
|
||||
|
||||
GMOCK_DEFINE_int32_(default_mock_behavior, 1,
|
||||
"Controls the default behavior of mocks."
|
||||
" Valid values:\n"
|
||||
" 0 - by default, mocks act as NiceMocks.\n"
|
||||
" 1 - by default, mocks act as NaggyMocks.\n"
|
||||
" 2 - by default, mocks act as StrictMocks.");
|
||||
|
||||
namespace internal {
|
||||
|
||||
// Parses a string as a command line flag. The string should have the
|
||||
|
@ -62,7 +68,7 @@ static const char* ParseGoogleMockFlagValue(const char* str,
|
|||
if (str == NULL || flag == NULL) return NULL;
|
||||
|
||||
// The flag must start with "--gmock_".
|
||||
const String flag_str = String::Format("--gmock_%s", flag);
|
||||
const std::string flag_str = std::string("--gmock_") + flag;
|
||||
const size_t flag_len = flag_str.length();
|
||||
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
|
||||
|
||||
|
@ -106,6 +112,7 @@ static bool ParseGoogleMockBoolFlag(const char* str, const char* flag,
|
|||
//
|
||||
// On success, stores the value of the flag in *value, and returns
|
||||
// true. On failure, returns false without changing *value.
|
||||
template <typename String>
|
||||
static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
|
||||
String* value) {
|
||||
// Gets the value of the flag as a string.
|
||||
|
@ -119,6 +126,19 @@ static bool ParseGoogleMockStringFlag(const char* str, const char* flag,
|
|||
return true;
|
||||
}
|
||||
|
||||
static bool ParseGoogleMockIntFlag(const char* str, const char* flag,
|
||||
int* value) {
|
||||
// Gets the value of the flag as a string.
|
||||
const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);
|
||||
|
||||
// Aborts if the parsing failed.
|
||||
if (value_str == NULL) return false;
|
||||
|
||||
// Sets *value to the value of the flag.
|
||||
return ParseInt32(Message() << "The value of flag --" << flag,
|
||||
value_str, value);
|
||||
}
|
||||
|
||||
// The internal implementation of InitGoogleMock().
|
||||
//
|
||||
// The type parameter CharType can be instantiated to either char or
|
||||
|
@ -131,13 +151,15 @@ void InitGoogleMockImpl(int* argc, CharType** argv) {
|
|||
if (*argc <= 0) return;
|
||||
|
||||
for (int i = 1; i != *argc; i++) {
|
||||
const String arg_string = StreamableToString(argv[i]);
|
||||
const std::string arg_string = StreamableToString(argv[i]);
|
||||
const char* const arg = arg_string.c_str();
|
||||
|
||||
// Do we see a Google Mock flag?
|
||||
if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks",
|
||||
&GMOCK_FLAG(catch_leaked_mocks)) ||
|
||||
ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) {
|
||||
ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose)) ||
|
||||
ParseGoogleMockIntFlag(arg, "default_mock_behavior",
|
||||
&GMOCK_FLAG(default_mock_behavior))) {
|
||||
// Yes. Shift the remainder of the argv list left by one. Note
|
||||
// that argv has (*argc + 1) elements, the last one always being
|
||||
// NULL. The following loop moves the trailing NULL element as
|
||||
|
@ -169,13 +191,13 @@ void InitGoogleMockImpl(int* argc, CharType** argv) {
|
|||
// Since Google Test is needed for Google Mock to work, this function
|
||||
// also initializes Google Test and parses its flags, if that hasn't
|
||||
// been done.
|
||||
void InitGoogleMock(int* argc, char** argv) {
|
||||
GTEST_API_ void InitGoogleMock(int* argc, char** argv) {
|
||||
internal::InitGoogleMockImpl(argc, argv);
|
||||
}
|
||||
|
||||
// This overloaded version can be used in Windows programs compiled in
|
||||
// UNICODE mode.
|
||||
void InitGoogleMock(int* argc, wchar_t** argv) {
|
||||
GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {
|
||||
internal::InitGoogleMockImpl(argc, argv);
|
||||
}
|
||||
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 <iostream>
|
||||
#include "gmock/gmock.h"
|
||||
|
@ -37,13 +36,14 @@
|
|||
// causes a link error when _tmain is defined in a static library and UNICODE
|
||||
// is enabled. For this reason instead of _tmain, main function is used on
|
||||
// Windows. See the following link to track the current status of this bug:
|
||||
// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT
|
||||
// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library
|
||||
// // NOLINT
|
||||
#if GTEST_OS_WINDOWS_MOBILE
|
||||
# include <tchar.h> // NOLINT
|
||||
|
||||
int _tmain(int argc, TCHAR** argv) {
|
||||
GTEST_API_ int _tmain(int argc, TCHAR** argv) {
|
||||
#else
|
||||
int main(int argc, char** argv) {
|
||||
GTEST_API_ int main(int argc, char** argv) {
|
||||
#endif // GTEST_OS_WINDOWS_MOBILE
|
||||
std::cout << "Running main() from gmock_main.cc\n";
|
||||
// Since Google Mock depends on Google Test, InitGoogleMock() is
|
||||
|
|
|
@ -0,0 +1,123 @@
|
|||
# Copyright 2017 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: misterg@google.com (Gennadiy Civil)
|
||||
#
|
||||
# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock
|
||||
|
||||
licenses(["notice"])
|
||||
|
||||
""" gmock own tests """
|
||||
|
||||
cc_test(
|
||||
name = "gmock_all_test",
|
||||
size = "small",
|
||||
srcs = glob(
|
||||
include = [
|
||||
"gmock-*.cc",
|
||||
],
|
||||
),
|
||||
linkopts = select({
|
||||
"//:windows": [],
|
||||
"//:windows_msvc": [],
|
||||
"//conditions:default": [
|
||||
"-pthread",
|
||||
],
|
||||
}),
|
||||
deps = ["//:gtest"],
|
||||
)
|
||||
|
||||
# Py tests
|
||||
|
||||
py_library(
|
||||
name = "gmock_test_utils",
|
||||
testonly = 1,
|
||||
srcs = ["gmock_test_utils.py"],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "gmock_leak_test_",
|
||||
testonly = 1,
|
||||
srcs = ["gmock_leak_test_.cc"],
|
||||
deps = [
|
||||
"//:gtest_main",
|
||||
],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "gmock_leak_test",
|
||||
size = "medium",
|
||||
srcs = ["gmock_leak_test.py"],
|
||||
data = [
|
||||
":gmock_leak_test_",
|
||||
":gmock_test_utils",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gmock_link_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"gmock_link2_test.cc",
|
||||
"gmock_link_test.cc",
|
||||
"gmock_link_test.h",
|
||||
],
|
||||
deps = [
|
||||
"//:gtest_main",
|
||||
],
|
||||
)
|
||||
|
||||
cc_binary(
|
||||
name = "gmock_output_test_",
|
||||
srcs = ["gmock_output_test_.cc"],
|
||||
deps = [
|
||||
"//:gtest",
|
||||
],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "gmock_output_test",
|
||||
size = "medium",
|
||||
srcs = ["gmock_output_test.py"],
|
||||
data = [
|
||||
":gmock_output_test_",
|
||||
":gmock_output_test_golden.txt",
|
||||
],
|
||||
deps = [":gmock_test_utils"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gmock_test",
|
||||
size = "small",
|
||||
srcs = ["gmock_test.cc"],
|
||||
deps = [
|
||||
"//:gtest_main",
|
||||
],
|
||||
)
|
|
@ -26,16 +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)
|
||||
|
||||
|
||||
// Google Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file tests the built-in actions.
|
||||
|
||||
// Silence C4800 (C4800: 'int *const ': forcing value
|
||||
// to bool 'true' or 'false') for MSVC 14,15
|
||||
#ifdef _MSC_VER
|
||||
#if _MSC_VER <= 1900
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4800)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#include "gmock/gmock-actions.h"
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "gmock/gmock.h"
|
||||
#include "gmock/internal/gmock-port.h"
|
||||
|
@ -44,18 +53,11 @@
|
|||
|
||||
namespace {
|
||||
|
||||
using ::std::tr1::get;
|
||||
using ::std::tr1::make_tuple;
|
||||
using ::std::tr1::tuple;
|
||||
using ::std::tr1::tuple_element;
|
||||
using testing::internal::BuiltInDefaultValue;
|
||||
using testing::internal::Int64;
|
||||
using testing::internal::UInt64;
|
||||
// This list should be kept sorted.
|
||||
using testing::_;
|
||||
using testing::Action;
|
||||
using testing::ActionInterface;
|
||||
using testing::Assign;
|
||||
using testing::ByMove;
|
||||
using testing::ByRef;
|
||||
using testing::DefaultValue;
|
||||
using testing::DoDefault;
|
||||
|
@ -71,15 +73,20 @@ using testing::ReturnRef;
|
|||
using testing::ReturnRefOfCopy;
|
||||
using testing::SetArgPointee;
|
||||
using testing::SetArgumentPointee;
|
||||
using testing::Unused;
|
||||
using testing::_;
|
||||
using testing::get;
|
||||
using testing::internal::BuiltInDefaultValue;
|
||||
using testing::internal::Int64;
|
||||
using testing::internal::UInt64;
|
||||
using testing::make_tuple;
|
||||
using testing::tuple;
|
||||
using testing::tuple_element;
|
||||
|
||||
#if !GTEST_OS_WINDOWS_MOBILE
|
||||
using testing::SetErrnoAndReturn;
|
||||
#endif
|
||||
|
||||
#if GTEST_HAS_PROTOBUF_
|
||||
using testing::internal::TestMessage;
|
||||
#endif // GTEST_HAS_PROTOBUF_
|
||||
|
||||
// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
|
||||
TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
|
||||
EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
|
||||
|
@ -105,7 +112,11 @@ TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
|
|||
EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
|
||||
#endif
|
||||
#if GMOCK_WCHAR_T_IS_NATIVE_
|
||||
#if !defined(__WCHAR_UNSIGNED__)
|
||||
EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
|
||||
#else
|
||||
EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
|
||||
#endif
|
||||
#endif
|
||||
EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
|
||||
EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
|
||||
|
@ -189,16 +200,43 @@ TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
|
|||
EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
|
||||
}
|
||||
|
||||
// Tests that BuiltInDefaultValue<T>::Get() aborts the program with
|
||||
// the correct error message when T is a user-defined type.
|
||||
struct UserType {
|
||||
UserType() : value(0) {}
|
||||
// A type that's default constructible.
|
||||
class MyDefaultConstructible {
|
||||
public:
|
||||
MyDefaultConstructible() : value_(42) {}
|
||||
|
||||
int value;
|
||||
int value() const { return value_; }
|
||||
|
||||
private:
|
||||
int value_;
|
||||
};
|
||||
|
||||
TEST(BuiltInDefaultValueTest, UserTypeHasNoDefault) {
|
||||
EXPECT_FALSE(BuiltInDefaultValue<UserType>::Exists());
|
||||
// A type that's not default constructible.
|
||||
class MyNonDefaultConstructible {
|
||||
public:
|
||||
// Does not have a default ctor.
|
||||
explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
|
||||
|
||||
int value() const { return value_; }
|
||||
|
||||
private:
|
||||
int value_;
|
||||
};
|
||||
|
||||
#if GTEST_LANG_CXX11
|
||||
|
||||
TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
|
||||
EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
|
||||
}
|
||||
|
||||
TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
|
||||
EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
|
||||
}
|
||||
|
||||
#endif // GTEST_LANG_CXX11
|
||||
|
||||
TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
|
||||
EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
|
||||
}
|
||||
|
||||
// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
|
||||
|
@ -211,40 +249,42 @@ TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
|
|||
}, "");
|
||||
}
|
||||
|
||||
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForUserTypes) {
|
||||
TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
BuiltInDefaultValue<UserType>::Get();
|
||||
BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
|
||||
}, "");
|
||||
}
|
||||
|
||||
// Tests that DefaultValue<T>::IsSet() is false initially.
|
||||
TEST(DefaultValueTest, IsInitiallyUnset) {
|
||||
EXPECT_FALSE(DefaultValue<int>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<const UserType>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
|
||||
}
|
||||
|
||||
// Tests that DefaultValue<T> can be set and then unset.
|
||||
TEST(DefaultValueTest, CanBeSetAndUnset) {
|
||||
EXPECT_TRUE(DefaultValue<int>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<const UserType>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
|
||||
|
||||
DefaultValue<int>::Set(1);
|
||||
DefaultValue<const UserType>::Set(UserType());
|
||||
DefaultValue<const MyNonDefaultConstructible>::Set(
|
||||
MyNonDefaultConstructible(42));
|
||||
|
||||
EXPECT_EQ(1, DefaultValue<int>::Get());
|
||||
EXPECT_EQ(0, DefaultValue<const UserType>::Get().value);
|
||||
EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
|
||||
|
||||
EXPECT_TRUE(DefaultValue<int>::Exists());
|
||||
EXPECT_TRUE(DefaultValue<const UserType>::Exists());
|
||||
EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
|
||||
|
||||
DefaultValue<int>::Clear();
|
||||
DefaultValue<const UserType>::Clear();
|
||||
DefaultValue<const MyNonDefaultConstructible>::Clear();
|
||||
|
||||
EXPECT_FALSE(DefaultValue<int>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<const UserType>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
|
||||
|
||||
EXPECT_TRUE(DefaultValue<int>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<const UserType>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
|
||||
}
|
||||
|
||||
// Tests that DefaultValue<T>::Get() returns the
|
||||
|
@ -253,16 +293,29 @@ TEST(DefaultValueTest, CanBeSetAndUnset) {
|
|||
TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
|
||||
EXPECT_FALSE(DefaultValue<int>::IsSet());
|
||||
EXPECT_TRUE(DefaultValue<int>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<UserType>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<UserType>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
|
||||
|
||||
EXPECT_EQ(0, DefaultValue<int>::Get());
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
DefaultValue<UserType>::Get();
|
||||
DefaultValue<MyNonDefaultConstructible>::Get();
|
||||
}, "");
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_UNIQUE_PTR_
|
||||
TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
|
||||
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
|
||||
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL);
|
||||
DefaultValue<std::unique_ptr<int>>::SetFactory([] {
|
||||
return std::unique_ptr<int>(new int(42));
|
||||
});
|
||||
EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
|
||||
std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
|
||||
EXPECT_EQ(42, *i);
|
||||
}
|
||||
#endif // GTEST_HAS_STD_UNIQUE_PTR_
|
||||
|
||||
// Tests that DefaultValue<void>::Get() returns void.
|
||||
TEST(DefaultValueTest, GetWorksForVoid) {
|
||||
return DefaultValue<void>::Get();
|
||||
|
@ -273,36 +326,38 @@ TEST(DefaultValueTest, GetWorksForVoid) {
|
|||
// Tests that DefaultValue<T&>::IsSet() is false initially.
|
||||
TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
|
||||
EXPECT_FALSE(DefaultValue<int&>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<UserType&>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
|
||||
}
|
||||
|
||||
// Tests that DefaultValue<T&>::Exists is false initiallly.
|
||||
TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
|
||||
EXPECT_FALSE(DefaultValue<int&>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<UserType&>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
|
||||
}
|
||||
|
||||
// Tests that DefaultValue<T&> can be set and then unset.
|
||||
TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
|
||||
int n = 1;
|
||||
DefaultValue<const int&>::Set(n);
|
||||
UserType u;
|
||||
DefaultValue<UserType&>::Set(u);
|
||||
MyNonDefaultConstructible x(42);
|
||||
DefaultValue<MyNonDefaultConstructible&>::Set(x);
|
||||
|
||||
EXPECT_TRUE(DefaultValue<const int&>::Exists());
|
||||
EXPECT_TRUE(DefaultValue<UserType&>::Exists());
|
||||
EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
|
||||
|
||||
EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
|
||||
EXPECT_EQ(&u, &(DefaultValue<UserType&>::Get()));
|
||||
EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
|
||||
|
||||
DefaultValue<const int&>::Clear();
|
||||
DefaultValue<UserType&>::Clear();
|
||||
DefaultValue<MyNonDefaultConstructible&>::Clear();
|
||||
|
||||
EXPECT_FALSE(DefaultValue<const int&>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<UserType&>::Exists());
|
||||
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
|
||||
|
||||
EXPECT_FALSE(DefaultValue<const int&>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<UserType&>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
|
||||
}
|
||||
|
||||
// Tests that DefaultValue<T&>::Get() returns the
|
||||
|
@ -310,22 +365,22 @@ TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
|
|||
// false.
|
||||
TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
|
||||
EXPECT_FALSE(DefaultValue<int&>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<UserType&>::IsSet());
|
||||
EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
DefaultValue<int&>::Get();
|
||||
}, "");
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
DefaultValue<UserType>::Get();
|
||||
DefaultValue<MyNonDefaultConstructible>::Get();
|
||||
}, "");
|
||||
}
|
||||
|
||||
// Tests that ActionInterface can be implemented by defining the
|
||||
// Perform method.
|
||||
|
||||
typedef int MyFunction(bool, int);
|
||||
typedef int MyGlobalFunction(bool, int);
|
||||
|
||||
class MyActionImpl : public ActionInterface<MyFunction> {
|
||||
class MyActionImpl : public ActionInterface<MyGlobalFunction> {
|
||||
public:
|
||||
virtual int Perform(const tuple<bool, int>& args) {
|
||||
return get<0>(args) ? get<1>(args) : 0;
|
||||
|
@ -338,7 +393,7 @@ TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
|
|||
}
|
||||
|
||||
TEST(ActionInterfaceTest, MakeAction) {
|
||||
Action<MyFunction> action = MakeAction(new MyActionImpl);
|
||||
Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
|
||||
|
||||
// When exercising the Perform() method of Action<F>, we must pass
|
||||
// it a tuple whose size and type are compatible with F's argument
|
||||
|
@ -351,12 +406,12 @@ TEST(ActionInterfaceTest, MakeAction) {
|
|||
// Tests that Action<F> can be contructed from a pointer to
|
||||
// ActionInterface<F>.
|
||||
TEST(ActionTest, CanBeConstructedFromActionInterface) {
|
||||
Action<MyFunction> action(new MyActionImpl);
|
||||
Action<MyGlobalFunction> action(new MyActionImpl);
|
||||
}
|
||||
|
||||
// Tests that Action<F> delegates actual work to ActionInterface<F>.
|
||||
TEST(ActionTest, DelegatesWorkToActionInterface) {
|
||||
const Action<MyFunction> action(new MyActionImpl);
|
||||
const Action<MyGlobalFunction> action(new MyActionImpl);
|
||||
|
||||
EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
|
||||
EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
|
||||
|
@ -364,8 +419,8 @@ TEST(ActionTest, DelegatesWorkToActionInterface) {
|
|||
|
||||
// Tests that Action<F> can be copied.
|
||||
TEST(ActionTest, IsCopyable) {
|
||||
Action<MyFunction> a1(new MyActionImpl);
|
||||
Action<MyFunction> a2(a1); // Tests the copy constructor.
|
||||
Action<MyGlobalFunction> a1(new MyActionImpl);
|
||||
Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
|
||||
|
||||
// a1 should continue to work after being copied from.
|
||||
EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
|
||||
|
@ -492,6 +547,26 @@ TEST(ReturnTest, AcceptsStringLiteral) {
|
|||
EXPECT_EQ("world", a2.Perform(make_tuple()));
|
||||
}
|
||||
|
||||
// Test struct which wraps a vector of integers. Used in
|
||||
// 'SupportsWrapperReturnType' test.
|
||||
struct IntegerVectorWrapper {
|
||||
std::vector<int> * v;
|
||||
IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT
|
||||
};
|
||||
|
||||
// Tests that Return() works when return type is a wrapper type.
|
||||
TEST(ReturnTest, SupportsWrapperReturnType) {
|
||||
// Initialize vector of integers.
|
||||
std::vector<int> v;
|
||||
for (int i = 0; i < 5; ++i) v.push_back(i);
|
||||
|
||||
// Return() called with 'v' as argument. The Action will return the same data
|
||||
// as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
|
||||
Action<IntegerVectorWrapper()> a = Return(v);
|
||||
const std::vector<int>& result = *(a.Perform(make_tuple()).v);
|
||||
EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
|
||||
}
|
||||
|
||||
// Tests that Return(v) is covaraint.
|
||||
|
||||
struct Base {
|
||||
|
@ -518,7 +593,7 @@ TEST(ReturnTest, IsCovariant) {
|
|||
// gmock-actions.h for more information.
|
||||
class FromType {
|
||||
public:
|
||||
FromType(bool* is_converted) : converted_(is_converted) {}
|
||||
explicit FromType(bool* is_converted) : converted_(is_converted) {}
|
||||
bool* converted() const { return converted_; }
|
||||
|
||||
private:
|
||||
|
@ -529,7 +604,8 @@ class FromType {
|
|||
|
||||
class ToType {
|
||||
public:
|
||||
ToType(const FromType& x) { *x.converted() = true; }
|
||||
// Must allow implicit conversion due to use in ImplicitCast_<T>.
|
||||
ToType(const FromType& x) { *x.converted() = true; } // NOLINT
|
||||
};
|
||||
|
||||
TEST(ReturnTest, ConvertsArgumentWhenConverted) {
|
||||
|
@ -541,7 +617,7 @@ TEST(ReturnTest, ConvertsArgumentWhenConverted) {
|
|||
converted = false;
|
||||
action.Perform(tuple<>());
|
||||
EXPECT_FALSE(converted) << "Action must NOT convert its argument "
|
||||
<< "when performed." ;
|
||||
<< "when performed.";
|
||||
}
|
||||
|
||||
class DestinationType {};
|
||||
|
@ -566,6 +642,18 @@ TEST(ReturnNullTest, WorksInPointerReturningFunction) {
|
|||
EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_UNIQUE_PTR_
|
||||
// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
|
||||
// functions.
|
||||
TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
|
||||
const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
|
||||
EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr);
|
||||
|
||||
const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
|
||||
EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr);
|
||||
}
|
||||
#endif // GTEST_HAS_STD_UNIQUE_PTR_
|
||||
|
||||
// Tests that ReturnRef(v) works for reference types.
|
||||
TEST(ReturnRefTest, WorksForReference) {
|
||||
const int n = 0;
|
||||
|
@ -611,14 +699,20 @@ TEST(ReturnRefOfCopyTest, IsCovariant) {
|
|||
|
||||
// Tests that DoDefault() does the default action for the mock method.
|
||||
|
||||
class MyClass {};
|
||||
|
||||
class MockClass {
|
||||
public:
|
||||
MockClass() {}
|
||||
|
||||
MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
|
||||
MOCK_METHOD0(Foo, MyClass());
|
||||
MOCK_METHOD0(Foo, MyNonDefaultConstructible());
|
||||
#if GTEST_HAS_STD_UNIQUE_PTR_
|
||||
MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
|
||||
MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
|
||||
MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
|
||||
MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
|
||||
MOCK_METHOD2(TakeUnique,
|
||||
int(const std::unique_ptr<int>&, std::unique_ptr<int>));
|
||||
#endif
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
|
||||
|
@ -633,15 +727,19 @@ TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
|
|||
EXPECT_EQ(0, mock.IntFunc(true));
|
||||
}
|
||||
|
||||
// Tests that DoDefault() aborts the process when there is no built-in
|
||||
// default value for the return type.
|
||||
// Tests that DoDefault() throws (when exceptions are enabled) or aborts
|
||||
// the process when there is no built-in default value for the return type.
|
||||
TEST(DoDefaultDeathTest, DiesForUnknowType) {
|
||||
MockClass mock;
|
||||
EXPECT_CALL(mock, Foo())
|
||||
.WillRepeatedly(DoDefault());
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
EXPECT_ANY_THROW(mock.Foo());
|
||||
#else
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
mock.Foo();
|
||||
}, "");
|
||||
#endif
|
||||
}
|
||||
|
||||
// Tests that using DoDefault() inside a composite action leads to a
|
||||
|
@ -792,105 +890,6 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
|
|||
# endif
|
||||
}
|
||||
|
||||
#if GTEST_HAS_PROTOBUF_
|
||||
|
||||
// Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
|
||||
// variable pointed to by the N-th (0-based) argument to proto_buffer.
|
||||
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
|
||||
TestMessage* const msg = new TestMessage;
|
||||
msg->set_member("yes");
|
||||
TestMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg);
|
||||
// SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
|
||||
// s.t. the action works even when the original proto_buffer has
|
||||
// died. We ensure this behavior by deleting msg before using the
|
||||
// action.
|
||||
delete msg;
|
||||
|
||||
TestMessage dest;
|
||||
EXPECT_FALSE(orig_msg.Equals(dest));
|
||||
a.Perform(make_tuple(true, &dest));
|
||||
EXPECT_TRUE(orig_msg.Equals(dest));
|
||||
}
|
||||
|
||||
// Tests that SetArgPointee<N>(proto_buffer) sets the
|
||||
// ::ProtocolMessage variable pointed to by the N-th (0-based)
|
||||
// argument to proto_buffer.
|
||||
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
|
||||
TestMessage* const msg = new TestMessage;
|
||||
msg->set_member("yes");
|
||||
TestMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg);
|
||||
// SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
|
||||
// s.t. the action works even when the original proto_buffer has
|
||||
// died. We ensure this behavior by deleting msg before using the
|
||||
// action.
|
||||
delete msg;
|
||||
|
||||
TestMessage dest;
|
||||
::ProtocolMessage* const dest_base = &dest;
|
||||
EXPECT_FALSE(orig_msg.Equals(dest));
|
||||
a.Perform(make_tuple(true, dest_base));
|
||||
EXPECT_TRUE(orig_msg.Equals(dest));
|
||||
}
|
||||
|
||||
// Tests that SetArgPointee<N>(proto2_buffer) sets the v2
|
||||
// protobuf variable pointed to by the N-th (0-based) argument to
|
||||
// proto2_buffer.
|
||||
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
|
||||
using testing::internal::FooMessage;
|
||||
FooMessage* const msg = new FooMessage;
|
||||
msg->set_int_field(2);
|
||||
msg->set_string_field("hi");
|
||||
FooMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg);
|
||||
// SetArgPointee<N>(proto2_buffer) makes a copy of
|
||||
// proto2_buffer s.t. the action works even when the original
|
||||
// proto2_buffer has died. We ensure this behavior by deleting msg
|
||||
// before using the action.
|
||||
delete msg;
|
||||
|
||||
FooMessage dest;
|
||||
dest.set_int_field(0);
|
||||
a.Perform(make_tuple(true, &dest));
|
||||
EXPECT_EQ(2, dest.int_field());
|
||||
EXPECT_EQ("hi", dest.string_field());
|
||||
}
|
||||
|
||||
// Tests that SetArgPointee<N>(proto2_buffer) sets the
|
||||
// proto2::Message variable pointed to by the N-th (0-based) argument
|
||||
// to proto2_buffer.
|
||||
TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
|
||||
using testing::internal::FooMessage;
|
||||
FooMessage* const msg = new FooMessage;
|
||||
msg->set_int_field(2);
|
||||
msg->set_string_field("hi");
|
||||
FooMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg);
|
||||
// SetArgPointee<N>(proto2_buffer) makes a copy of
|
||||
// proto2_buffer s.t. the action works even when the original
|
||||
// proto2_buffer has died. We ensure this behavior by deleting msg
|
||||
// before using the action.
|
||||
delete msg;
|
||||
|
||||
FooMessage dest;
|
||||
dest.set_int_field(0);
|
||||
::proto2::Message* const dest_base = &dest;
|
||||
a.Perform(make_tuple(true, dest_base));
|
||||
EXPECT_EQ(2, dest.int_field());
|
||||
EXPECT_EQ("hi", dest.string_field());
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_PROTOBUF_
|
||||
|
||||
// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
|
||||
// the N-th (0-based) argument to v.
|
||||
TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
|
||||
|
@ -911,105 +910,6 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
|
|||
EXPECT_EQ('a', ch);
|
||||
}
|
||||
|
||||
#if GTEST_HAS_PROTOBUF_
|
||||
|
||||
// Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
|
||||
// variable pointed to by the N-th (0-based) argument to proto_buffer.
|
||||
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
|
||||
TestMessage* const msg = new TestMessage;
|
||||
msg->set_member("yes");
|
||||
TestMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg);
|
||||
// SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
|
||||
// s.t. the action works even when the original proto_buffer has
|
||||
// died. We ensure this behavior by deleting msg before using the
|
||||
// action.
|
||||
delete msg;
|
||||
|
||||
TestMessage dest;
|
||||
EXPECT_FALSE(orig_msg.Equals(dest));
|
||||
a.Perform(make_tuple(true, &dest));
|
||||
EXPECT_TRUE(orig_msg.Equals(dest));
|
||||
}
|
||||
|
||||
// Tests that SetArgumentPointee<N>(proto_buffer) sets the
|
||||
// ::ProtocolMessage variable pointed to by the N-th (0-based)
|
||||
// argument to proto_buffer.
|
||||
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
|
||||
TestMessage* const msg = new TestMessage;
|
||||
msg->set_member("yes");
|
||||
TestMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg);
|
||||
// SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
|
||||
// s.t. the action works even when the original proto_buffer has
|
||||
// died. We ensure this behavior by deleting msg before using the
|
||||
// action.
|
||||
delete msg;
|
||||
|
||||
TestMessage dest;
|
||||
::ProtocolMessage* const dest_base = &dest;
|
||||
EXPECT_FALSE(orig_msg.Equals(dest));
|
||||
a.Perform(make_tuple(true, dest_base));
|
||||
EXPECT_TRUE(orig_msg.Equals(dest));
|
||||
}
|
||||
|
||||
// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
|
||||
// protobuf variable pointed to by the N-th (0-based) argument to
|
||||
// proto2_buffer.
|
||||
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
|
||||
using testing::internal::FooMessage;
|
||||
FooMessage* const msg = new FooMessage;
|
||||
msg->set_int_field(2);
|
||||
msg->set_string_field("hi");
|
||||
FooMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg);
|
||||
// SetArgumentPointee<N>(proto2_buffer) makes a copy of
|
||||
// proto2_buffer s.t. the action works even when the original
|
||||
// proto2_buffer has died. We ensure this behavior by deleting msg
|
||||
// before using the action.
|
||||
delete msg;
|
||||
|
||||
FooMessage dest;
|
||||
dest.set_int_field(0);
|
||||
a.Perform(make_tuple(true, &dest));
|
||||
EXPECT_EQ(2, dest.int_field());
|
||||
EXPECT_EQ("hi", dest.string_field());
|
||||
}
|
||||
|
||||
// Tests that SetArgumentPointee<N>(proto2_buffer) sets the
|
||||
// proto2::Message variable pointed to by the N-th (0-based) argument
|
||||
// to proto2_buffer.
|
||||
TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
|
||||
using testing::internal::FooMessage;
|
||||
FooMessage* const msg = new FooMessage;
|
||||
msg->set_int_field(2);
|
||||
msg->set_string_field("hi");
|
||||
FooMessage orig_msg;
|
||||
orig_msg.CopyFrom(*msg);
|
||||
|
||||
Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg);
|
||||
// SetArgumentPointee<N>(proto2_buffer) makes a copy of
|
||||
// proto2_buffer s.t. the action works even when the original
|
||||
// proto2_buffer has died. We ensure this behavior by deleting msg
|
||||
// before using the action.
|
||||
delete msg;
|
||||
|
||||
FooMessage dest;
|
||||
dest.set_int_field(0);
|
||||
::proto2::Message* const dest_base = &dest;
|
||||
a.Perform(make_tuple(true, dest_base));
|
||||
EXPECT_EQ(2, dest.int_field());
|
||||
EXPECT_EQ("hi", dest.string_field());
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_PROTOBUF_
|
||||
|
||||
// Sample functions and functors for testing Invoke() and etc.
|
||||
int Nullary() { return 1; }
|
||||
|
||||
|
@ -1026,68 +926,12 @@ class VoidNullaryFunctor {
|
|||
void operator()() { g_done = true; }
|
||||
};
|
||||
|
||||
bool Unary(int x) { return x < 0; }
|
||||
|
||||
const char* Plus1(const char* s) { return s + 1; }
|
||||
|
||||
void VoidUnary(int /* n */) { g_done = true; }
|
||||
|
||||
bool ByConstRef(const std::string& s) { return s == "Hi"; }
|
||||
|
||||
const double g_double = 0;
|
||||
bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
|
||||
|
||||
std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT
|
||||
|
||||
struct UnaryFunctor {
|
||||
int operator()(bool x) { return x ? 1 : -1; }
|
||||
};
|
||||
|
||||
const char* Binary(const char* input, short n) { return input + n; } // NOLINT
|
||||
|
||||
void VoidBinary(int, char) { g_done = true; }
|
||||
|
||||
int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
|
||||
|
||||
void VoidTernary(int, char, bool) { g_done = true; }
|
||||
|
||||
int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
|
||||
|
||||
void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; }
|
||||
|
||||
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
|
||||
|
||||
struct SumOf5Functor {
|
||||
int operator()(int a, int b, int c, int d, int e) {
|
||||
return a + b + c + d + e;
|
||||
}
|
||||
};
|
||||
|
||||
int SumOf6(int a, int b, int c, int d, int e, int f) {
|
||||
return a + b + c + d + e + f;
|
||||
}
|
||||
|
||||
struct SumOf6Functor {
|
||||
int operator()(int a, int b, int c, int d, int e, int f) {
|
||||
return a + b + c + d + e + f;
|
||||
}
|
||||
};
|
||||
|
||||
class Foo {
|
||||
public:
|
||||
Foo() : value_(123) {}
|
||||
|
||||
int Nullary() const { return value_; }
|
||||
short Unary(long x) { return static_cast<short>(value_ + x); } // NOLINT
|
||||
std::string Binary(const std::string& str, char c) const { return str + c; }
|
||||
int Ternary(int x, bool y, char z) { return value_ + x + y*z; }
|
||||
int SumOf4(int a, int b, int c, int d) const {
|
||||
return a + b + c + d + value_;
|
||||
}
|
||||
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
|
||||
int SumOf6(int a, int b, int c, int d, int e, int f) {
|
||||
return a + b + c + d + e + f;
|
||||
}
|
||||
|
||||
private:
|
||||
int value_;
|
||||
};
|
||||
|
@ -1157,14 +1001,15 @@ TEST(IgnoreResultTest, MonomorphicAction) {
|
|||
|
||||
// Tests using IgnoreResult() on an action that returns a class type.
|
||||
|
||||
MyClass ReturnMyClass(double /* x */) {
|
||||
MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
|
||||
g_done = true;
|
||||
return MyClass();
|
||||
return MyNonDefaultConstructible(42);
|
||||
}
|
||||
|
||||
TEST(IgnoreResultTest, ActionReturningClass) {
|
||||
g_done = false;
|
||||
Action<void(int)> a = IgnoreResult(Invoke(ReturnMyClass)); // NOLINT
|
||||
Action<void(int)> a =
|
||||
IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
|
||||
a.Perform(make_tuple(2));
|
||||
EXPECT_TRUE(g_done);
|
||||
}
|
||||
|
@ -1226,7 +1071,8 @@ TEST(ByRefTest, IsCopyable) {
|
|||
const std::string s1 = "Hi";
|
||||
const std::string s2 = "Hello";
|
||||
|
||||
::testing::internal::ReferenceWrapper<const std::string> ref_wrapper = ByRef(s1);
|
||||
::testing::internal::ReferenceWrapper<const std::string> ref_wrapper =
|
||||
ByRef(s1);
|
||||
const std::string& r1 = ref_wrapper;
|
||||
EXPECT_EQ(&s1, &r1);
|
||||
|
||||
|
@ -1235,7 +1081,8 @@ TEST(ByRefTest, IsCopyable) {
|
|||
const std::string& r2 = ref_wrapper;
|
||||
EXPECT_EQ(&s2, &r2);
|
||||
|
||||
::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 = ByRef(s1);
|
||||
::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 =
|
||||
ByRef(s1);
|
||||
// Copies ref_wrapper1 to ref_wrapper.
|
||||
ref_wrapper = ref_wrapper1;
|
||||
const std::string& r3 = ref_wrapper;
|
||||
|
@ -1302,4 +1149,224 @@ TEST(ByRefTest, PrintsCorrectly) {
|
|||
EXPECT_EQ(expected.str(), actual.str());
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_UNIQUE_PTR_
|
||||
|
||||
std::unique_ptr<int> UniquePtrSource() {
|
||||
return std::unique_ptr<int>(new int(19));
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
|
||||
std::vector<std::unique_ptr<int>> out;
|
||||
out.emplace_back(new int(7));
|
||||
return out;
|
||||
}
|
||||
|
||||
TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
|
||||
MockClass mock;
|
||||
std::unique_ptr<int> i(new int(19));
|
||||
EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
|
||||
EXPECT_CALL(mock, MakeVectorUnique())
|
||||
.WillOnce(Return(ByMove(VectorUniquePtrSource())));
|
||||
Derived* d = new Derived;
|
||||
EXPECT_CALL(mock, MakeUniqueBase())
|
||||
.WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
|
||||
|
||||
std::unique_ptr<int> result1 = mock.MakeUnique();
|
||||
EXPECT_EQ(19, *result1);
|
||||
|
||||
std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
|
||||
EXPECT_EQ(1u, vresult.size());
|
||||
EXPECT_NE(nullptr, vresult[0]);
|
||||
EXPECT_EQ(7, *vresult[0]);
|
||||
|
||||
std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
|
||||
EXPECT_EQ(d, result2.get());
|
||||
}
|
||||
|
||||
TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
|
||||
testing::MockFunction<void()> mock_function;
|
||||
MockClass mock;
|
||||
std::unique_ptr<int> i(new int(19));
|
||||
EXPECT_CALL(mock_function, Call());
|
||||
EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
|
||||
InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
|
||||
Return(ByMove(std::move(i)))));
|
||||
|
||||
std::unique_ptr<int> result1 = mock.MakeUnique();
|
||||
EXPECT_EQ(19, *result1);
|
||||
}
|
||||
|
||||
TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
|
||||
MockClass mock;
|
||||
|
||||
// Check default value
|
||||
DefaultValue<std::unique_ptr<int>>::SetFactory([] {
|
||||
return std::unique_ptr<int>(new int(42));
|
||||
});
|
||||
EXPECT_EQ(42, *mock.MakeUnique());
|
||||
|
||||
EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
|
||||
EXPECT_CALL(mock, MakeVectorUnique())
|
||||
.WillRepeatedly(Invoke(VectorUniquePtrSource));
|
||||
std::unique_ptr<int> result1 = mock.MakeUnique();
|
||||
EXPECT_EQ(19, *result1);
|
||||
std::unique_ptr<int> result2 = mock.MakeUnique();
|
||||
EXPECT_EQ(19, *result2);
|
||||
EXPECT_NE(result1, result2);
|
||||
|
||||
std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
|
||||
EXPECT_EQ(1u, vresult.size());
|
||||
EXPECT_NE(nullptr, vresult[0]);
|
||||
EXPECT_EQ(7, *vresult[0]);
|
||||
}
|
||||
|
||||
TEST(MockMethodTest, CanTakeMoveOnlyValue) {
|
||||
MockClass mock;
|
||||
auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
|
||||
|
||||
EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
|
||||
return *i;
|
||||
});
|
||||
// DoAll() does not compile, since it would move from its arguments twice.
|
||||
// EXPECT_CALL(mock, TakeUnique(_, _))
|
||||
// .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
|
||||
// Return(1)));
|
||||
EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
|
||||
.WillOnce(Return(-7))
|
||||
.RetiresOnSaturation();
|
||||
EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
|
||||
.WillOnce(Return(-1))
|
||||
.RetiresOnSaturation();
|
||||
|
||||
EXPECT_EQ(5, mock.TakeUnique(make(5)));
|
||||
EXPECT_EQ(-7, mock.TakeUnique(make(7)));
|
||||
EXPECT_EQ(7, mock.TakeUnique(make(7)));
|
||||
EXPECT_EQ(7, mock.TakeUnique(make(7)));
|
||||
EXPECT_EQ(-1, mock.TakeUnique({}));
|
||||
|
||||
// Some arguments are moved, some passed by reference.
|
||||
auto lvalue = make(6);
|
||||
EXPECT_CALL(mock, TakeUnique(_, _))
|
||||
.WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
|
||||
return *i * *j;
|
||||
});
|
||||
EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
|
||||
|
||||
// The unique_ptr can be saved by the action.
|
||||
std::unique_ptr<int> saved;
|
||||
EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
|
||||
saved = std::move(i);
|
||||
return 0;
|
||||
});
|
||||
EXPECT_EQ(0, mock.TakeUnique(make(42)));
|
||||
EXPECT_EQ(42, *saved);
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_STD_UNIQUE_PTR_
|
||||
|
||||
#if GTEST_LANG_CXX11
|
||||
// Tests for std::function based action.
|
||||
|
||||
int Add(int val, int& ref, int* ptr) { // NOLINT
|
||||
int result = val + ref + *ptr;
|
||||
ref = 42;
|
||||
*ptr = 43;
|
||||
return result;
|
||||
}
|
||||
|
||||
int Deref(std::unique_ptr<int> ptr) { return *ptr; }
|
||||
|
||||
struct Double {
|
||||
template <typename T>
|
||||
T operator()(T t) { return 2 * t; }
|
||||
};
|
||||
|
||||
std::unique_ptr<int> UniqueInt(int i) {
|
||||
return std::unique_ptr<int>(new int(i));
|
||||
}
|
||||
|
||||
TEST(FunctorActionTest, ActionFromFunction) {
|
||||
Action<int(int, int&, int*)> a = &Add;
|
||||
int x = 1, y = 2, z = 3;
|
||||
EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
|
||||
EXPECT_EQ(42, y);
|
||||
EXPECT_EQ(43, z);
|
||||
|
||||
Action<int(std::unique_ptr<int>)> a1 = &Deref;
|
||||
EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
|
||||
}
|
||||
|
||||
TEST(FunctorActionTest, ActionFromLambda) {
|
||||
Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
|
||||
EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
|
||||
EXPECT_EQ(0, a1.Perform(make_tuple(false, 5)));
|
||||
|
||||
std::unique_ptr<int> saved;
|
||||
Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
|
||||
saved = std::move(p);
|
||||
};
|
||||
a2.Perform(make_tuple(UniqueInt(5)));
|
||||
EXPECT_EQ(5, *saved);
|
||||
}
|
||||
|
||||
TEST(FunctorActionTest, PolymorphicFunctor) {
|
||||
Action<int(int)> ai = Double();
|
||||
EXPECT_EQ(2, ai.Perform(make_tuple(1)));
|
||||
Action<double(double)> ad = Double(); // Double? Double double!
|
||||
EXPECT_EQ(3.0, ad.Perform(make_tuple(1.5)));
|
||||
}
|
||||
|
||||
TEST(FunctorActionTest, TypeConversion) {
|
||||
// Numeric promotions are allowed.
|
||||
const Action<bool(int)> a1 = [](int i) { return i > 1; };
|
||||
const Action<int(bool)> a2 = Action<int(bool)>(a1);
|
||||
EXPECT_EQ(1, a1.Perform(make_tuple(42)));
|
||||
EXPECT_EQ(0, a2.Perform(make_tuple(42)));
|
||||
|
||||
// Implicit constructors are allowed.
|
||||
const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
|
||||
const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
|
||||
EXPECT_EQ(0, s2.Perform(make_tuple("")));
|
||||
EXPECT_EQ(1, s2.Perform(make_tuple("hello")));
|
||||
|
||||
// Also between the lambda and the action itself.
|
||||
const Action<bool(std::string)> x = [](Unused) { return 42; };
|
||||
EXPECT_TRUE(x.Perform(make_tuple("hello")));
|
||||
}
|
||||
|
||||
TEST(FunctorActionTest, UnusedArguments) {
|
||||
// Verify that users can ignore uninteresting arguments.
|
||||
Action<int(int, double y, double z)> a =
|
||||
[](int i, Unused, Unused) { return 2 * i; };
|
||||
tuple<int, double, double> dummy = make_tuple(3, 7.3, 9.44);
|
||||
EXPECT_EQ(6, a.Perform(dummy));
|
||||
}
|
||||
|
||||
// Test that basic built-in actions work with move-only arguments.
|
||||
// FIXME: Currently, almost all ActionInterface-based actions will not
|
||||
// work, even if they only try to use other, copyable arguments. Implement them
|
||||
// if necessary (but note that DoAll cannot work on non-copyable types anyway -
|
||||
// so maybe it's better to make users use lambdas instead.
|
||||
TEST(MoveOnlyArgumentsTest, ReturningActions) {
|
||||
Action<int(std::unique_ptr<int>)> a = Return(1);
|
||||
EXPECT_EQ(1, a.Perform(make_tuple(nullptr)));
|
||||
|
||||
a = testing::WithoutArgs([]() { return 7; });
|
||||
EXPECT_EQ(7, a.Perform(make_tuple(nullptr)));
|
||||
|
||||
Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
|
||||
int x = 0;
|
||||
a2.Perform(make_tuple(nullptr, &x));
|
||||
EXPECT_EQ(x, 3);
|
||||
}
|
||||
|
||||
#endif // GTEST_LANG_CXX11
|
||||
|
||||
} // Unnamed namespace
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#if _MSC_VER == 1900
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -391,7 +390,7 @@ TEST(ExactlyTest, HasCorrectBounds) {
|
|||
EXPECT_EQ(3, c.ConservativeUpperBound());
|
||||
}
|
||||
|
||||
// Tests that a user can make his own cardinality by implementing
|
||||
// Tests that a user can make their own cardinality by implementing
|
||||
// CardinalityInterface and calling MakeCardinality().
|
||||
|
||||
class EvenCardinality : public CardinalityInterface {
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -46,10 +45,10 @@ namespace gmock_generated_actions_test {
|
|||
|
||||
using ::std::plus;
|
||||
using ::std::string;
|
||||
using ::std::tr1::get;
|
||||
using ::std::tr1::make_tuple;
|
||||
using ::std::tr1::tuple;
|
||||
using ::std::tr1::tuple_element;
|
||||
using testing::get;
|
||||
using testing::make_tuple;
|
||||
using testing::tuple;
|
||||
using testing::tuple_element;
|
||||
using testing::_;
|
||||
using testing::Action;
|
||||
using testing::ActionInterface;
|
||||
|
@ -81,12 +80,12 @@ bool Unary(int x) { return x < 0; }
|
|||
|
||||
const char* Plus1(const char* s) { return s + 1; }
|
||||
|
||||
bool ByConstRef(const string& s) { return s == "Hi"; }
|
||||
bool ByConstRef(const std::string& s) { return s == "Hi"; }
|
||||
|
||||
const double g_double = 0;
|
||||
bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
|
||||
|
||||
string ByNonConstRef(string& s) { return s += "+"; } // NOLINT
|
||||
std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT
|
||||
|
||||
struct UnaryFunctor {
|
||||
int operator()(bool x) { return x ? 1 : -1; }
|
||||
|
@ -102,9 +101,9 @@ void VoidTernary(int, char, bool) { g_done = true; }
|
|||
|
||||
int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
|
||||
|
||||
string Concat4(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4) {
|
||||
return string(s1) + s2 + s3 + s4;
|
||||
std::string Concat4(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4) {
|
||||
return std::string(s1) + s2 + s3 + s4;
|
||||
}
|
||||
|
||||
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
|
||||
|
@ -115,9 +114,9 @@ struct SumOf5Functor {
|
|||
}
|
||||
};
|
||||
|
||||
string Concat5(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5) {
|
||||
return string(s1) + s2 + s3 + s4 + s5;
|
||||
std::string Concat5(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5;
|
||||
}
|
||||
|
||||
int SumOf6(int a, int b, int c, int d, int e, int f) {
|
||||
|
@ -130,34 +129,34 @@ struct SumOf6Functor {
|
|||
}
|
||||
};
|
||||
|
||||
string Concat6(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6;
|
||||
std::string Concat6(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6;
|
||||
}
|
||||
|
||||
string Concat7(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
|
||||
std::string Concat7(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
|
||||
}
|
||||
|
||||
string Concat8(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
|
||||
std::string Concat8(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
|
||||
}
|
||||
|
||||
string Concat9(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
|
||||
std::string Concat9(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
|
||||
}
|
||||
|
||||
string Concat10(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9,
|
||||
const char* s10) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
|
||||
std::string Concat10(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9,
|
||||
const char* s10) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
|
||||
}
|
||||
|
||||
// A helper that turns the type of a C-string literal from const
|
||||
|
@ -208,38 +207,37 @@ TEST(InvokeArgumentTest, Functor6) {
|
|||
|
||||
// Tests using InvokeArgument with a 7-ary function.
|
||||
TEST(InvokeArgumentTest, Function7) {
|
||||
Action<string(string(*)(const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*))> a =
|
||||
InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
|
||||
Action<std::string(std::string(*)(const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*))>
|
||||
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7");
|
||||
EXPECT_EQ("1234567", a.Perform(make_tuple(&Concat7)));
|
||||
}
|
||||
|
||||
// Tests using InvokeArgument with a 8-ary function.
|
||||
TEST(InvokeArgumentTest, Function8) {
|
||||
Action<string(string(*)(const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*, const char*))> a =
|
||||
InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
|
||||
Action<std::string(std::string(*)(const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*, const char*))>
|
||||
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8");
|
||||
EXPECT_EQ("12345678", a.Perform(make_tuple(&Concat8)));
|
||||
}
|
||||
|
||||
// Tests using InvokeArgument with a 9-ary function.
|
||||
TEST(InvokeArgumentTest, Function9) {
|
||||
Action<string(string(*)(const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*, const char*, const char*))> a =
|
||||
InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
|
||||
Action<std::string(std::string(*)(const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*, const char*, const char*))>
|
||||
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9");
|
||||
EXPECT_EQ("123456789", a.Perform(make_tuple(&Concat9)));
|
||||
}
|
||||
|
||||
// Tests using InvokeArgument with a 10-ary function.
|
||||
TEST(InvokeArgumentTest, Function10) {
|
||||
Action<string(string(*)(const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*, const char*, const char*,
|
||||
const char*))> a =
|
||||
InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
|
||||
Action<std::string(std::string(*)(
|
||||
const char*, const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*, const char*))>
|
||||
a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
|
||||
EXPECT_EQ("1234567890", a.Perform(make_tuple(&Concat10)));
|
||||
}
|
||||
|
||||
|
@ -260,8 +258,8 @@ TEST(InvokeArgumentTest, FunctionWithCStringLiteral) {
|
|||
|
||||
// Tests using InvokeArgument with a function that takes a const reference.
|
||||
TEST(InvokeArgumentTest, ByConstReferenceFunction) {
|
||||
Action<bool(bool(*function)(const string& s))> a = // NOLINT
|
||||
InvokeArgument<0>(string("Hi"));
|
||||
Action<bool(bool (*function)(const std::string& s))> a = // NOLINT
|
||||
InvokeArgument<0>(std::string("Hi"));
|
||||
// When action 'a' is constructed, it makes a copy of the temporary
|
||||
// string object passed to it, so it's OK to use 'a' later, when the
|
||||
// temporary object has already died.
|
||||
|
@ -305,17 +303,18 @@ TEST(WithArgsTest, ThreeArgs) {
|
|||
|
||||
// Tests using WithArgs with an action that takes 4 arguments.
|
||||
TEST(WithArgsTest, FourArgs) {
|
||||
Action<string(const char*, const char*, double, const char*, const char*)> a =
|
||||
WithArgs<4, 3, 1, 0>(Invoke(Concat4));
|
||||
Action<std::string(const char*, const char*, double, const char*,
|
||||
const char*)>
|
||||
a = WithArgs<4, 3, 1, 0>(Invoke(Concat4));
|
||||
EXPECT_EQ("4310", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), 2.5,
|
||||
CharPtr("3"), CharPtr("4"))));
|
||||
}
|
||||
|
||||
// Tests using WithArgs with an action that takes 5 arguments.
|
||||
TEST(WithArgsTest, FiveArgs) {
|
||||
Action<string(const char*, const char*, const char*,
|
||||
const char*, const char*)> a =
|
||||
WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5));
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*)>
|
||||
a = WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5));
|
||||
EXPECT_EQ("43210",
|
||||
a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
|
||||
CharPtr("3"), CharPtr("4"))));
|
||||
|
@ -323,7 +322,7 @@ TEST(WithArgsTest, FiveArgs) {
|
|||
|
||||
// Tests using WithArgs with an action that takes 6 arguments.
|
||||
TEST(WithArgsTest, SixArgs) {
|
||||
Action<string(const char*, const char*, const char*)> a =
|
||||
Action<std::string(const char*, const char*, const char*)> a =
|
||||
WithArgs<0, 1, 2, 2, 1, 0>(Invoke(Concat6));
|
||||
EXPECT_EQ("012210",
|
||||
a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"))));
|
||||
|
@ -331,7 +330,7 @@ TEST(WithArgsTest, SixArgs) {
|
|||
|
||||
// Tests using WithArgs with an action that takes 7 arguments.
|
||||
TEST(WithArgsTest, SevenArgs) {
|
||||
Action<string(const char*, const char*, const char*, const char*)> a =
|
||||
Action<std::string(const char*, const char*, const char*, const char*)> a =
|
||||
WithArgs<0, 1, 2, 3, 2, 1, 0>(Invoke(Concat7));
|
||||
EXPECT_EQ("0123210",
|
||||
a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
|
||||
|
@ -340,7 +339,7 @@ TEST(WithArgsTest, SevenArgs) {
|
|||
|
||||
// Tests using WithArgs with an action that takes 8 arguments.
|
||||
TEST(WithArgsTest, EightArgs) {
|
||||
Action<string(const char*, const char*, const char*, const char*)> a =
|
||||
Action<std::string(const char*, const char*, const char*, const char*)> a =
|
||||
WithArgs<0, 1, 2, 3, 0, 1, 2, 3>(Invoke(Concat8));
|
||||
EXPECT_EQ("01230123",
|
||||
a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
|
||||
|
@ -349,7 +348,7 @@ TEST(WithArgsTest, EightArgs) {
|
|||
|
||||
// Tests using WithArgs with an action that takes 9 arguments.
|
||||
TEST(WithArgsTest, NineArgs) {
|
||||
Action<string(const char*, const char*, const char*, const char*)> a =
|
||||
Action<std::string(const char*, const char*, const char*, const char*)> a =
|
||||
WithArgs<0, 1, 2, 3, 1, 2, 3, 2, 3>(Invoke(Concat9));
|
||||
EXPECT_EQ("012312323",
|
||||
a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
|
||||
|
@ -358,7 +357,7 @@ TEST(WithArgsTest, NineArgs) {
|
|||
|
||||
// Tests using WithArgs with an action that takes 10 arguments.
|
||||
TEST(WithArgsTest, TenArgs) {
|
||||
Action<string(const char*, const char*, const char*, const char*)> a =
|
||||
Action<std::string(const char*, const char*, const char*, const char*)> a =
|
||||
WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(Concat10));
|
||||
EXPECT_EQ("0123210123",
|
||||
a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
|
||||
|
@ -374,9 +373,10 @@ class SubstractAction : public ActionInterface<int(int, int)> { // NOLINT
|
|||
};
|
||||
|
||||
TEST(WithArgsTest, NonInvokeAction) {
|
||||
Action<int(const string&, int, int)> a = // NOLINT
|
||||
Action<int(const std::string&, int, int)> a = // NOLINT
|
||||
WithArgs<2, 1>(MakeAction(new SubstractAction));
|
||||
EXPECT_EQ(8, a.Perform(make_tuple(CharPtr("hi"), 2, 10)));
|
||||
tuple<std::string, int, int> dummy = make_tuple(std::string("hi"), 2, 10);
|
||||
EXPECT_EQ(8, a.Perform(dummy));
|
||||
}
|
||||
|
||||
// Tests using WithArgs to pass all original arguments in the original order.
|
||||
|
@ -639,7 +639,7 @@ TEST(ActionMacroTest, CanReferenceArgumentType) {
|
|||
// Tests that the body of ACTION() can reference the argument tuple
|
||||
// via args_type and args.
|
||||
ACTION(Sum2) {
|
||||
StaticAssertTypeEq< ::std::tr1::tuple<int, char, int*>, args_type>();
|
||||
StaticAssertTypeEq<tuple<int, char, int*>, args_type>();
|
||||
args_type args_copy = args;
|
||||
return get<0>(args_copy) + get<1>(args_copy);
|
||||
}
|
||||
|
@ -753,7 +753,8 @@ TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {
|
|||
TEST(ActionPMacroTest, WorksInCompatibleMockFunction) {
|
||||
Action<std::string(const std::string& s)> a1 = Plus("tail");
|
||||
const std::string re = "re";
|
||||
EXPECT_EQ("retail", a1.Perform(make_tuple(re)));
|
||||
tuple<const std::string> dummy = make_tuple(re);
|
||||
EXPECT_EQ("retail", a1.Perform(dummy));
|
||||
}
|
||||
|
||||
// Tests that we can use ACTION*() to define actions overloaded on the
|
||||
|
@ -795,7 +796,8 @@ TEST(ActionPnMacroTest, WorksFor3Parameters) {
|
|||
|
||||
Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">");
|
||||
const std::string re = "re";
|
||||
EXPECT_EQ("retail->", a2.Perform(make_tuple(re)));
|
||||
tuple<const std::string> dummy = make_tuple(re);
|
||||
EXPECT_EQ("retail->", a2.Perform(dummy));
|
||||
}
|
||||
|
||||
ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }
|
||||
|
@ -900,7 +902,9 @@ template <typename T1, typename T2>
|
|||
// pattern requires the user to use it directly.
|
||||
ConcatImplActionP3<std::string, T1, T2>
|
||||
Concat(const std::string& a, T1 b, T2 c) {
|
||||
GTEST_INTENTIONAL_CONST_COND_PUSH_()
|
||||
if (true) {
|
||||
GTEST_INTENTIONAL_CONST_COND_POP_()
|
||||
// This branch verifies that ConcatImpl() can be invoked without
|
||||
// explicit template arguments.
|
||||
return ConcatImpl(a, b, c);
|
||||
|
@ -956,6 +960,19 @@ TEST(ActionPnMacroTest, TypesAreCorrect) {
|
|||
Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');
|
||||
PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =
|
||||
Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
|
||||
|
||||
// Avoid "unused variable" warnings.
|
||||
(void)a0;
|
||||
(void)a1;
|
||||
(void)a2;
|
||||
(void)a3;
|
||||
(void)a4;
|
||||
(void)a5;
|
||||
(void)a6;
|
||||
(void)a7;
|
||||
(void)a8;
|
||||
(void)a9;
|
||||
(void)a10;
|
||||
}
|
||||
|
||||
// Tests that an ACTION_P*() action can be explicitly instantiated
|
||||
|
@ -1083,7 +1100,7 @@ TEST(ActionTemplateTest, WorksWithValueParams) {
|
|||
ACTION_TEMPLATE(MyDeleteArg,
|
||||
HAS_1_TEMPLATE_PARAMS(int, k),
|
||||
AND_0_VALUE_PARAMS()) {
|
||||
delete std::tr1::get<k>(args);
|
||||
delete get<k>(args);
|
||||
}
|
||||
|
||||
// Resets a bool variable in the destructor.
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -35,11 +34,6 @@
|
|||
|
||||
#include "gmock/gmock-generated-function-mockers.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but
|
||||
// we are getting compiler errors if we use basetyps.h, hence including
|
||||
|
@ -47,6 +41,11 @@
|
|||
# include <objbase.h>
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
// There is a bug in MSVC (fixed in VS 2008) that prevents creating a
|
||||
// mock for a function with const arguments, so we don't test such
|
||||
// cases for MSVC versions older than 2008.
|
||||
|
@ -57,7 +56,6 @@
|
|||
namespace testing {
|
||||
namespace gmock_generated_function_mockers_test {
|
||||
|
||||
using testing::internal::string;
|
||||
using testing::_;
|
||||
using testing::A;
|
||||
using testing::An;
|
||||
|
@ -82,11 +80,11 @@ class FooInterface {
|
|||
virtual bool Unary(int x) = 0;
|
||||
virtual long Binary(short x, int y) = 0; // NOLINT
|
||||
virtual int Decimal(bool b, char c, short d, int e, long f, // NOLINT
|
||||
float g, double h, unsigned i, char* j, const string& k)
|
||||
= 0;
|
||||
float g, double h, unsigned i, char* j,
|
||||
const std::string& k) = 0;
|
||||
|
||||
virtual bool TakesNonConstReference(int& n) = 0; // NOLINT
|
||||
virtual string TakesConstReference(const int& n) = 0;
|
||||
virtual std::string TakesConstReference(const int& n) = 0;
|
||||
#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
|
||||
virtual bool TakesConst(const int x) = 0;
|
||||
#endif // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
|
||||
|
@ -101,17 +99,26 @@ class FooInterface {
|
|||
virtual char OverloadedOnConstness() const = 0;
|
||||
|
||||
virtual int TypeWithHole(int (*func)()) = 0;
|
||||
virtual int TypeWithComma(const std::map<int, string>& a_map) = 0;
|
||||
virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
STDMETHOD_(int, CTNullary)() = 0;
|
||||
STDMETHOD_(bool, CTUnary)(int x) = 0;
|
||||
STDMETHOD_(int, CTDecimal)(bool b, char c, short d, int e, long f, // NOLINT
|
||||
float g, double h, unsigned i, char* j, const string& k) = 0;
|
||||
STDMETHOD_(int, CTDecimal)
|
||||
(bool b, char c, short d, int e, long f, // NOLINT
|
||||
float g, double h, unsigned i, char* j, const std::string& k) = 0;
|
||||
STDMETHOD_(char, CTConst)(int x) const = 0;
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
};
|
||||
|
||||
// Const qualifiers on arguments were once (incorrectly) considered
|
||||
// significant in determining whether two virtual functions had the same
|
||||
// signature. This was fixed in Visual Studio 2008. However, the compiler
|
||||
// still emits a warning that alerts about this change in behavior.
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable : 4373)
|
||||
#endif
|
||||
class MockFoo : public FooInterface {
|
||||
public:
|
||||
MockFoo() {}
|
||||
|
@ -125,13 +132,20 @@ class MockFoo : public FooInterface {
|
|||
MOCK_METHOD1(Unary, bool(int)); // NOLINT
|
||||
MOCK_METHOD2(Binary, long(short, int)); // NOLINT
|
||||
MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float, // NOLINT
|
||||
double, unsigned, char*, const string& str));
|
||||
double, unsigned, char*, const std::string& str));
|
||||
|
||||
MOCK_METHOD1(TakesNonConstReference, bool(int&)); // NOLINT
|
||||
MOCK_METHOD1(TakesConstReference, string(const int&));
|
||||
MOCK_METHOD1(TakesConstReference, std::string(const int&));
|
||||
|
||||
#ifdef GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
|
||||
MOCK_METHOD1(TakesConst, bool(const int)); // NOLINT
|
||||
#endif // GMOCK_ALLOWS_CONST_PARAM_FUNCTIONS
|
||||
#endif
|
||||
|
||||
// Tests that the function return type can contain unprotected comma.
|
||||
MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());
|
||||
MOCK_CONST_METHOD1(ReturnTypeWithComma,
|
||||
std::map<int, std::string>(int)); // NOLINT
|
||||
|
||||
MOCK_METHOD0(OverloadedOnArgumentNumber, int()); // NOLINT
|
||||
MOCK_METHOD1(OverloadedOnArgumentNumber, int(int)); // NOLINT
|
||||
|
||||
|
@ -142,19 +156,29 @@ class MockFoo : public FooInterface {
|
|||
MOCK_CONST_METHOD0(OverloadedOnConstness, char()); // NOLINT
|
||||
|
||||
MOCK_METHOD1(TypeWithHole, int(int (*)())); // NOLINT
|
||||
MOCK_METHOD1(TypeWithComma, int(const std::map<int, string>&)); // NOLINT
|
||||
MOCK_METHOD1(TypeWithComma,
|
||||
int(const std::map<int, std::string>&)); // NOLINT
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());
|
||||
MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int));
|
||||
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal, int(bool b, char c,
|
||||
short d, int e, long f, float g, double h, unsigned i, char* j,
|
||||
const string& k));
|
||||
MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,
|
||||
int(bool b, char c, short d, int e, long f,
|
||||
float g, double h, unsigned i, char* j,
|
||||
const std::string& k));
|
||||
MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst, char(int));
|
||||
|
||||
// Tests that the function return type can contain unprotected comma.
|
||||
MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,
|
||||
std::map<int, std::string>());
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
|
||||
};
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
class FunctionMockerTest : public testing::Test {
|
||||
protected:
|
||||
|
@ -267,6 +291,17 @@ TEST_F(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {
|
|||
EXPECT_EQ('a', Const(*foo_).OverloadedOnConstness());
|
||||
}
|
||||
|
||||
TEST_F(FunctionMockerTest, MocksReturnTypeWithComma) {
|
||||
const std::map<int, std::string> a_map;
|
||||
EXPECT_CALL(mock_foo_, ReturnTypeWithComma())
|
||||
.WillOnce(Return(a_map));
|
||||
EXPECT_CALL(mock_foo_, ReturnTypeWithComma(42))
|
||||
.WillOnce(Return(a_map));
|
||||
|
||||
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma());
|
||||
EXPECT_EQ(a_map, mock_foo_.ReturnTypeWithComma(42));
|
||||
}
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
// Tests mocking a nullary function with calltype.
|
||||
TEST_F(FunctionMockerTest, MocksNullaryFunctionWithCallType) {
|
||||
|
@ -306,6 +341,14 @@ TEST_F(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {
|
|||
EXPECT_EQ('a', Const(*foo_).CTConst(0));
|
||||
}
|
||||
|
||||
TEST_F(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {
|
||||
const std::map<int, std::string> a_map;
|
||||
EXPECT_CALL(mock_foo_, CTReturnTypeWithComma())
|
||||
.WillOnce(Return(a_map));
|
||||
|
||||
EXPECT_EQ(a_map, mock_foo_.CTReturnTypeWithComma());
|
||||
}
|
||||
|
||||
#endif // GTEST_OS_WINDOWS
|
||||
|
||||
class MockB {
|
||||
|
@ -362,6 +405,10 @@ class MockStack : public StackInterface<T> {
|
|||
MOCK_CONST_METHOD0_T(GetSize, int()); // NOLINT
|
||||
MOCK_CONST_METHOD0_T(GetTop, const T&());
|
||||
|
||||
// Tests that the function return type can contain unprotected comma.
|
||||
MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());
|
||||
MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int)); // NOLINT
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockStack);
|
||||
};
|
||||
|
@ -389,6 +436,19 @@ TEST(TemplateMockTest, Works) {
|
|||
EXPECT_EQ(0, mock.GetSize());
|
||||
}
|
||||
|
||||
TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {
|
||||
MockStack<int> mock;
|
||||
|
||||
const std::map<int, int> a_map;
|
||||
EXPECT_CALL(mock, ReturnTypeWithComma())
|
||||
.WillOnce(Return(a_map));
|
||||
EXPECT_CALL(mock, ReturnTypeWithComma(1))
|
||||
.WillOnce(Return(a_map));
|
||||
|
||||
EXPECT_EQ(a_map, mock.ReturnTypeWithComma());
|
||||
EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));
|
||||
}
|
||||
|
||||
#if GTEST_OS_WINDOWS
|
||||
// Tests mocking template interfaces with calltype.
|
||||
|
||||
|
@ -536,5 +596,51 @@ TEST(MockFunctionTest, WorksFor10Arguments) {
|
|||
EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_FUNCTION_
|
||||
TEST(MockFunctionTest, AsStdFunction) {
|
||||
MockFunction<int(int)> foo;
|
||||
auto call = [](const std::function<int(int)> &f, int i) {
|
||||
return f(i);
|
||||
};
|
||||
EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));
|
||||
EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));
|
||||
EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));
|
||||
EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));
|
||||
}
|
||||
|
||||
TEST(MockFunctionTest, AsStdFunctionReturnsReference) {
|
||||
MockFunction<int&()> foo;
|
||||
int value = 1;
|
||||
EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));
|
||||
int& ref = foo.AsStdFunction()();
|
||||
EXPECT_EQ(1, ref);
|
||||
value = 2;
|
||||
EXPECT_EQ(2, ref);
|
||||
}
|
||||
#endif // GTEST_HAS_STD_FUNCTION_
|
||||
|
||||
struct MockMethodSizes0 {
|
||||
MOCK_METHOD0(func, void());
|
||||
};
|
||||
struct MockMethodSizes1 {
|
||||
MOCK_METHOD1(func, void(int));
|
||||
};
|
||||
struct MockMethodSizes2 {
|
||||
MOCK_METHOD2(func, void(int, int));
|
||||
};
|
||||
struct MockMethodSizes3 {
|
||||
MOCK_METHOD3(func, void(int, int, int));
|
||||
};
|
||||
struct MockMethodSizes4 {
|
||||
MOCK_METHOD4(func, void(int, int, int, int));
|
||||
};
|
||||
|
||||
TEST(MockFunctionTest, MockMethodSizeOverhead) {
|
||||
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));
|
||||
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));
|
||||
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));
|
||||
EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));
|
||||
}
|
||||
|
||||
} // namespace gmock_generated_function_mockers_test
|
||||
} // namespace testing
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -39,7 +38,7 @@
|
|||
|
||||
namespace {
|
||||
|
||||
using ::std::tr1::tuple;
|
||||
using ::testing::tuple;
|
||||
using ::testing::Matcher;
|
||||
using ::testing::internal::CompileAssertTypesEqual;
|
||||
using ::testing::internal::MatcherTuple;
|
||||
|
@ -63,10 +62,10 @@ TEST(MatcherTupleTest, ForSize2) {
|
|||
}
|
||||
|
||||
TEST(MatcherTupleTest, ForSize5) {
|
||||
CompileAssertTypesEqual<tuple<Matcher<int>, Matcher<char>, Matcher<bool>,
|
||||
Matcher<double>, Matcher<char*> >,
|
||||
MatcherTuple<tuple<int, char, bool, double, char*>
|
||||
>::type>();
|
||||
CompileAssertTypesEqual<
|
||||
tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<double>,
|
||||
Matcher<char*> >,
|
||||
MatcherTuple<tuple<int, char, bool, double, char*> >::type>();
|
||||
}
|
||||
|
||||
// Tests the Function template struct.
|
||||
|
@ -97,8 +96,9 @@ TEST(FunctionTest, Binary) {
|
|||
CompileAssertTypesEqual<bool, F::Argument1>();
|
||||
CompileAssertTypesEqual<const long&, F::Argument2>(); // NOLINT
|
||||
CompileAssertTypesEqual<tuple<bool, const long&>, F::ArgumentTuple>(); // NOLINT
|
||||
CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT
|
||||
F::ArgumentMatcherTuple>();
|
||||
CompileAssertTypesEqual<
|
||||
tuple<Matcher<bool>, Matcher<const long&> >, // NOLINT
|
||||
F::ArgumentMatcherTuple>();
|
||||
CompileAssertTypesEqual<void(bool, const long&), F::MakeResultVoid>(); // NOLINT
|
||||
CompileAssertTypesEqual<IgnoredValue(bool, const long&), // NOLINT
|
||||
F::MakeResultIgnoredValue>();
|
||||
|
@ -114,9 +114,10 @@ TEST(FunctionTest, LongArgumentList) {
|
|||
CompileAssertTypesEqual<const long&, F::Argument5>(); // NOLINT
|
||||
CompileAssertTypesEqual<tuple<bool, int, char*, int&, const long&>, // NOLINT
|
||||
F::ArgumentTuple>();
|
||||
CompileAssertTypesEqual<tuple<Matcher<bool>, Matcher<int>, Matcher<char*>,
|
||||
Matcher<int&>, Matcher<const long&> >, // NOLINT
|
||||
F::ArgumentMatcherTuple>();
|
||||
CompileAssertTypesEqual<
|
||||
tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>,
|
||||
Matcher<const long&> >, // NOLINT
|
||||
F::ArgumentMatcherTuple>();
|
||||
CompileAssertTypesEqual<void(bool, int, char*, int&, const long&), // NOLINT
|
||||
F::MakeResultVoid>();
|
||||
CompileAssertTypesEqual<
|
||||
|
|
|
@ -31,10 +31,19 @@
|
|||
//
|
||||
// This file tests the built-in matchers generated by a script.
|
||||
|
||||
// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
|
||||
// possible loss of data and C4100, unreferenced local parameter
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4244)
|
||||
# pragma warning(disable:4100)
|
||||
#endif
|
||||
|
||||
#include "gmock/gmock-generated-matchers.h"
|
||||
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
@ -53,10 +62,12 @@ using std::pair;
|
|||
using std::set;
|
||||
using std::stringstream;
|
||||
using std::vector;
|
||||
using std::tr1::get;
|
||||
using std::tr1::make_tuple;
|
||||
using std::tr1::tuple;
|
||||
using testing::get;
|
||||
using testing::make_tuple;
|
||||
using testing::tuple;
|
||||
using testing::_;
|
||||
using testing::AllOf;
|
||||
using testing::AnyOf;
|
||||
using testing::Args;
|
||||
using testing::Contains;
|
||||
using testing::ElementsAre;
|
||||
|
@ -64,6 +75,7 @@ using testing::ElementsAreArray;
|
|||
using testing::Eq;
|
||||
using testing::Ge;
|
||||
using testing::Gt;
|
||||
using testing::Le;
|
||||
using testing::Lt;
|
||||
using testing::MakeMatcher;
|
||||
using testing::Matcher;
|
||||
|
@ -77,11 +89,11 @@ using testing::Ref;
|
|||
using testing::StaticAssertTypeEq;
|
||||
using testing::StrEq;
|
||||
using testing::Value;
|
||||
using testing::internal::string;
|
||||
using testing::internal::ElementsAreArrayMatcher;
|
||||
|
||||
// Returns the description of the given matcher.
|
||||
template <typename T>
|
||||
string Describe(const Matcher<T>& m) {
|
||||
std::string Describe(const Matcher<T>& m) {
|
||||
stringstream ss;
|
||||
m.DescribeTo(&ss);
|
||||
return ss.str();
|
||||
|
@ -89,7 +101,7 @@ string Describe(const Matcher<T>& m) {
|
|||
|
||||
// Returns the description of the negation of the given matcher.
|
||||
template <typename T>
|
||||
string DescribeNegation(const Matcher<T>& m) {
|
||||
std::string DescribeNegation(const Matcher<T>& m) {
|
||||
stringstream ss;
|
||||
m.DescribeNegationTo(&ss);
|
||||
return ss.str();
|
||||
|
@ -97,7 +109,7 @@ string DescribeNegation(const Matcher<T>& m) {
|
|||
|
||||
// Returns the reason why x matches, or doesn't match, m.
|
||||
template <typename MatcherType, typename Value>
|
||||
string Explain(const MatcherType& m, const Value& x) {
|
||||
std::string Explain(const MatcherType& m, const Value& x) {
|
||||
stringstream ss;
|
||||
m.ExplainMatchResultTo(x, &ss);
|
||||
return ss.str();
|
||||
|
@ -283,9 +295,6 @@ Matcher<int> GreaterThan(int n) {
|
|||
|
||||
// Tests for ElementsAre().
|
||||
|
||||
// Evaluates to the number of elements in 'array'.
|
||||
#define GMOCK_ARRAY_SIZE_(array) (sizeof(array)/sizeof(array[0]))
|
||||
|
||||
TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
|
||||
Matcher<const vector<int>&> m = ElementsAre();
|
||||
EXPECT_EQ("is empty", Describe(m));
|
||||
|
@ -297,7 +306,7 @@ TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
|
|||
}
|
||||
|
||||
TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
|
||||
Matcher<list<string> > m = ElementsAre(StrEq("one"), "two");
|
||||
Matcher<list<std::string> > m = ElementsAre(StrEq("one"), "two");
|
||||
EXPECT_EQ("has 2 elements where\n"
|
||||
"element #0 is equal to \"one\",\n"
|
||||
"element #1 is equal to \"two\"", Describe(m));
|
||||
|
@ -315,7 +324,7 @@ TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
|
|||
}
|
||||
|
||||
TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
|
||||
Matcher<const list<string>& > m = ElementsAre("one", "two");
|
||||
Matcher<const list<std::string>&> m = ElementsAre("one", "two");
|
||||
EXPECT_EQ("doesn't have 2 elements, or\n"
|
||||
"element #0 isn't equal to \"one\", or\n"
|
||||
"element #1 isn't equal to \"two\"", DescribeNegation(m));
|
||||
|
@ -335,7 +344,7 @@ TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
|
|||
ElementsAre(GreaterThan(1), 0, GreaterThan(2));
|
||||
|
||||
const int a[] = { 10, 0, 100 };
|
||||
vector<int> test_vector(a, a + GMOCK_ARRAY_SIZE_(a));
|
||||
vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
EXPECT_EQ("whose element #0 matches, which is 9 more than 1,\n"
|
||||
"and whose element #2 matches, which is 98 more than 2",
|
||||
Explain(m, test_vector));
|
||||
|
@ -366,21 +375,21 @@ TEST(ElementsAreTest, CanExplainMismatchRightSize) {
|
|||
}
|
||||
|
||||
TEST(ElementsAreTest, MatchesOneElementVector) {
|
||||
vector<string> test_vector;
|
||||
vector<std::string> test_vector;
|
||||
test_vector.push_back("test string");
|
||||
|
||||
EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
|
||||
}
|
||||
|
||||
TEST(ElementsAreTest, MatchesOneElementList) {
|
||||
list<string> test_list;
|
||||
list<std::string> test_list;
|
||||
test_list.push_back("test string");
|
||||
|
||||
EXPECT_THAT(test_list, ElementsAre("test string"));
|
||||
}
|
||||
|
||||
TEST(ElementsAreTest, MatchesThreeElementVector) {
|
||||
vector<string> test_vector;
|
||||
vector<std::string> test_vector;
|
||||
test_vector.push_back("one");
|
||||
test_vector.push_back("two");
|
||||
test_vector.push_back("three");
|
||||
|
@ -420,7 +429,7 @@ TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
|
|||
|
||||
TEST(ElementsAreTest, MatchesTenElementVector) {
|
||||
const int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
vector<int> test_vector(a, a + GMOCK_ARRAY_SIZE_(a));
|
||||
vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
|
||||
EXPECT_THAT(test_vector,
|
||||
// The element list can contain values and/or matchers
|
||||
|
@ -429,30 +438,30 @@ TEST(ElementsAreTest, MatchesTenElementVector) {
|
|||
}
|
||||
|
||||
TEST(ElementsAreTest, DoesNotMatchWrongSize) {
|
||||
vector<string> test_vector;
|
||||
vector<std::string> test_vector;
|
||||
test_vector.push_back("test string");
|
||||
test_vector.push_back("test string");
|
||||
|
||||
Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
|
||||
Matcher<vector<std::string> > m = ElementsAre(StrEq("test string"));
|
||||
EXPECT_FALSE(m.Matches(test_vector));
|
||||
}
|
||||
|
||||
TEST(ElementsAreTest, DoesNotMatchWrongValue) {
|
||||
vector<string> test_vector;
|
||||
vector<std::string> test_vector;
|
||||
test_vector.push_back("other string");
|
||||
|
||||
Matcher<vector<string> > m = ElementsAre(StrEq("test string"));
|
||||
Matcher<vector<std::string> > m = ElementsAre(StrEq("test string"));
|
||||
EXPECT_FALSE(m.Matches(test_vector));
|
||||
}
|
||||
|
||||
TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
|
||||
vector<string> test_vector;
|
||||
vector<std::string> test_vector;
|
||||
test_vector.push_back("one");
|
||||
test_vector.push_back("three");
|
||||
test_vector.push_back("two");
|
||||
|
||||
Matcher<vector<string> > m = ElementsAre(
|
||||
StrEq("one"), StrEq("two"), StrEq("three"));
|
||||
Matcher<vector<std::string> > m =
|
||||
ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
|
||||
EXPECT_FALSE(m.Matches(test_vector));
|
||||
}
|
||||
|
||||
|
@ -463,7 +472,7 @@ TEST(ElementsAreTest, WorksForNestedContainer) {
|
|||
};
|
||||
|
||||
vector<list<char> > nested;
|
||||
for (size_t i = 0; i < GMOCK_ARRAY_SIZE_(strings); i++) {
|
||||
for (size_t i = 0; i < GTEST_ARRAY_SIZE_(strings); i++) {
|
||||
nested.push_back(list<char>(strings[i], strings[i] + strlen(strings[i])));
|
||||
}
|
||||
|
||||
|
@ -475,7 +484,7 @@ TEST(ElementsAreTest, WorksForNestedContainer) {
|
|||
|
||||
TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
|
||||
int a[] = { 0, 1, 2 };
|
||||
vector<int> v(a, a + GMOCK_ARRAY_SIZE_(a));
|
||||
vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
|
||||
EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
|
||||
EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
|
||||
|
@ -483,7 +492,7 @@ TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
|
|||
|
||||
TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
|
||||
int a[] = { 0, 1, 2 };
|
||||
vector<int> v(a, a + GMOCK_ARRAY_SIZE_(a));
|
||||
vector<int> v(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
|
||||
EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
|
||||
EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
|
||||
|
@ -508,7 +517,7 @@ class NativeArrayPassedAsPointerAndSize {
|
|||
|
||||
TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
|
||||
int array[] = { 0, 1 };
|
||||
::std::tr1::tuple<int*, size_t> array_as_tuple(array, 2);
|
||||
::testing::tuple<int*, size_t> array_as_tuple(array, 2);
|
||||
EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
|
||||
EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
|
||||
|
||||
|
@ -527,6 +536,52 @@ TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
|
|||
ElementsAre('l', 'o', '\0')));
|
||||
}
|
||||
|
||||
TEST(ElementsAreTest, AcceptsStringLiteral) {
|
||||
std::string array[] = {"hi", "one", "two"};
|
||||
EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
|
||||
EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
|
||||
}
|
||||
|
||||
#ifndef _MSC_VER
|
||||
|
||||
// The following test passes a value of type const char[] to a
|
||||
// function template that expects const T&. Some versions of MSVC
|
||||
// generates a compiler error C2665 for that. We believe it's a bug
|
||||
// in MSVC. Therefore this test is #if-ed out for MSVC.
|
||||
|
||||
// Declared here with the size unknown. Defined AFTER the following test.
|
||||
extern const char kHi[];
|
||||
|
||||
TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
|
||||
// The size of kHi is not known in this test, but ElementsAre() should
|
||||
// still accept it.
|
||||
|
||||
std::string array1[] = {"hi"};
|
||||
EXPECT_THAT(array1, ElementsAre(kHi));
|
||||
|
||||
std::string array2[] = {"ho"};
|
||||
EXPECT_THAT(array2, Not(ElementsAre(kHi)));
|
||||
}
|
||||
|
||||
const char kHi[] = "hi";
|
||||
|
||||
#endif // _MSC_VER
|
||||
|
||||
TEST(ElementsAreTest, MakesCopyOfArguments) {
|
||||
int x = 1;
|
||||
int y = 2;
|
||||
// This should make a copy of x and y.
|
||||
::testing::internal::ElementsAreMatcher<testing::tuple<int, int> >
|
||||
polymorphic_matcher = ElementsAre(x, y);
|
||||
// Changing x and y now shouldn't affect the meaning of the above matcher.
|
||||
x = y = 0;
|
||||
const int array1[] = { 1, 2 };
|
||||
EXPECT_THAT(array1, polymorphic_matcher);
|
||||
const int array2[] = { 0, 0 };
|
||||
EXPECT_THAT(array2, Not(polymorphic_matcher));
|
||||
}
|
||||
|
||||
|
||||
// Tests for ElementsAreArray(). Since ElementsAreArray() shares most
|
||||
// of the implementation with ElementsAre(), we don't test it as
|
||||
// thoroughly here.
|
||||
|
@ -534,7 +589,7 @@ TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
|
|||
TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
|
||||
const int a[] = { 1, 2, 3 };
|
||||
|
||||
vector<int> test_vector(a, a + GMOCK_ARRAY_SIZE_(a));
|
||||
vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(a));
|
||||
|
||||
test_vector[2] = 0;
|
||||
|
@ -544,18 +599,18 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
|
|||
TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
|
||||
const char* a[] = { "one", "two", "three" };
|
||||
|
||||
vector<string> test_vector(a, a + GMOCK_ARRAY_SIZE_(a));
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(a, GMOCK_ARRAY_SIZE_(a)));
|
||||
vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(a, GTEST_ARRAY_SIZE_(a)));
|
||||
|
||||
const char** p = a;
|
||||
test_vector[0] = "1";
|
||||
EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GMOCK_ARRAY_SIZE_(a))));
|
||||
EXPECT_THAT(test_vector, Not(ElementsAreArray(p, GTEST_ARRAY_SIZE_(a))));
|
||||
}
|
||||
|
||||
TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
|
||||
const char* a[] = { "one", "two", "three" };
|
||||
|
||||
vector<string> test_vector(a, a + GMOCK_ARRAY_SIZE_(a));
|
||||
vector<std::string> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(a));
|
||||
|
||||
test_vector[0] = "1";
|
||||
|
@ -563,10 +618,10 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
|
|||
}
|
||||
|
||||
TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
|
||||
const Matcher<string> kMatcherArray[] =
|
||||
{ StrEq("one"), StrEq("two"), StrEq("three") };
|
||||
const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
|
||||
StrEq("three")};
|
||||
|
||||
vector<string> test_vector;
|
||||
vector<std::string> test_vector;
|
||||
test_vector.push_back("one");
|
||||
test_vector.push_back("two");
|
||||
test_vector.push_back("three");
|
||||
|
@ -576,6 +631,77 @@ TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
|
|||
EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
|
||||
}
|
||||
|
||||
TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
|
||||
const int a[] = { 1, 2, 3 };
|
||||
vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(expected));
|
||||
test_vector.push_back(4);
|
||||
EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STD_INITIALIZER_LIST_
|
||||
|
||||
TEST(ElementsAreArrayTest, TakesInitializerList) {
|
||||
const int a[5] = { 1, 2, 3, 4, 5 };
|
||||
EXPECT_THAT(a, ElementsAreArray({ 1, 2, 3, 4, 5 }));
|
||||
EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 5, 4 })));
|
||||
EXPECT_THAT(a, Not(ElementsAreArray({ 1, 2, 3, 4, 6 })));
|
||||
}
|
||||
|
||||
TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
|
||||
const std::string a[5] = {"a", "b", "c", "d", "e"};
|
||||
EXPECT_THAT(a, ElementsAreArray({ "a", "b", "c", "d", "e" }));
|
||||
EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "e", "d" })));
|
||||
EXPECT_THAT(a, Not(ElementsAreArray({ "a", "b", "c", "d", "ef" })));
|
||||
}
|
||||
|
||||
TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
|
||||
const int a[5] = { 1, 2, 3, 4, 5 };
|
||||
EXPECT_THAT(a, ElementsAreArray(
|
||||
{ Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
|
||||
EXPECT_THAT(a, Not(ElementsAreArray(
|
||||
{ Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
|
||||
}
|
||||
|
||||
TEST(ElementsAreArrayTest,
|
||||
TakesInitializerListOfDifferentTypedMatchers) {
|
||||
const int a[5] = { 1, 2, 3, 4, 5 };
|
||||
// The compiler cannot infer the type of the initializer list if its
|
||||
// elements have different types. We must explicitly specify the
|
||||
// unified element type in this case.
|
||||
EXPECT_THAT(a, ElementsAreArray<Matcher<int> >(
|
||||
{ Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
|
||||
EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int> >(
|
||||
{ Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_STD_INITIALIZER_LIST_
|
||||
|
||||
TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
|
||||
const int a[] = { 1, 2, 3 };
|
||||
const Matcher<int> kMatchers[] = { Eq(1), Eq(2), Eq(3) };
|
||||
vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
const vector<Matcher<int> > expected(
|
||||
kMatchers, kMatchers + GTEST_ARRAY_SIZE_(kMatchers));
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(expected));
|
||||
test_vector.push_back(4);
|
||||
EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
|
||||
}
|
||||
|
||||
TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
|
||||
const int a[] = { 1, 2, 3 };
|
||||
const vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
const vector<int> expected(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
|
||||
// Pointers are iterators, too.
|
||||
EXPECT_THAT(test_vector, ElementsAreArray(a, a + GTEST_ARRAY_SIZE_(a)));
|
||||
// The empty range of NULL pointers should also be okay.
|
||||
int* const null_int = NULL;
|
||||
EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
|
||||
EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
|
||||
}
|
||||
|
||||
// Since ElementsAre() and ElementsAreArray() share much of the
|
||||
// implementation, we only do a sanity test for native arrays here.
|
||||
TEST(ElementsAreArrayTest, WorksWithNativeArray) {
|
||||
|
@ -587,6 +713,22 @@ TEST(ElementsAreArrayTest, WorksWithNativeArray) {
|
|||
EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
|
||||
}
|
||||
|
||||
TEST(ElementsAreArrayTest, SourceLifeSpan) {
|
||||
const int a[] = { 1, 2, 3 };
|
||||
vector<int> test_vector(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
vector<int> expect(a, a + GTEST_ARRAY_SIZE_(a));
|
||||
ElementsAreArrayMatcher<int> matcher_maker =
|
||||
ElementsAreArray(expect.begin(), expect.end());
|
||||
EXPECT_THAT(test_vector, matcher_maker);
|
||||
// Changing in place the values that initialized matcher_maker should not
|
||||
// affect matcher_maker anymore. It should have made its own copy of them.
|
||||
typedef vector<int>::iterator Iter;
|
||||
for (Iter it = expect.begin(); it != expect.end(); ++it) { *it += 10; }
|
||||
EXPECT_THAT(test_vector, matcher_maker);
|
||||
test_vector.push_back(3);
|
||||
EXPECT_THAT(test_vector, Not(matcher_maker));
|
||||
}
|
||||
|
||||
// Tests for the MATCHER*() macro family.
|
||||
|
||||
// Tests that a simple MATCHER() definition works.
|
||||
|
@ -619,9 +761,9 @@ MATCHER(IsEven2, negation ? "is odd" : "is even") {
|
|||
|
||||
// This also tests that the description string can reference matcher
|
||||
// parameters.
|
||||
MATCHER_P2(EqSumOf, x, y,
|
||||
string(negation ? "doesn't equal" : "equals") + " the sum of " +
|
||||
PrintToString(x) + " and " + PrintToString(y)) {
|
||||
MATCHER_P2(EqSumOf, x, y, std::string(negation ? "doesn't equal" : "equals") +
|
||||
" the sum of " + PrintToString(x) + " and " +
|
||||
PrintToString(y)) {
|
||||
if (arg == (x + y)) {
|
||||
*result_listener << "OK";
|
||||
return true;
|
||||
|
@ -944,6 +1086,19 @@ TEST(MatcherPnMacroTest, TypesAreCorrect) {
|
|||
EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
|
||||
EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
|
||||
EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
|
||||
|
||||
// Avoid "unused variable" warnings.
|
||||
(void)a0;
|
||||
(void)a1;
|
||||
(void)a2;
|
||||
(void)a3;
|
||||
(void)a4;
|
||||
(void)a5;
|
||||
(void)a6;
|
||||
(void)a7;
|
||||
(void)a8;
|
||||
(void)a9;
|
||||
(void)a10;
|
||||
}
|
||||
|
||||
// Tests that matcher-typed parameters can be used in Value() inside a
|
||||
|
@ -972,12 +1127,12 @@ TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
|
|||
EXPECT_THAT(some_list, Contains(Gt(2.5)));
|
||||
EXPECT_THAT(some_list, Contains(Eq(2.0f)));
|
||||
|
||||
list<string> another_list;
|
||||
list<std::string> another_list;
|
||||
another_list.push_back("fee");
|
||||
another_list.push_back("fie");
|
||||
another_list.push_back("foe");
|
||||
another_list.push_back("fum");
|
||||
EXPECT_THAT(another_list, Contains(string("fee")));
|
||||
EXPECT_THAT(another_list, Contains(std::string("fee")));
|
||||
}
|
||||
|
||||
TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
|
||||
|
@ -1001,7 +1156,7 @@ TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
|
|||
another_set.insert("fie");
|
||||
another_set.insert("foe");
|
||||
another_set.insert("fum");
|
||||
EXPECT_THAT(another_set, Contains(Eq(string("fum"))));
|
||||
EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
|
||||
}
|
||||
|
||||
TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
|
||||
|
@ -1012,12 +1167,12 @@ TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
|
|||
|
||||
set<const char*> c_string_set;
|
||||
c_string_set.insert("hello");
|
||||
EXPECT_THAT(c_string_set, Not(Contains(string("hello").c_str())));
|
||||
EXPECT_THAT(c_string_set, Not(Contains(std::string("hello").c_str())));
|
||||
}
|
||||
|
||||
TEST(ContainsTest, ExplainsMatchResultCorrectly) {
|
||||
const int a[2] = { 1, 2 };
|
||||
Matcher<const int(&)[2]> m = Contains(2);
|
||||
Matcher<const int (&)[2]> m = Contains(2);
|
||||
EXPECT_EQ("whose element #1 matches", Explain(m, a));
|
||||
|
||||
m = Contains(3);
|
||||
|
@ -1044,13 +1199,14 @@ TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
|
|||
my_map[bar] = 2;
|
||||
EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
|
||||
|
||||
map<string, int> another_map;
|
||||
map<std::string, int> another_map;
|
||||
another_map["fee"] = 1;
|
||||
another_map["fie"] = 2;
|
||||
another_map["foe"] = 3;
|
||||
another_map["fum"] = 4;
|
||||
EXPECT_THAT(another_map, Contains(pair<const string, int>(string("fee"), 1)));
|
||||
EXPECT_THAT(another_map, Contains(pair<const string, int>("fie", 2)));
|
||||
EXPECT_THAT(another_map,
|
||||
Contains(pair<const std::string, int>(std::string("fee"), 1)));
|
||||
EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
|
||||
}
|
||||
|
||||
TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
|
||||
|
@ -1062,7 +1218,7 @@ TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
|
|||
|
||||
TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
|
||||
const char* string_array[] = { "fee", "fie", "foe", "fum" };
|
||||
EXPECT_THAT(string_array, Contains(Eq(string("fum"))));
|
||||
EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
|
||||
}
|
||||
|
||||
TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
|
||||
|
@ -1091,6 +1247,20 @@ TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
|
|||
EXPECT_THAT(a, Contains(Not(Contains(5))));
|
||||
}
|
||||
|
||||
TEST(AllOfTest, HugeMatcher) {
|
||||
// Verify that using AllOf with many arguments doesn't cause
|
||||
// the compiler to exceed template instantiation depth limit.
|
||||
EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
|
||||
testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
|
||||
}
|
||||
|
||||
TEST(AnyOfTest, HugeMatcher) {
|
||||
// Verify that using AnyOf with many arguments doesn't cause
|
||||
// the compiler to exceed template instantiation depth limit.
|
||||
EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
|
||||
testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
|
||||
}
|
||||
|
||||
namespace adl_test {
|
||||
|
||||
// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
|
||||
|
@ -1124,4 +1294,48 @@ TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
|
|||
# pragma warning(pop)
|
||||
#endif
|
||||
|
||||
#if GTEST_LANG_CXX11
|
||||
|
||||
TEST(AllOfTest, WorksOnMoveOnlyType) {
|
||||
std::unique_ptr<int> p(new int(3));
|
||||
EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
|
||||
EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
|
||||
}
|
||||
|
||||
TEST(AnyOfTest, WorksOnMoveOnlyType) {
|
||||
std::unique_ptr<int> p(new int(3));
|
||||
EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
|
||||
EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
|
||||
}
|
||||
|
||||
MATCHER(IsNotNull, "") {
|
||||
return arg != nullptr;
|
||||
}
|
||||
|
||||
// Verifies that a matcher defined using MATCHER() can work on
|
||||
// move-only types.
|
||||
TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
|
||||
std::unique_ptr<int> p(new int(3));
|
||||
EXPECT_THAT(p, IsNotNull());
|
||||
EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
|
||||
}
|
||||
|
||||
MATCHER_P(UniquePointee, pointee, "") {
|
||||
return *arg == pointee;
|
||||
}
|
||||
|
||||
// Verifies that a matcher defined using MATCHER_P*() can work on
|
||||
// move-only types.
|
||||
TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
|
||||
std::unique_ptr<int> p(new int(3));
|
||||
EXPECT_THAT(p, UniquePointee(3));
|
||||
EXPECT_THAT(p, Not(UniquePointee(2)));
|
||||
}
|
||||
|
||||
#endif // GTEST_LASNG_CXX11
|
||||
|
||||
} // namespace
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -36,6 +35,7 @@
|
|||
#include "gmock/internal/gmock-internal-utils.h"
|
||||
#include <stdlib.h>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
@ -44,6 +44,15 @@
|
|||
#include "gtest/gtest.h"
|
||||
#include "gtest/gtest-spi.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
|
||||
// their code.
|
||||
#define GTEST_IMPLEMENTATION_ 1
|
||||
#include "src/gtest-internal-inl.h"
|
||||
#undef GTEST_IMPLEMENTATION_
|
||||
|
||||
#if GTEST_OS_CYGWIN
|
||||
# include <sys/types.h> // For ssize_t. NOLINT
|
||||
#endif
|
||||
|
@ -59,8 +68,25 @@ namespace internal {
|
|||
|
||||
namespace {
|
||||
|
||||
using ::std::tr1::make_tuple;
|
||||
using ::std::tr1::tuple;
|
||||
TEST(JoinAsTupleTest, JoinsEmptyTuple) {
|
||||
EXPECT_EQ("", JoinAsTuple(Strings()));
|
||||
}
|
||||
|
||||
TEST(JoinAsTupleTest, JoinsOneTuple) {
|
||||
const char* fields[] = {"1"};
|
||||
EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
|
||||
}
|
||||
|
||||
TEST(JoinAsTupleTest, JoinsTwoTuple) {
|
||||
const char* fields[] = {"1", "a"};
|
||||
EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
|
||||
}
|
||||
|
||||
TEST(JoinAsTupleTest, JoinsTenTuple) {
|
||||
const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
|
||||
EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
|
||||
JoinAsTuple(Strings(fields, fields + 10)));
|
||||
}
|
||||
|
||||
TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {
|
||||
EXPECT_EQ("", ConvertIdentifierNameToWords(""));
|
||||
|
@ -99,6 +125,13 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
|
|||
TEST(PointeeOfTest, WorksForSmartPointers) {
|
||||
CompileAssertTypesEqual<const char,
|
||||
PointeeOf<internal::linked_ptr<const char> >::type>();
|
||||
#if GTEST_HAS_STD_UNIQUE_PTR_
|
||||
CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>();
|
||||
#endif // GTEST_HAS_STD_UNIQUE_PTR_
|
||||
#if GTEST_HAS_STD_SHARED_PTR_
|
||||
CompileAssertTypesEqual<std::string,
|
||||
PointeeOf<std::shared_ptr<std::string> >::type>();
|
||||
#endif // GTEST_HAS_STD_SHARED_PTR_
|
||||
}
|
||||
|
||||
TEST(PointeeOfTest, WorksForRawPointers) {
|
||||
|
@ -108,6 +141,17 @@ TEST(PointeeOfTest, WorksForRawPointers) {
|
|||
}
|
||||
|
||||
TEST(GetRawPointerTest, WorksForSmartPointers) {
|
||||
#if GTEST_HAS_STD_UNIQUE_PTR_
|
||||
const char* const raw_p1 = new const char('a'); // NOLINT
|
||||
const std::unique_ptr<const char> p1(raw_p1);
|
||||
EXPECT_EQ(raw_p1, GetRawPointer(p1));
|
||||
#endif // GTEST_HAS_STD_UNIQUE_PTR_
|
||||
#if GTEST_HAS_STD_SHARED_PTR_
|
||||
double* const raw_p2 = new double(2.5); // NOLINT
|
||||
const std::shared_ptr<double> p2(raw_p2);
|
||||
EXPECT_EQ(raw_p2, GetRawPointer(p2));
|
||||
#endif // GTEST_HAS_STD_SHARED_PTR_
|
||||
|
||||
const char* const raw_p4 = new const char('a'); // NOLINT
|
||||
const internal::linked_ptr<const char> p4(raw_p4);
|
||||
EXPECT_EQ(raw_p4, GetRawPointer(p4));
|
||||
|
@ -250,7 +294,9 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {
|
|||
|
||||
// Larger size => smaller size is not fine.
|
||||
EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));
|
||||
GTEST_INTENTIONAL_CONST_COND_PUSH_()
|
||||
if (sizeof(double) == sizeof(long double)) { // NOLINT
|
||||
GTEST_INTENTIONAL_CONST_COND_POP_()
|
||||
// In some implementations (e.g. MSVC), double and long double
|
||||
// have the same size.
|
||||
EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));
|
||||
|
@ -292,11 +338,10 @@ TEST(TupleMatchesTest, WorksForSize2) {
|
|||
|
||||
TEST(TupleMatchesTest, WorksForSize5) {
|
||||
tuple<Matcher<int>, Matcher<char>, Matcher<bool>, Matcher<long>, // NOLINT
|
||||
Matcher<string> >
|
||||
Matcher<std::string> >
|
||||
matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi"));
|
||||
tuple<int, char, bool, long, string> // NOLINT
|
||||
values1(1, 'a', true, 2L, "hi"),
|
||||
values2(1, 'a', true, 2L, "hello"),
|
||||
tuple<int, char, bool, long, std::string> // NOLINT
|
||||
values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"),
|
||||
values3(2, 'a', true, 2L, "hi");
|
||||
|
||||
EXPECT_TRUE(TupleMatches(matchers, values1));
|
||||
|
@ -343,36 +388,30 @@ TEST(ExpectTest, FailsNonfatallyOnFalse) {
|
|||
class LogIsVisibleTest : public ::testing::Test {
|
||||
protected:
|
||||
virtual void SetUp() {
|
||||
// The code needs to work when both ::string and ::std::string are
|
||||
// defined and the flag is implemented as a
|
||||
// testing::internal::String. In this case, without the call to
|
||||
// c_str(), the compiler will complain that it cannot figure out
|
||||
// whether the String flag should be converted to a ::string or an
|
||||
// ::std::string before being assigned to original_verbose_.
|
||||
original_verbose_ = GMOCK_FLAG(verbose).c_str();
|
||||
original_verbose_ = GMOCK_FLAG(verbose);
|
||||
}
|
||||
|
||||
virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; }
|
||||
|
||||
string original_verbose_;
|
||||
std::string original_verbose_;
|
||||
};
|
||||
|
||||
TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {
|
||||
GMOCK_FLAG(verbose) = kInfoVerbosity;
|
||||
EXPECT_TRUE(LogIsVisible(INFO));
|
||||
EXPECT_TRUE(LogIsVisible(WARNING));
|
||||
EXPECT_TRUE(LogIsVisible(kInfo));
|
||||
EXPECT_TRUE(LogIsVisible(kWarning));
|
||||
}
|
||||
|
||||
TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {
|
||||
GMOCK_FLAG(verbose) = kErrorVerbosity;
|
||||
EXPECT_FALSE(LogIsVisible(INFO));
|
||||
EXPECT_FALSE(LogIsVisible(WARNING));
|
||||
EXPECT_FALSE(LogIsVisible(kInfo));
|
||||
EXPECT_FALSE(LogIsVisible(kWarning));
|
||||
}
|
||||
|
||||
TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
|
||||
GMOCK_FLAG(verbose) = kWarningVerbosity;
|
||||
EXPECT_FALSE(LogIsVisible(INFO));
|
||||
EXPECT_TRUE(LogIsVisible(WARNING));
|
||||
EXPECT_FALSE(LogIsVisible(kInfo));
|
||||
EXPECT_TRUE(LogIsVisible(kWarning));
|
||||
}
|
||||
|
||||
#if GTEST_HAS_STREAM_REDIRECTION
|
||||
|
@ -381,16 +420,16 @@ TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {
|
|||
|
||||
// Verifies that Log() behaves correctly for the given verbosity level
|
||||
// and log severity.
|
||||
void TestLogWithSeverity(const string& verbosity, LogSeverity severity,
|
||||
void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,
|
||||
bool should_print) {
|
||||
const string old_flag = GMOCK_FLAG(verbose);
|
||||
const std::string old_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = verbosity;
|
||||
CaptureStdout();
|
||||
Log(severity, "Test log.\n", 0);
|
||||
if (should_print) {
|
||||
EXPECT_THAT(GetCapturedStdout().c_str(),
|
||||
ContainsRegex(
|
||||
severity == WARNING ?
|
||||
severity == kWarning ?
|
||||
"^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" :
|
||||
"^\nTest log\\.\nStack trace:\n"));
|
||||
} else {
|
||||
|
@ -402,63 +441,86 @@ void TestLogWithSeverity(const string& verbosity, LogSeverity severity,
|
|||
// Tests that when the stack_frames_to_skip parameter is negative,
|
||||
// Log() doesn't include the stack trace in the output.
|
||||
TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {
|
||||
const string saved_flag = GMOCK_FLAG(verbose);
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = kInfoVerbosity;
|
||||
CaptureStdout();
|
||||
Log(INFO, "Test log.\n", -1);
|
||||
Log(kInfo, "Test log.\n", -1);
|
||||
EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str());
|
||||
GMOCK_FLAG(verbose) = saved_flag;
|
||||
}
|
||||
|
||||
struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {
|
||||
virtual std::string CurrentStackTrace(int max_depth, int skip_count) {
|
||||
return (testing::Message() << max_depth << "::" << skip_count << "\n")
|
||||
.GetString();
|
||||
}
|
||||
virtual void UponLeavingGTest() {}
|
||||
};
|
||||
|
||||
// Tests that in opt mode, a positive stack_frames_to_skip argument is
|
||||
// treated as 0.
|
||||
TEST(LogTest, NoSkippingStackFrameInOptMode) {
|
||||
MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;
|
||||
GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);
|
||||
|
||||
CaptureStdout();
|
||||
Log(WARNING, "Test log.\n", 100);
|
||||
const String log = GetCapturedStdout();
|
||||
Log(kWarning, "Test log.\n", 100);
|
||||
const std::string log = GetCapturedStdout();
|
||||
|
||||
# if defined(NDEBUG) && GTEST_GOOGLE3_MODE_
|
||||
std::string expected_trace =
|
||||
(testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString();
|
||||
std::string expected_message =
|
||||
"\nGMOCK WARNING:\n"
|
||||
"Test log.\n"
|
||||
"Stack trace:\n" +
|
||||
expected_trace;
|
||||
EXPECT_THAT(log, HasSubstr(expected_message));
|
||||
int skip_count = atoi(log.substr(expected_message.size()).c_str());
|
||||
|
||||
# if defined(NDEBUG)
|
||||
// In opt mode, no stack frame should be skipped.
|
||||
EXPECT_THAT(log, ContainsRegex("\nGMOCK WARNING:\n"
|
||||
"Test log\\.\n"
|
||||
"Stack trace:\n"
|
||||
".+"));
|
||||
const int expected_skip_count = 0;
|
||||
# else
|
||||
|
||||
// In dbg mode, the stack frames should be skipped.
|
||||
EXPECT_STREQ("\nGMOCK WARNING:\n"
|
||||
"Test log.\n"
|
||||
"Stack trace:\n", log.c_str());
|
||||
const int expected_skip_count = 100;
|
||||
# endif
|
||||
|
||||
// Note that each inner implementation layer will +1 the number to remove
|
||||
// itself from the trace. This means that the value is a little higher than
|
||||
// expected, but close enough.
|
||||
EXPECT_THAT(skip_count,
|
||||
AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));
|
||||
|
||||
// Restores the default OS stack trace getter.
|
||||
GetUnitTestImpl()->set_os_stack_trace_getter(NULL);
|
||||
}
|
||||
|
||||
// Tests that all logs are printed when the value of the
|
||||
// --gmock_verbose flag is "info".
|
||||
TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {
|
||||
TestLogWithSeverity(kInfoVerbosity, INFO, true);
|
||||
TestLogWithSeverity(kInfoVerbosity, WARNING, true);
|
||||
TestLogWithSeverity(kInfoVerbosity, kInfo, true);
|
||||
TestLogWithSeverity(kInfoVerbosity, kWarning, true);
|
||||
}
|
||||
|
||||
// Tests that only warnings are printed when the value of the
|
||||
// --gmock_verbose flag is "warning".
|
||||
TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {
|
||||
TestLogWithSeverity(kWarningVerbosity, INFO, false);
|
||||
TestLogWithSeverity(kWarningVerbosity, WARNING, true);
|
||||
TestLogWithSeverity(kWarningVerbosity, kInfo, false);
|
||||
TestLogWithSeverity(kWarningVerbosity, kWarning, true);
|
||||
}
|
||||
|
||||
// Tests that no logs are printed when the value of the
|
||||
// --gmock_verbose flag is "error".
|
||||
TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {
|
||||
TestLogWithSeverity(kErrorVerbosity, INFO, false);
|
||||
TestLogWithSeverity(kErrorVerbosity, WARNING, false);
|
||||
TestLogWithSeverity(kErrorVerbosity, kInfo, false);
|
||||
TestLogWithSeverity(kErrorVerbosity, kWarning, false);
|
||||
}
|
||||
|
||||
// Tests that only warnings are printed when the value of the
|
||||
// --gmock_verbose flag is invalid.
|
||||
TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {
|
||||
TestLogWithSeverity("invalid", INFO, false);
|
||||
TestLogWithSeverity("invalid", WARNING, true);
|
||||
TestLogWithSeverity("invalid", kInfo, false);
|
||||
TestLogWithSeverity("invalid", kWarning, true);
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_STREAM_REDIRECTION
|
||||
|
@ -502,8 +564,8 @@ TEST(TypeTraitsTest, remove_reference) {
|
|||
|
||||
// Verifies that Log() behaves correctly for the given verbosity level
|
||||
// and log severity.
|
||||
String GrabOutput(void(*logger)(), const char* verbosity) {
|
||||
const string saved_flag = GMOCK_FLAG(verbose);
|
||||
std::string GrabOutput(void(*logger)(), const char* verbosity) {
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = verbosity;
|
||||
CaptureStdout();
|
||||
logger();
|
||||
|
@ -525,7 +587,7 @@ void ExpectCallLogger() {
|
|||
|
||||
// Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info".
|
||||
TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {
|
||||
EXPECT_THAT(GrabOutput(ExpectCallLogger, kInfoVerbosity),
|
||||
EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),
|
||||
HasSubstr("EXPECT_CALL(mock, TestMethod())"));
|
||||
}
|
||||
|
||||
|
@ -548,7 +610,7 @@ void OnCallLogger() {
|
|||
|
||||
// Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info".
|
||||
TEST(OnCallTest, LogsWhenVerbosityIsInfo) {
|
||||
EXPECT_THAT(GrabOutput(OnCallLogger, kInfoVerbosity),
|
||||
EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),
|
||||
HasSubstr("ON_CALL(mock, TestMethod())"));
|
||||
}
|
||||
|
||||
|
@ -571,7 +633,7 @@ void OnCallAnyArgumentLogger() {
|
|||
|
||||
// Verifies that ON_CALL prints provided _ argument.
|
||||
TEST(OnCallTest, LogsAnythingArgument) {
|
||||
EXPECT_THAT(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity),
|
||||
EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),
|
||||
HasSubstr("ON_CALL(mock, TestMethodArg(_)"));
|
||||
}
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -47,10 +46,10 @@ namespace gmock_more_actions_test {
|
|||
|
||||
using ::std::plus;
|
||||
using ::std::string;
|
||||
using ::std::tr1::get;
|
||||
using ::std::tr1::make_tuple;
|
||||
using ::std::tr1::tuple;
|
||||
using ::std::tr1::tuple_element;
|
||||
using testing::get;
|
||||
using testing::make_tuple;
|
||||
using testing::tuple;
|
||||
using testing::tuple_element;
|
||||
using testing::_;
|
||||
using testing::Action;
|
||||
using testing::ActionInterface;
|
||||
|
@ -94,12 +93,12 @@ const char* Plus1(const char* s) { return s + 1; }
|
|||
|
||||
void VoidUnary(int /* n */) { g_done = true; }
|
||||
|
||||
bool ByConstRef(const string& s) { return s == "Hi"; }
|
||||
bool ByConstRef(const std::string& s) { return s == "Hi"; }
|
||||
|
||||
const double g_double = 0;
|
||||
bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
|
||||
|
||||
string ByNonConstRef(string& s) { return s += "+"; } // NOLINT
|
||||
std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT
|
||||
|
||||
struct UnaryFunctor {
|
||||
int operator()(bool x) { return x ? 1 : -1; }
|
||||
|
@ -119,9 +118,9 @@ int SumOfFirst2(int a, int b, Unused, Unused) { return a + b; }
|
|||
|
||||
void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; }
|
||||
|
||||
string Concat4(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4) {
|
||||
return string(s1) + s2 + s3 + s4;
|
||||
std::string Concat4(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4) {
|
||||
return std::string(s1) + s2 + s3 + s4;
|
||||
}
|
||||
|
||||
int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
|
||||
|
@ -132,9 +131,9 @@ struct SumOf5Functor {
|
|||
}
|
||||
};
|
||||
|
||||
string Concat5(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5) {
|
||||
return string(s1) + s2 + s3 + s4 + s5;
|
||||
std::string Concat5(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5;
|
||||
}
|
||||
|
||||
int SumOf6(int a, int b, int c, int d, int e, int f) {
|
||||
|
@ -147,34 +146,34 @@ struct SumOf6Functor {
|
|||
}
|
||||
};
|
||||
|
||||
string Concat6(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6;
|
||||
std::string Concat6(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6;
|
||||
}
|
||||
|
||||
string Concat7(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
|
||||
std::string Concat7(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
|
||||
}
|
||||
|
||||
string Concat8(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
|
||||
std::string Concat8(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
|
||||
}
|
||||
|
||||
string Concat9(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
|
||||
std::string Concat9(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
|
||||
}
|
||||
|
||||
string Concat10(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9,
|
||||
const char* s10) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
|
||||
std::string Concat10(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9,
|
||||
const char* s10) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
|
||||
}
|
||||
|
||||
class Foo {
|
||||
|
@ -185,7 +184,7 @@ class Foo {
|
|||
|
||||
short Unary(long x) { return static_cast<short>(value_ + x); } // NOLINT
|
||||
|
||||
string Binary(const string& str, char c) const { return str + c; }
|
||||
std::string Binary(const std::string& str, char c) const { return str + c; }
|
||||
|
||||
int Ternary(int x, bool y, char z) { return value_ + x + y*z; }
|
||||
|
||||
|
@ -201,30 +200,31 @@ class Foo {
|
|||
return a + b + c + d + e + f;
|
||||
}
|
||||
|
||||
string Concat7(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
|
||||
std::string Concat7(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;
|
||||
}
|
||||
|
||||
string Concat8(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
|
||||
std::string Concat8(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;
|
||||
}
|
||||
|
||||
string Concat9(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
|
||||
std::string Concat9(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;
|
||||
}
|
||||
|
||||
string Concat10(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9,
|
||||
const char* s10) {
|
||||
return string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
|
||||
std::string Concat10(const char* s1, const char* s2, const char* s3,
|
||||
const char* s4, const char* s5, const char* s6,
|
||||
const char* s7, const char* s8, const char* s9,
|
||||
const char* s10) {
|
||||
return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;
|
||||
}
|
||||
|
||||
private:
|
||||
int value_;
|
||||
};
|
||||
|
@ -279,9 +279,9 @@ inline const char* CharPtr(const char* s) { return s; }
|
|||
|
||||
// Tests using Invoke() with a 7-argument function.
|
||||
TEST(InvokeTest, FunctionThatTakes7Arguments) {
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*)> a =
|
||||
Invoke(Concat7);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*)>
|
||||
a = Invoke(Concat7);
|
||||
EXPECT_EQ("1234567",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -290,9 +290,9 @@ TEST(InvokeTest, FunctionThatTakes7Arguments) {
|
|||
|
||||
// Tests using Invoke() with a 8-argument function.
|
||||
TEST(InvokeTest, FunctionThatTakes8Arguments) {
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*)> a =
|
||||
Invoke(Concat8);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*)>
|
||||
a = Invoke(Concat8);
|
||||
EXPECT_EQ("12345678",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -301,9 +301,10 @@ TEST(InvokeTest, FunctionThatTakes8Arguments) {
|
|||
|
||||
// Tests using Invoke() with a 9-argument function.
|
||||
TEST(InvokeTest, FunctionThatTakes9Arguments) {
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*)> a = Invoke(Concat9);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*)>
|
||||
a = Invoke(Concat9);
|
||||
EXPECT_EQ("123456789",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -312,9 +313,10 @@ TEST(InvokeTest, FunctionThatTakes9Arguments) {
|
|||
|
||||
// Tests using Invoke() with a 10-argument function.
|
||||
TEST(InvokeTest, FunctionThatTakes10Arguments) {
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*, const char*)> a = Invoke(Concat10);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*, const char*)>
|
||||
a = Invoke(Concat10);
|
||||
EXPECT_EQ("1234567890",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -324,9 +326,10 @@ TEST(InvokeTest, FunctionThatTakes10Arguments) {
|
|||
|
||||
// Tests using Invoke() with functions with parameters declared as Unused.
|
||||
TEST(InvokeTest, FunctionWithUnusedParameters) {
|
||||
Action<int(int, int, double, const string&)> a1 =
|
||||
Invoke(SumOfFirst2);
|
||||
EXPECT_EQ(12, a1.Perform(make_tuple(10, 2, 5.6, CharPtr("hi"))));
|
||||
Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2);
|
||||
tuple<int, int, double, std::string> dummy =
|
||||
make_tuple(10, 2, 5.6, std::string("hi"));
|
||||
EXPECT_EQ(12, a1.Perform(dummy));
|
||||
|
||||
Action<int(int, int, bool, int*)> a2 =
|
||||
Invoke(SumOfFirst2);
|
||||
|
@ -336,8 +339,7 @@ TEST(InvokeTest, FunctionWithUnusedParameters) {
|
|||
// Tests using Invoke() with methods with parameters declared as Unused.
|
||||
TEST(InvokeTest, MethodWithUnusedParameters) {
|
||||
Foo foo;
|
||||
Action<int(string, bool, int, int)> a1 =
|
||||
Invoke(&foo, &Foo::SumOfLast2);
|
||||
Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2);
|
||||
EXPECT_EQ(12, a1.Perform(make_tuple(CharPtr("hi"), true, 10, 2)));
|
||||
|
||||
Action<int(char, double, int, int)> a2 =
|
||||
|
@ -376,9 +378,10 @@ TEST(InvokeMethodTest, Unary) {
|
|||
// Tests using Invoke() with a binary method.
|
||||
TEST(InvokeMethodTest, Binary) {
|
||||
Foo foo;
|
||||
Action<string(const string&, char)> a = Invoke(&foo, &Foo::Binary);
|
||||
string s("Hell");
|
||||
EXPECT_EQ("Hello", a.Perform(make_tuple(s, 'o')));
|
||||
Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary);
|
||||
std::string s("Hell");
|
||||
tuple<std::string, char> dummy = make_tuple(s, 'o');
|
||||
EXPECT_EQ("Hello", a.Perform(dummy));
|
||||
}
|
||||
|
||||
// Tests using Invoke() with a ternary method.
|
||||
|
@ -413,9 +416,9 @@ TEST(InvokeMethodTest, MethodThatTakes6Arguments) {
|
|||
// Tests using Invoke() with a 7-argument method.
|
||||
TEST(InvokeMethodTest, MethodThatTakes7Arguments) {
|
||||
Foo foo;
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*)> a =
|
||||
Invoke(&foo, &Foo::Concat7);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*)>
|
||||
a = Invoke(&foo, &Foo::Concat7);
|
||||
EXPECT_EQ("1234567",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -425,9 +428,9 @@ TEST(InvokeMethodTest, MethodThatTakes7Arguments) {
|
|||
// Tests using Invoke() with a 8-argument method.
|
||||
TEST(InvokeMethodTest, MethodThatTakes8Arguments) {
|
||||
Foo foo;
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*)> a =
|
||||
Invoke(&foo, &Foo::Concat8);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*)>
|
||||
a = Invoke(&foo, &Foo::Concat8);
|
||||
EXPECT_EQ("12345678",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -437,9 +440,10 @@ TEST(InvokeMethodTest, MethodThatTakes8Arguments) {
|
|||
// Tests using Invoke() with a 9-argument method.
|
||||
TEST(InvokeMethodTest, MethodThatTakes9Arguments) {
|
||||
Foo foo;
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*)> a = Invoke(&foo, &Foo::Concat9);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*)>
|
||||
a = Invoke(&foo, &Foo::Concat9);
|
||||
EXPECT_EQ("123456789",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -449,9 +453,10 @@ TEST(InvokeMethodTest, MethodThatTakes9Arguments) {
|
|||
// Tests using Invoke() with a 10-argument method.
|
||||
TEST(InvokeMethodTest, MethodThatTakes10Arguments) {
|
||||
Foo foo;
|
||||
Action<string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*, const char*)> a = Invoke(&foo, &Foo::Concat10);
|
||||
Action<std::string(const char*, const char*, const char*, const char*,
|
||||
const char*, const char*, const char*, const char*,
|
||||
const char*, const char*)>
|
||||
a = Invoke(&foo, &Foo::Concat10);
|
||||
EXPECT_EQ("1234567890",
|
||||
a.Perform(make_tuple(CharPtr("1"), CharPtr("2"), CharPtr("3"),
|
||||
CharPtr("4"), CharPtr("5"), CharPtr("6"),
|
||||
|
@ -491,8 +496,8 @@ TEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) {
|
|||
}
|
||||
|
||||
TEST(ReturnArgActionTest, WorksForMultiArgStringArg2) {
|
||||
const Action<string(int, int, string, int)> a = ReturnArg<2>();
|
||||
EXPECT_EQ("seven", a.Perform(make_tuple(5, 6, string("seven"), 8)));
|
||||
const Action<std::string(int, int, std::string, int)> a = ReturnArg<2>();
|
||||
EXPECT_EQ("seven", a.Perform(make_tuple(5, 6, std::string("seven"), 8)));
|
||||
}
|
||||
|
||||
TEST(SaveArgActionTest, WorksForSameType) {
|
||||
|
@ -667,17 +672,17 @@ TEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {
|
|||
// Tests SetArrayArgument<N>(first, last) where *first is convertible
|
||||
// (but not equal) to the argument type.
|
||||
TEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {
|
||||
typedef void MyFunction(bool, char*);
|
||||
int codes[] = { 97, 98, 99 };
|
||||
Action<MyFunction> a = SetArrayArgument<1>(codes, codes + 3);
|
||||
typedef void MyFunction(bool, int*);
|
||||
char chars[] = { 97, 98, 99 };
|
||||
Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3);
|
||||
|
||||
char ch[4] = {};
|
||||
char* pch = ch;
|
||||
a.Perform(make_tuple(true, pch));
|
||||
EXPECT_EQ('a', ch[0]);
|
||||
EXPECT_EQ('b', ch[1]);
|
||||
EXPECT_EQ('c', ch[2]);
|
||||
EXPECT_EQ('\0', ch[3]);
|
||||
int codes[4] = { 111, 222, 333, 444 };
|
||||
int* pcodes = codes;
|
||||
a.Perform(make_tuple(true, pcodes));
|
||||
EXPECT_EQ(97, codes[0]);
|
||||
EXPECT_EQ(98, codes[1]);
|
||||
EXPECT_EQ(99, codes[2]);
|
||||
EXPECT_EQ(444, codes[3]);
|
||||
}
|
||||
|
||||
// Test SetArrayArgument<N>(first, last) with iterator as argument.
|
||||
|
|
|
@ -26,15 +26,15 @@
|
|||
// 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 "gmock/gmock-generated-nice-strict.h"
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest/gtest.h"
|
||||
#include "gtest/gtest-spi.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
// This must not be defined inside the ::testing namespace, or it will
|
||||
// clash with ::testing::Mock.
|
||||
|
@ -51,9 +51,9 @@ class Mock {
|
|||
namespace testing {
|
||||
namespace gmock_nice_strict_test {
|
||||
|
||||
using testing::internal::string;
|
||||
using testing::GMOCK_FLAG(verbose);
|
||||
using testing::HasSubstr;
|
||||
using testing::NaggyMock;
|
||||
using testing::NiceMock;
|
||||
using testing::StrictMock;
|
||||
|
||||
|
@ -62,6 +62,12 @@ using testing::internal::CaptureStdout;
|
|||
using testing::internal::GetCapturedStdout;
|
||||
#endif
|
||||
|
||||
// Class without default constructor.
|
||||
class NotDefaultConstructible {
|
||||
public:
|
||||
explicit NotDefaultConstructible(int) {}
|
||||
};
|
||||
|
||||
// Defines some mock classes needed by the tests.
|
||||
|
||||
class Foo {
|
||||
|
@ -79,6 +85,7 @@ class MockFoo : public Foo {
|
|||
|
||||
MOCK_METHOD0(DoThis, void());
|
||||
MOCK_METHOD1(DoThat, int(bool flag));
|
||||
MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible());
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo);
|
||||
|
@ -86,29 +93,97 @@ class MockFoo : public Foo {
|
|||
|
||||
class MockBar {
|
||||
public:
|
||||
explicit MockBar(const string& s) : str_(s) {}
|
||||
explicit MockBar(const std::string& s) : str_(s) {}
|
||||
|
||||
MockBar(char a1, char a2, string a3, string a4, int a5, int a6,
|
||||
const string& a7, const string& a8, bool a9, bool a10) {
|
||||
str_ = string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) +
|
||||
MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6,
|
||||
const std::string& a7, const std::string& a8, bool a9, bool a10) {
|
||||
str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) +
|
||||
static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F');
|
||||
}
|
||||
|
||||
virtual ~MockBar() {}
|
||||
|
||||
const string& str() const { return str_; }
|
||||
const std::string& str() const { return str_; }
|
||||
|
||||
MOCK_METHOD0(This, int());
|
||||
MOCK_METHOD2(That, string(int, bool));
|
||||
MOCK_METHOD2(That, std::string(int, bool));
|
||||
|
||||
private:
|
||||
string str_;
|
||||
std::string str_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar);
|
||||
};
|
||||
|
||||
#if GTEST_GTEST_LANG_CXX11
|
||||
|
||||
class MockBaz {
|
||||
public:
|
||||
class MoveOnly {
|
||||
MoveOnly() = default;
|
||||
|
||||
MoveOnly(const MoveOnly&) = delete;
|
||||
operator=(const MoveOnly&) = delete;
|
||||
|
||||
MoveOnly(MoveOnly&&) = default;
|
||||
operator=(MoveOnly&&) = default;
|
||||
};
|
||||
|
||||
MockBaz(MoveOnly) {}
|
||||
}
|
||||
#endif // GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
|
||||
|
||||
#if GTEST_HAS_STREAM_REDIRECTION
|
||||
|
||||
// Tests that a raw mock generates warnings for uninteresting calls.
|
||||
TEST(RawMockTest, WarningForUninterestingCall) {
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = "warning";
|
||||
|
||||
MockFoo raw_foo;
|
||||
|
||||
CaptureStdout();
|
||||
raw_foo.DoThis();
|
||||
raw_foo.DoThat(true);
|
||||
EXPECT_THAT(GetCapturedStdout(),
|
||||
HasSubstr("Uninteresting mock function call"));
|
||||
|
||||
GMOCK_FLAG(verbose) = saved_flag;
|
||||
}
|
||||
|
||||
// Tests that a raw mock generates warnings for uninteresting calls
|
||||
// that delete the mock object.
|
||||
TEST(RawMockTest, WarningForUninterestingCallAfterDeath) {
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = "warning";
|
||||
|
||||
MockFoo* const raw_foo = new MockFoo;
|
||||
|
||||
ON_CALL(*raw_foo, DoThis())
|
||||
.WillByDefault(Invoke(raw_foo, &MockFoo::Delete));
|
||||
|
||||
CaptureStdout();
|
||||
raw_foo->DoThis();
|
||||
EXPECT_THAT(GetCapturedStdout(),
|
||||
HasSubstr("Uninteresting mock function call"));
|
||||
|
||||
GMOCK_FLAG(verbose) = saved_flag;
|
||||
}
|
||||
|
||||
// Tests that a raw mock generates informational logs for
|
||||
// uninteresting calls.
|
||||
TEST(RawMockTest, InfoForUninterestingCall) {
|
||||
MockFoo raw_foo;
|
||||
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = "info";
|
||||
CaptureStdout();
|
||||
raw_foo.DoThis();
|
||||
EXPECT_THAT(GetCapturedStdout(),
|
||||
HasSubstr("Uninteresting mock function call"));
|
||||
|
||||
GMOCK_FLAG(verbose) = saved_flag;
|
||||
}
|
||||
|
||||
// Tests that a nice mock generates no warning for uninteresting calls.
|
||||
TEST(NiceMockTest, NoWarningForUninterestingCall) {
|
||||
NiceMock<MockFoo> nice_foo;
|
||||
|
@ -116,7 +191,7 @@ TEST(NiceMockTest, NoWarningForUninterestingCall) {
|
|||
CaptureStdout();
|
||||
nice_foo.DoThis();
|
||||
nice_foo.DoThat(true);
|
||||
EXPECT_STREQ("", GetCapturedStdout().c_str());
|
||||
EXPECT_EQ("", GetCapturedStdout());
|
||||
}
|
||||
|
||||
// Tests that a nice mock generates no warning for uninteresting calls
|
||||
|
@ -129,7 +204,7 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) {
|
|||
|
||||
CaptureStdout();
|
||||
nice_foo->DoThis();
|
||||
EXPECT_STREQ("", GetCapturedStdout().c_str());
|
||||
EXPECT_EQ("", GetCapturedStdout());
|
||||
}
|
||||
|
||||
// Tests that a nice mock generates informational logs for
|
||||
|
@ -137,17 +212,13 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) {
|
|||
TEST(NiceMockTest, InfoForUninterestingCall) {
|
||||
NiceMock<MockFoo> nice_foo;
|
||||
|
||||
const string saved_flag = GMOCK_FLAG(verbose);
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = "info";
|
||||
CaptureStdout();
|
||||
nice_foo.DoThis();
|
||||
EXPECT_THAT(GetCapturedStdout(),
|
||||
HasSubstr("Uninteresting mock function call"));
|
||||
|
||||
CaptureStdout();
|
||||
nice_foo.DoThat(true);
|
||||
EXPECT_THAT(GetCapturedStdout(),
|
||||
HasSubstr("Uninteresting mock function call"));
|
||||
GMOCK_FLAG(verbose) = saved_flag;
|
||||
}
|
||||
|
||||
|
@ -161,6 +232,23 @@ TEST(NiceMockTest, AllowsExpectedCall) {
|
|||
nice_foo.DoThis();
|
||||
}
|
||||
|
||||
// Tests that an unexpected call on a nice mock which returns a
|
||||
// not-default-constructible type throws an exception and the exception contains
|
||||
// the method's name.
|
||||
TEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) {
|
||||
NiceMock<MockFoo> nice_foo;
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
try {
|
||||
nice_foo.ReturnNonDefaultConstructible();
|
||||
FAIL();
|
||||
} catch (const std::runtime_error& ex) {
|
||||
EXPECT_THAT(ex.what(), HasSubstr("ReturnNonDefaultConstructible"));
|
||||
}
|
||||
#else
|
||||
EXPECT_DEATH_IF_SUPPORTED({ nice_foo.ReturnNonDefaultConstructible(); }, "");
|
||||
#endif
|
||||
}
|
||||
|
||||
// Tests that an unexpected call on a nice mock fails.
|
||||
TEST(NiceMockTest, UnexpectedCallFails) {
|
||||
NiceMock<MockFoo> nice_foo;
|
||||
|
@ -190,9 +278,24 @@ TEST(NiceMockTest, NonDefaultConstructor10) {
|
|||
nice_bar.That(5, true);
|
||||
}
|
||||
|
||||
TEST(NiceMockTest, AllowLeak) {
|
||||
NiceMock<MockFoo>* leaked = new NiceMock<MockFoo>;
|
||||
Mock::AllowLeak(leaked);
|
||||
EXPECT_CALL(*leaked, DoThis());
|
||||
leaked->DoThis();
|
||||
}
|
||||
|
||||
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
|
||||
|
||||
TEST(NiceMockTest, MoveOnlyConstructor) {
|
||||
NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly());
|
||||
}
|
||||
|
||||
#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
|
||||
|
||||
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
|
||||
// Tests that NiceMock<Mock> compiles where Mock is a user-defined
|
||||
// class (as opposed to ::testing::Mock). We had to workaround an
|
||||
// class (as opposed to ::testing::Mock). We had to work around an
|
||||
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
|
||||
// NiceMock to be looked up in the wrong context, and this test
|
||||
// ensures that our fix works.
|
||||
|
@ -206,6 +309,114 @@ TEST(NiceMockTest, AcceptsClassNamedMock) {
|
|||
}
|
||||
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
#if GTEST_HAS_STREAM_REDIRECTION
|
||||
|
||||
// Tests that a naggy mock generates warnings for uninteresting calls.
|
||||
TEST(NaggyMockTest, WarningForUninterestingCall) {
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = "warning";
|
||||
|
||||
NaggyMock<MockFoo> naggy_foo;
|
||||
|
||||
CaptureStdout();
|
||||
naggy_foo.DoThis();
|
||||
naggy_foo.DoThat(true);
|
||||
EXPECT_THAT(GetCapturedStdout(),
|
||||
HasSubstr("Uninteresting mock function call"));
|
||||
|
||||
GMOCK_FLAG(verbose) = saved_flag;
|
||||
}
|
||||
|
||||
// Tests that a naggy mock generates a warning for an uninteresting call
|
||||
// that deletes the mock object.
|
||||
TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {
|
||||
const std::string saved_flag = GMOCK_FLAG(verbose);
|
||||
GMOCK_FLAG(verbose) = "warning";
|
||||
|
||||
NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>;
|
||||
|
||||
ON_CALL(*naggy_foo, DoThis())
|
||||
.WillByDefault(Invoke(naggy_foo, &MockFoo::Delete));
|
||||
|
||||
CaptureStdout();
|
||||
naggy_foo->DoThis();
|
||||
EXPECT_THAT(GetCapturedStdout(),
|
||||
HasSubstr("Uninteresting mock function call"));
|
||||
|
||||
GMOCK_FLAG(verbose) = saved_flag;
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_STREAM_REDIRECTION
|
||||
|
||||
// Tests that a naggy mock allows expected calls.
|
||||
TEST(NaggyMockTest, AllowsExpectedCall) {
|
||||
NaggyMock<MockFoo> naggy_foo;
|
||||
|
||||
EXPECT_CALL(naggy_foo, DoThis());
|
||||
naggy_foo.DoThis();
|
||||
}
|
||||
|
||||
// Tests that an unexpected call on a naggy mock fails.
|
||||
TEST(NaggyMockTest, UnexpectedCallFails) {
|
||||
NaggyMock<MockFoo> naggy_foo;
|
||||
|
||||
EXPECT_CALL(naggy_foo, DoThis()).Times(0);
|
||||
EXPECT_NONFATAL_FAILURE(naggy_foo.DoThis(),
|
||||
"called more times than expected");
|
||||
}
|
||||
|
||||
// Tests that NaggyMock works with a mock class that has a non-default
|
||||
// constructor.
|
||||
TEST(NaggyMockTest, NonDefaultConstructor) {
|
||||
NaggyMock<MockBar> naggy_bar("hi");
|
||||
EXPECT_EQ("hi", naggy_bar.str());
|
||||
|
||||
naggy_bar.This();
|
||||
naggy_bar.That(5, true);
|
||||
}
|
||||
|
||||
// Tests that NaggyMock works with a mock class that has a 10-ary
|
||||
// non-default constructor.
|
||||
TEST(NaggyMockTest, NonDefaultConstructor10) {
|
||||
NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5',
|
||||
"6", "7", true, false);
|
||||
EXPECT_EQ("01234567TF", naggy_bar.str());
|
||||
|
||||
naggy_bar.This();
|
||||
naggy_bar.That(5, true);
|
||||
}
|
||||
|
||||
TEST(NaggyMockTest, AllowLeak) {
|
||||
NaggyMock<MockFoo>* leaked = new NaggyMock<MockFoo>;
|
||||
Mock::AllowLeak(leaked);
|
||||
EXPECT_CALL(*leaked, DoThis());
|
||||
leaked->DoThis();
|
||||
}
|
||||
|
||||
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
|
||||
|
||||
TEST(NaggyMockTest, MoveOnlyConstructor) {
|
||||
NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly());
|
||||
}
|
||||
|
||||
#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
|
||||
|
||||
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
|
||||
// Tests that NaggyMock<Mock> compiles where Mock is a user-defined
|
||||
// class (as opposed to ::testing::Mock). We had to work around an
|
||||
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
|
||||
// NaggyMock to be looked up in the wrong context, and this test
|
||||
// ensures that our fix works.
|
||||
//
|
||||
// We have to skip this test on Symbian and Windows Mobile, as it
|
||||
// causes the program to crash there, for reasons unclear to us yet.
|
||||
TEST(NaggyMockTest, AcceptsClassNamedMock) {
|
||||
NaggyMock< ::Mock> naggy;
|
||||
EXPECT_CALL(naggy, DoThis());
|
||||
naggy.DoThis();
|
||||
}
|
||||
#endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
|
||||
|
||||
// Tests that a strict mock allows expected calls.
|
||||
TEST(StrictMockTest, AllowsExpectedCall) {
|
||||
StrictMock<MockFoo> strict_foo;
|
||||
|
@ -264,9 +475,24 @@ TEST(StrictMockTest, NonDefaultConstructor10) {
|
|||
"Uninteresting mock function call");
|
||||
}
|
||||
|
||||
TEST(StrictMockTest, AllowLeak) {
|
||||
StrictMock<MockFoo>* leaked = new StrictMock<MockFoo>;
|
||||
Mock::AllowLeak(leaked);
|
||||
EXPECT_CALL(*leaked, DoThis());
|
||||
leaked->DoThis();
|
||||
}
|
||||
|
||||
#if GTEST_GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
|
||||
|
||||
TEST(StrictMockTest, MoveOnlyConstructor) {
|
||||
StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly());
|
||||
}
|
||||
|
||||
#endif // GTEST_LANG_CXX11 && GTEST_HAS_STD_MOVE_
|
||||
|
||||
#if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE
|
||||
// Tests that StrictMock<Mock> compiles where Mock is a user-defined
|
||||
// class (as opposed to ::testing::Mock). We had to workaround an
|
||||
// class (as opposed to ::testing::Mock). We had to work around an
|
||||
// MSVC 8.0 bug that caused the symbol Mock used in the definition of
|
||||
// StrictMock to be looked up in the wrong context, and this test
|
||||
// ensures that our fix works.
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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)
|
||||
|
||||
|
||||
// Google Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
|
|
@ -26,8 +26,7 @@
|
|||
// 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 Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
|
@ -81,21 +80,26 @@ using testing::Gt;
|
|||
using testing::InSequence;
|
||||
using testing::Invoke;
|
||||
using testing::InvokeWithoutArgs;
|
||||
using testing::IsNotSubstring;
|
||||
using testing::IsSubstring;
|
||||
using testing::Lt;
|
||||
using testing::Message;
|
||||
using testing::Mock;
|
||||
using testing::NaggyMock;
|
||||
using testing::Ne;
|
||||
using testing::Return;
|
||||
using testing::SaveArg;
|
||||
using testing::Sequence;
|
||||
using testing::SetArgPointee;
|
||||
using testing::internal::ExpectationTester;
|
||||
using testing::internal::FormatFileLocation;
|
||||
using testing::internal::g_gmock_mutex;
|
||||
using testing::internal::kAllow;
|
||||
using testing::internal::kErrorVerbosity;
|
||||
using testing::internal::kFail;
|
||||
using testing::internal::kInfoVerbosity;
|
||||
using testing::internal::kWarn;
|
||||
using testing::internal::kWarningVerbosity;
|
||||
using testing::internal::String;
|
||||
using testing::internal::string;
|
||||
using testing::internal::linked_ptr;
|
||||
|
||||
#if GTEST_HAS_STREAM_REDIRECTION
|
||||
using testing::HasSubstr;
|
||||
|
@ -133,14 +137,21 @@ void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
|
|||
|
||||
class Result {};
|
||||
|
||||
// A type that's not default constructible.
|
||||
class NonDefaultConstructible {
|
||||
public:
|
||||
explicit NonDefaultConstructible(int /* dummy */) {}
|
||||
};
|
||||
|
||||
class MockA {
|
||||
public:
|
||||
MockA() {}
|
||||
|
||||
MOCK_METHOD1(DoA, void(int n)); // NOLINT
|
||||
MOCK_METHOD1(ReturnResult, Result(int n)); // NOLINT
|
||||
MOCK_METHOD2(Binary, bool(int x, int y)); // NOLINT
|
||||
MOCK_METHOD2(ReturnInt, int(int x, int y)); // NOLINT
|
||||
MOCK_METHOD1(DoA, void(int n));
|
||||
MOCK_METHOD1(ReturnResult, Result(int n));
|
||||
MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
|
||||
MOCK_METHOD2(Binary, bool(int x, int y));
|
||||
MOCK_METHOD2(ReturnInt, int(int x, int y));
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
|
||||
|
@ -157,6 +168,16 @@ class MockB {
|
|||
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
|
||||
};
|
||||
|
||||
class ReferenceHoldingMock {
|
||||
public:
|
||||
ReferenceHoldingMock() {}
|
||||
|
||||
MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
|
||||
|
||||
private:
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
|
||||
};
|
||||
|
||||
// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
|
||||
// redefining a mock method name. This could happen, for example, when
|
||||
// the tested code #includes Win32 API headers which define many APIs
|
||||
|
@ -621,7 +642,7 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
|
|||
b.DoB(1);
|
||||
b.DoB(2);
|
||||
}
|
||||
const String output = GetCapturedStdout();
|
||||
const std::string output = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(
|
||||
IsSubstring,
|
||||
"Too many actions specified in EXPECT_CALL(b, DoB())...\n"
|
||||
|
@ -663,7 +684,7 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
|
|||
|
||||
CaptureStdout();
|
||||
b.DoB();
|
||||
const String output = GetCapturedStdout();
|
||||
const std::string output = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(
|
||||
IsSubstring,
|
||||
"Too few actions specified in EXPECT_CALL(b, DoB())...\n"
|
||||
|
@ -673,6 +694,60 @@ TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
|
|||
b.DoB();
|
||||
}
|
||||
|
||||
TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
|
||||
int original_behavior = testing::GMOCK_FLAG(default_mock_behavior);
|
||||
|
||||
testing::GMOCK_FLAG(default_mock_behavior) = kAllow;
|
||||
CaptureStdout();
|
||||
{
|
||||
MockA a;
|
||||
a.DoA(0);
|
||||
}
|
||||
std::string output = GetCapturedStdout();
|
||||
EXPECT_TRUE(output.empty()) << output;
|
||||
|
||||
testing::GMOCK_FLAG(default_mock_behavior) = kWarn;
|
||||
CaptureStdout();
|
||||
{
|
||||
MockA a;
|
||||
a.DoA(0);
|
||||
}
|
||||
std::string warning_output = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
|
||||
warning_output);
|
||||
|
||||
testing::GMOCK_FLAG(default_mock_behavior) = kFail;
|
||||
EXPECT_NONFATAL_FAILURE({
|
||||
MockA a;
|
||||
a.DoA(0);
|
||||
}, "Uninteresting mock function call");
|
||||
|
||||
// Out of bounds values are converted to kWarn
|
||||
testing::GMOCK_FLAG(default_mock_behavior) = -1;
|
||||
CaptureStdout();
|
||||
{
|
||||
MockA a;
|
||||
a.DoA(0);
|
||||
}
|
||||
warning_output = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
|
||||
warning_output);
|
||||
testing::GMOCK_FLAG(default_mock_behavior) = 3;
|
||||
CaptureStdout();
|
||||
{
|
||||
MockA a;
|
||||
a.DoA(0);
|
||||
}
|
||||
warning_output = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
|
||||
warning_output);
|
||||
|
||||
testing::GMOCK_FLAG(default_mock_behavior) = original_behavior;
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_STREAM_REDIRECTION
|
||||
|
||||
// Tests the semantics of ON_CALL().
|
||||
|
@ -858,13 +933,13 @@ TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
|
|||
// expectation has no action clause at all.
|
||||
EXPECT_EQ(1, b.DoB());
|
||||
EXPECT_EQ(2, b.DoB());
|
||||
const String output1 = GetCapturedStdout();
|
||||
const std::string output1 = GetCapturedStdout();
|
||||
EXPECT_STREQ("", output1.c_str());
|
||||
|
||||
CaptureStdout();
|
||||
EXPECT_EQ(0, b.DoB());
|
||||
EXPECT_EQ(0, b.DoB());
|
||||
const String output2 = GetCapturedStdout();
|
||||
const std::string output2 = GetCapturedStdout();
|
||||
EXPECT_THAT(output2.c_str(),
|
||||
HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
|
||||
"Called 3 times, but only 2 WillOnce()s are specified"
|
||||
|
@ -875,7 +950,7 @@ TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
|
|||
" - returning default value."));
|
||||
}
|
||||
|
||||
TEST(FunctionMockerTest, ReportsExpectCallLocationForExhausedActions) {
|
||||
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
|
||||
MockB b;
|
||||
std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
|
||||
EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
|
||||
|
@ -884,16 +959,17 @@ TEST(FunctionMockerTest, ReportsExpectCallLocationForExhausedActions) {
|
|||
|
||||
CaptureStdout();
|
||||
EXPECT_EQ(0, b.DoB());
|
||||
const String output = GetCapturedStdout();
|
||||
const std::string output = GetCapturedStdout();
|
||||
// The warning message should contain the call location.
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
|
||||
}
|
||||
|
||||
TEST(FunctionMockerTest, ReportsDefaultActionLocationOfUninterestingCalls) {
|
||||
TEST(FunctionMockerMessageTest,
|
||||
ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
|
||||
std::string on_call_location;
|
||||
CaptureStdout();
|
||||
{
|
||||
MockB b;
|
||||
NaggyMock<MockB> b;
|
||||
on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
|
||||
ON_CALL(b, DoB(_)).WillByDefault(Return(0));
|
||||
b.DoB(0);
|
||||
|
@ -1096,12 +1172,17 @@ TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
|
|||
b.DoB(4);
|
||||
}
|
||||
|
||||
TEST(UndefinedReturnValueTest, ReturnValueIsMandatory) {
|
||||
TEST(UndefinedReturnValueTest,
|
||||
ReturnValueIsMandatoryWhenNotDefaultConstructible) {
|
||||
MockA a;
|
||||
// TODO(wan@google.com): We should really verify the output message,
|
||||
// FIXME: We should really verify the output message,
|
||||
// but we cannot yet due to that EXPECT_DEATH only captures stderr
|
||||
// while Google Mock logs to stdout.
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(1), "");
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
|
||||
#else
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
|
||||
#endif
|
||||
}
|
||||
|
||||
// Tests that an excessive call (one whose arguments match the
|
||||
|
@ -1250,87 +1331,116 @@ TEST(SequenceTest, AnyOrderIsOkByDefault) {
|
|||
|
||||
// Tests that the calls must be in strict order when a complete order
|
||||
// is specified.
|
||||
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo) {
|
||||
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
|
||||
MockA a;
|
||||
ON_CALL(a, ReturnResult(_))
|
||||
.WillByDefault(Return(Result()));
|
||||
|
||||
Sequence s;
|
||||
|
||||
EXPECT_CALL(a, ReturnResult(1))
|
||||
.InSequence(s)
|
||||
.WillOnce(Return(Result()));
|
||||
|
||||
.InSequence(s);
|
||||
EXPECT_CALL(a, ReturnResult(2))
|
||||
.InSequence(s)
|
||||
.WillOnce(Return(Result()));
|
||||
|
||||
.InSequence(s);
|
||||
EXPECT_CALL(a, ReturnResult(3))
|
||||
.InSequence(s)
|
||||
.WillOnce(Return(Result()));
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
a.ReturnResult(1);
|
||||
a.ReturnResult(3);
|
||||
a.ReturnResult(2);
|
||||
}, "");
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
a.ReturnResult(2);
|
||||
a.ReturnResult(1);
|
||||
a.ReturnResult(3);
|
||||
}, "");
|
||||
.InSequence(s);
|
||||
|
||||
a.ReturnResult(1);
|
||||
|
||||
// May only be called after a.ReturnResult(2).
|
||||
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
|
||||
|
||||
a.ReturnResult(2);
|
||||
a.ReturnResult(3);
|
||||
}
|
||||
|
||||
// Tests specifying a DAG using multiple sequences.
|
||||
TEST(SequenceTest, CallsMustConformToSpecifiedDag) {
|
||||
// Tests that the calls must be in strict order when a complete order
|
||||
// is specified.
|
||||
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
|
||||
MockA a;
|
||||
MockB b;
|
||||
Sequence x, y;
|
||||
ON_CALL(a, ReturnResult(_))
|
||||
.WillByDefault(Return(Result()));
|
||||
|
||||
Sequence s;
|
||||
EXPECT_CALL(a, ReturnResult(1))
|
||||
.InSequence(x)
|
||||
.WillOnce(Return(Result()));
|
||||
|
||||
EXPECT_CALL(b, DoB())
|
||||
.Times(2)
|
||||
.InSequence(y);
|
||||
|
||||
.InSequence(s);
|
||||
EXPECT_CALL(a, ReturnResult(2))
|
||||
.InSequence(x, y)
|
||||
.WillRepeatedly(Return(Result()));
|
||||
.InSequence(s);
|
||||
|
||||
EXPECT_CALL(a, ReturnResult(3))
|
||||
.InSequence(x)
|
||||
.WillOnce(Return(Result()));
|
||||
// May only be called after a.ReturnResult(1).
|
||||
EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
a.ReturnResult(1);
|
||||
b.DoB();
|
||||
a.ReturnResult(2);
|
||||
}, "");
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
a.ReturnResult(2);
|
||||
}, "");
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
a.ReturnResult(3);
|
||||
}, "");
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED({
|
||||
a.ReturnResult(1);
|
||||
b.DoB();
|
||||
b.DoB();
|
||||
a.ReturnResult(3);
|
||||
a.ReturnResult(2);
|
||||
}, "");
|
||||
|
||||
b.DoB();
|
||||
a.ReturnResult(1);
|
||||
b.DoB();
|
||||
a.ReturnResult(3);
|
||||
a.ReturnResult(2);
|
||||
}
|
||||
|
||||
// Tests specifying a DAG using multiple sequences.
|
||||
class PartialOrderTest : public testing::Test {
|
||||
protected:
|
||||
PartialOrderTest() {
|
||||
ON_CALL(a_, ReturnResult(_))
|
||||
.WillByDefault(Return(Result()));
|
||||
|
||||
// Specifies this partial ordering:
|
||||
//
|
||||
// a.ReturnResult(1) ==>
|
||||
// a.ReturnResult(2) * n ==> a.ReturnResult(3)
|
||||
// b.DoB() * 2 ==>
|
||||
Sequence x, y;
|
||||
EXPECT_CALL(a_, ReturnResult(1))
|
||||
.InSequence(x);
|
||||
EXPECT_CALL(b_, DoB())
|
||||
.Times(2)
|
||||
.InSequence(y);
|
||||
EXPECT_CALL(a_, ReturnResult(2))
|
||||
.Times(AnyNumber())
|
||||
.InSequence(x, y);
|
||||
EXPECT_CALL(a_, ReturnResult(3))
|
||||
.InSequence(x);
|
||||
}
|
||||
|
||||
MockA a_;
|
||||
MockB b_;
|
||||
};
|
||||
|
||||
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
|
||||
a_.ReturnResult(1);
|
||||
b_.DoB();
|
||||
|
||||
// May only be called after the second DoB().
|
||||
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
|
||||
|
||||
b_.DoB();
|
||||
a_.ReturnResult(3);
|
||||
}
|
||||
|
||||
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
|
||||
// May only be called after ReturnResult(1).
|
||||
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
|
||||
|
||||
a_.ReturnResult(1);
|
||||
b_.DoB();
|
||||
b_.DoB();
|
||||
a_.ReturnResult(3);
|
||||
}
|
||||
|
||||
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
|
||||
// May only be called last.
|
||||
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
|
||||
|
||||
a_.ReturnResult(1);
|
||||
b_.DoB();
|
||||
b_.DoB();
|
||||
a_.ReturnResult(3);
|
||||
}
|
||||
|
||||
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
|
||||
a_.ReturnResult(1);
|
||||
b_.DoB();
|
||||
b_.DoB();
|
||||
a_.ReturnResult(3);
|
||||
|
||||
// May only be called before ReturnResult(3).
|
||||
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
|
||||
}
|
||||
|
||||
TEST(SequenceTest, Retirement) {
|
||||
|
@ -1478,14 +1588,14 @@ TEST(ExpectationSetTest, SizeWorks) {
|
|||
|
||||
TEST(ExpectationSetTest, IsEnumerable) {
|
||||
ExpectationSet es;
|
||||
EXPECT_THAT(es.begin(), Eq(es.end()));
|
||||
EXPECT_TRUE(es.begin() == es.end());
|
||||
|
||||
es += Expectation();
|
||||
ExpectationSet::const_iterator it = es.begin();
|
||||
EXPECT_THAT(it, Ne(es.end()));
|
||||
EXPECT_TRUE(it != es.end());
|
||||
EXPECT_THAT(*it, Eq(Expectation()));
|
||||
++it;
|
||||
EXPECT_THAT(it, Eq(es.end()));
|
||||
EXPECT_TRUE(it== es.end());
|
||||
}
|
||||
|
||||
// Tests the .After() clause.
|
||||
|
@ -1520,71 +1630,112 @@ TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
|
|||
a.DoA(2);
|
||||
}
|
||||
|
||||
// Calls must be in strict order when specified so.
|
||||
TEST(AfterDeathTest, CallsMustBeInStrictOrderWhenSpecifiedSo) {
|
||||
// Calls must be in strict order when specified so using .After().
|
||||
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
|
||||
MockA a;
|
||||
MockB b;
|
||||
|
||||
// Define ordering:
|
||||
// a.DoA(1) ==> b.DoB() ==> a.DoA(2)
|
||||
Expectation e1 = EXPECT_CALL(a, DoA(1));
|
||||
Expectation e2 = EXPECT_CALL(b, DoB())
|
||||
.After(e1);
|
||||
EXPECT_CALL(a, DoA(2))
|
||||
.After(e2);
|
||||
|
||||
a.DoA(1);
|
||||
|
||||
// May only be called after DoB().
|
||||
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
|
||||
|
||||
b.DoB();
|
||||
a.DoA(2);
|
||||
}
|
||||
|
||||
// Calls must be in strict order when specified so using .After().
|
||||
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
|
||||
MockA a;
|
||||
MockB b;
|
||||
|
||||
// Define ordering:
|
||||
// a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
|
||||
Expectation e1 = EXPECT_CALL(a, DoA(1));
|
||||
Expectation e2 = EXPECT_CALL(b, DoB())
|
||||
.Times(2)
|
||||
.After(e1);
|
||||
EXPECT_CALL(a, ReturnResult(2))
|
||||
.After(e2)
|
||||
.WillOnce(Return(Result()));
|
||||
EXPECT_CALL(a, DoA(2))
|
||||
.After(e2);
|
||||
|
||||
a.DoA(1);
|
||||
// If a call to ReturnResult() violates the specified order, no
|
||||
// matching expectation will be found, and thus the default action
|
||||
// will be done. Since the return type of ReturnResult() is not a
|
||||
// built-in type, gmock won't know what to return and will thus
|
||||
// abort the program. Therefore a death test can tell us whether
|
||||
// gmock catches the order violation correctly.
|
||||
//
|
||||
// gtest and gmock print messages to stdout, which isn't captured by
|
||||
// death tests. Therefore we have to match with an empty regular
|
||||
// expression in all the EXPECT_DEATH()s.
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(2), "");
|
||||
b.DoB();
|
||||
|
||||
// May only be called after the second DoB().
|
||||
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
|
||||
|
||||
b.DoB();
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(2), "");
|
||||
|
||||
b.DoB();
|
||||
a.ReturnResult(2);
|
||||
a.DoA(2);
|
||||
}
|
||||
|
||||
// Calls must satisfy the partial order when specified so.
|
||||
TEST(AfterDeathTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
|
||||
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
|
||||
MockA a;
|
||||
ON_CALL(a, ReturnResult(_))
|
||||
.WillByDefault(Return(Result()));
|
||||
|
||||
// Define ordering:
|
||||
// a.DoA(1) ==>
|
||||
// a.DoA(2) ==> a.ReturnResult(3)
|
||||
Expectation e = EXPECT_CALL(a, DoA(1));
|
||||
const ExpectationSet es = EXPECT_CALL(a, DoA(2));
|
||||
EXPECT_CALL(a, ReturnResult(3))
|
||||
.After(e, es)
|
||||
.WillOnce(Return(Result()));
|
||||
.After(e, es);
|
||||
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
|
||||
// May only be called last.
|
||||
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
|
||||
|
||||
a.DoA(2);
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
|
||||
|
||||
a.DoA(1);
|
||||
a.ReturnResult(3);
|
||||
}
|
||||
|
||||
// Calls must satisfy the partial order when specified so.
|
||||
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
|
||||
MockA a;
|
||||
|
||||
// Define ordering:
|
||||
// a.DoA(1) ==>
|
||||
// a.DoA(2) ==> a.DoA(3)
|
||||
Expectation e = EXPECT_CALL(a, DoA(1));
|
||||
const ExpectationSet es = EXPECT_CALL(a, DoA(2));
|
||||
EXPECT_CALL(a, DoA(3))
|
||||
.After(e, es);
|
||||
|
||||
a.DoA(2);
|
||||
|
||||
// May only be called last.
|
||||
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
|
||||
|
||||
a.DoA(1);
|
||||
a.DoA(3);
|
||||
}
|
||||
|
||||
// .After() can be combined with .InSequence().
|
||||
TEST(AfterDeathTest, CanBeUsedWithInSequence) {
|
||||
TEST(AfterTest, CanBeUsedWithInSequence) {
|
||||
MockA a;
|
||||
Sequence s;
|
||||
Expectation e = EXPECT_CALL(a, DoA(1));
|
||||
EXPECT_CALL(a, DoA(2)).InSequence(s);
|
||||
EXPECT_CALL(a, ReturnResult(3))
|
||||
.InSequence(s).After(e)
|
||||
.WillOnce(Return(Result()));
|
||||
EXPECT_CALL(a, DoA(3))
|
||||
.InSequence(s)
|
||||
.After(e);
|
||||
|
||||
a.DoA(1);
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
|
||||
|
||||
// May only be after DoA(2).
|
||||
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
|
||||
|
||||
a.DoA(2);
|
||||
a.ReturnResult(3);
|
||||
a.DoA(3);
|
||||
}
|
||||
|
||||
// .After() can be called multiple times.
|
||||
|
@ -1626,17 +1777,24 @@ TEST(AfterTest, AcceptsUpToFiveArguments) {
|
|||
// .After() allows input to contain duplicated Expectations.
|
||||
TEST(AfterTest, AcceptsDuplicatedInput) {
|
||||
MockA a;
|
||||
ON_CALL(a, ReturnResult(_))
|
||||
.WillByDefault(Return(Result()));
|
||||
|
||||
// Define ordering:
|
||||
// DoA(1) ==>
|
||||
// DoA(2) ==> ReturnResult(3)
|
||||
Expectation e1 = EXPECT_CALL(a, DoA(1));
|
||||
Expectation e2 = EXPECT_CALL(a, DoA(2));
|
||||
ExpectationSet es;
|
||||
es += e1;
|
||||
es += e2;
|
||||
EXPECT_CALL(a, ReturnResult(3))
|
||||
.After(e1, e2, es, e1)
|
||||
.WillOnce(Return(Result()));
|
||||
.After(e1, e2, es, e1);
|
||||
|
||||
a.DoA(1);
|
||||
EXPECT_DEATH_IF_SUPPORTED(a.ReturnResult(3), "");
|
||||
|
||||
// May only be after DoA(2).
|
||||
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
|
||||
|
||||
a.DoA(2);
|
||||
a.ReturnResult(3);
|
||||
|
@ -1852,7 +2010,7 @@ class MockC {
|
|||
public:
|
||||
MockC() {}
|
||||
|
||||
MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
|
||||
MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
|
||||
const Printable& x, Unprintable y));
|
||||
MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
|
||||
|
||||
|
@ -1862,32 +2020,43 @@ class MockC {
|
|||
|
||||
class VerboseFlagPreservingFixture : public testing::Test {
|
||||
protected:
|
||||
// The code needs to work when both ::string and ::std::string are defined
|
||||
// and the flag is implemented as a testing::internal::String. In this
|
||||
// case, without the call to c_str(), the compiler will complain that it
|
||||
// cannot figure out what overload of string constructor to use.
|
||||
// TODO(vladl@google.com): Use internal::string instead of String for
|
||||
// string flags in Google Test.
|
||||
VerboseFlagPreservingFixture()
|
||||
: saved_verbose_flag_(GMOCK_FLAG(verbose).c_str()) {}
|
||||
: saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
|
||||
|
||||
~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
|
||||
|
||||
private:
|
||||
const string saved_verbose_flag_;
|
||||
const std::string saved_verbose_flag_;
|
||||
|
||||
GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
|
||||
};
|
||||
|
||||
#if GTEST_HAS_STREAM_REDIRECTION
|
||||
|
||||
// Tests that an uninteresting mock function call generates a warning
|
||||
// containing the stack trace.
|
||||
TEST(FunctionCallMessageTest, UninterestingCallGeneratesFyiWithStackTrace) {
|
||||
MockC c;
|
||||
// Tests that an uninteresting mock function call on a naggy mock
|
||||
// generates a warning without the stack trace when
|
||||
// --gmock_verbose=warning is specified.
|
||||
TEST(FunctionCallMessageTest,
|
||||
UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
|
||||
GMOCK_FLAG(verbose) = kWarningVerbosity;
|
||||
NaggyMock<MockC> c;
|
||||
CaptureStdout();
|
||||
c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
|
||||
const String output = GetCapturedStdout();
|
||||
const std::string output = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
|
||||
EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
|
||||
}
|
||||
|
||||
// Tests that an uninteresting mock function call on a naggy mock
|
||||
// generates a warning containing the stack trace when
|
||||
// --gmock_verbose=info is specified.
|
||||
TEST(FunctionCallMessageTest,
|
||||
UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
|
||||
GMOCK_FLAG(verbose) = kInfoVerbosity;
|
||||
NaggyMock<MockC> c;
|
||||
CaptureStdout();
|
||||
c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
|
||||
const std::string output = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
|
||||
|
||||
|
@ -1904,20 +2073,21 @@ TEST(FunctionCallMessageTest, UninterestingCallGeneratesFyiWithStackTrace) {
|
|||
// stack trace.
|
||||
CaptureStdout();
|
||||
c.NonVoidMethod();
|
||||
const String output2 = GetCapturedStdout();
|
||||
const std::string output2 = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
|
||||
|
||||
# endif // NDEBUG
|
||||
}
|
||||
|
||||
// Tests that an uninteresting mock function call causes the function
|
||||
// arguments and return value to be printed.
|
||||
TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) {
|
||||
// Tests that an uninteresting mock function call on a naggy mock
|
||||
// causes the function arguments and return value to be printed.
|
||||
TEST(FunctionCallMessageTest,
|
||||
UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
|
||||
// A non-void mock function.
|
||||
MockB b;
|
||||
NaggyMock<MockB> b;
|
||||
CaptureStdout();
|
||||
b.DoB();
|
||||
const String output1 = GetCapturedStdout();
|
||||
const std::string output1 = GetCapturedStdout();
|
||||
EXPECT_PRED_FORMAT2(
|
||||
IsSubstring,
|
||||
"Uninteresting mock function call - returning default value.\n"
|
||||
|
@ -1926,10 +2096,10 @@ TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) {
|
|||
// Makes sure the return value is printed.
|
||||
|
||||
// A void mock function.
|
||||
MockC c;
|
||||
NaggyMock<MockC> c;
|
||||
CaptureStdout();
|
||||
c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
|
||||
const String output2 = GetCapturedStdout();
|
||||
const std::string output2 = GetCapturedStdout();
|
||||
EXPECT_THAT(output2.c_str(),
|
||||
ContainsRegex(
|
||||
"Uninteresting mock function call - returning directly\\.\n"
|
||||
|
@ -1947,9 +2117,9 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
|
|||
// should_print is true, the output should match the given regex and
|
||||
// contain the given function name in the stack trace. When it's
|
||||
// false, the output should be empty.)
|
||||
void VerifyOutput(const String& output, bool should_print,
|
||||
const string& expected_substring,
|
||||
const string& function_name) {
|
||||
void VerifyOutput(const std::string& output, bool should_print,
|
||||
const std::string& expected_substring,
|
||||
const std::string& function_name) {
|
||||
if (should_print) {
|
||||
EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
|
||||
# ifndef NDEBUG
|
||||
|
@ -1996,9 +2166,17 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
|
|||
"Binary");
|
||||
}
|
||||
|
||||
// Tests how the flag affects uninteresting calls.
|
||||
void TestUninterestingCall(bool should_print) {
|
||||
MockA a;
|
||||
// Tests how the flag affects uninteresting calls on a naggy mock.
|
||||
void TestUninterestingCallOnNaggyMock(bool should_print) {
|
||||
NaggyMock<MockA> a;
|
||||
const std::string note =
|
||||
"NOTE: You can safely ignore the above warning unless this "
|
||||
"call should not happen. Do not suppress it by blindly adding "
|
||||
"an EXPECT_CALL() if you don't mean to enforce the call. "
|
||||
"See "
|
||||
"https://github.com/google/googletest/blob/master/googlemock/docs/"
|
||||
"CookBook.md#"
|
||||
"knowing-when-to-expect for details.";
|
||||
|
||||
// A void-returning function.
|
||||
CaptureStdout();
|
||||
|
@ -2008,8 +2186,8 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
|
|||
should_print,
|
||||
"\nGMOCK WARNING:\n"
|
||||
"Uninteresting mock function call - returning directly.\n"
|
||||
" Function call: DoA(5)\n"
|
||||
"Stack trace:\n",
|
||||
" Function call: DoA(5)\n" +
|
||||
note,
|
||||
"DoA");
|
||||
|
||||
// A non-void-returning function.
|
||||
|
@ -2021,8 +2199,8 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
|
|||
"\nGMOCK WARNING:\n"
|
||||
"Uninteresting mock function call - returning default value.\n"
|
||||
" Function call: Binary(2, 1)\n"
|
||||
" Returns: false\n"
|
||||
"Stack trace:\n",
|
||||
" Returns: false\n" +
|
||||
note,
|
||||
"Binary");
|
||||
}
|
||||
};
|
||||
|
@ -2032,7 +2210,7 @@ class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
|
|||
TEST_F(GMockVerboseFlagTest, Info) {
|
||||
GMOCK_FLAG(verbose) = kInfoVerbosity;
|
||||
TestExpectedCall(true);
|
||||
TestUninterestingCall(true);
|
||||
TestUninterestingCallOnNaggyMock(true);
|
||||
}
|
||||
|
||||
// Tests that --gmock_verbose=warning causes uninteresting calls to be
|
||||
|
@ -2040,7 +2218,7 @@ TEST_F(GMockVerboseFlagTest, Info) {
|
|||
TEST_F(GMockVerboseFlagTest, Warning) {
|
||||
GMOCK_FLAG(verbose) = kWarningVerbosity;
|
||||
TestExpectedCall(false);
|
||||
TestUninterestingCall(true);
|
||||
TestUninterestingCallOnNaggyMock(true);
|
||||
}
|
||||
|
||||
// Tests that --gmock_verbose=warning causes neither expected nor
|
||||
|
@ -2048,7 +2226,7 @@ TEST_F(GMockVerboseFlagTest, Warning) {
|
|||
TEST_F(GMockVerboseFlagTest, Error) {
|
||||
GMOCK_FLAG(verbose) = kErrorVerbosity;
|
||||
TestExpectedCall(false);
|
||||
TestUninterestingCall(false);
|
||||
TestUninterestingCallOnNaggyMock(false);
|
||||
}
|
||||
|
||||
// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
|
||||
|
@ -2056,7 +2234,7 @@ TEST_F(GMockVerboseFlagTest, Error) {
|
|||
TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
|
||||
GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
|
||||
TestExpectedCall(false);
|
||||
TestUninterestingCall(true);
|
||||
TestUninterestingCallOnNaggyMock(true);
|
||||
}
|
||||
|
||||
#endif // GTEST_HAS_STREAM_REDIRECTION
|
||||
|
@ -2439,6 +2617,46 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
|
|||
EXPECT_EQ(2, b1.DoB(0));
|
||||
}
|
||||
|
||||
TEST(VerifyAndClearTest,
|
||||
DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
|
||||
linked_ptr<MockA> a(new MockA);
|
||||
ReferenceHoldingMock test_mock;
|
||||
|
||||
// EXPECT_CALL stores a reference to a inside test_mock.
|
||||
EXPECT_CALL(test_mock, AcceptReference(_))
|
||||
.WillRepeatedly(SetArgPointee<0>(a));
|
||||
|
||||
// Throw away the reference to the mock that we have in a. After this, the
|
||||
// only reference to it is stored by test_mock.
|
||||
a.reset();
|
||||
|
||||
// When test_mock goes out of scope, it destroys the last remaining reference
|
||||
// to the mock object originally pointed to by a. This will cause the MockA
|
||||
// destructor to be called from inside the ReferenceHoldingMock destructor.
|
||||
// The state of all mocks is protected by a single global lock, but there
|
||||
// should be no deadlock.
|
||||
}
|
||||
|
||||
TEST(VerifyAndClearTest,
|
||||
DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
|
||||
linked_ptr<MockA> a(new MockA);
|
||||
ReferenceHoldingMock test_mock;
|
||||
|
||||
// ON_CALL stores a reference to a inside test_mock.
|
||||
ON_CALL(test_mock, AcceptReference(_))
|
||||
.WillByDefault(SetArgPointee<0>(a));
|
||||
|
||||
// Throw away the reference to the mock that we have in a. After this, the
|
||||
// only reference to it is stored by test_mock.
|
||||
a.reset();
|
||||
|
||||
// When test_mock goes out of scope, it destroys the last remaining reference
|
||||
// to the mock object originally pointed to by a. This will cause the MockA
|
||||
// destructor to be called from inside the ReferenceHoldingMock destructor.
|
||||
// The state of all mocks is protected by a single global lock, but there
|
||||
// should be no deadlock.
|
||||
}
|
||||
|
||||
// Tests that a mock function's action can call a mock function
|
||||
// (either the same function or a different one) either as an explicit
|
||||
// action or as a default action without causing a dead lock. It
|
||||
|
@ -2463,9 +2681,78 @@ TEST(SynchronizationTest, CanCallMockMethodInAction) {
|
|||
// EXPECT_CALL() did not specify an action.
|
||||
}
|
||||
|
||||
TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
|
||||
MockA a;
|
||||
int do_a_arg0 = 0;
|
||||
ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
|
||||
int do_a_47_arg0 = 0;
|
||||
ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
|
||||
|
||||
a.DoA(17);
|
||||
EXPECT_THAT(do_a_arg0, 17);
|
||||
EXPECT_THAT(do_a_47_arg0, 0);
|
||||
a.DoA(47);
|
||||
EXPECT_THAT(do_a_arg0, 17);
|
||||
EXPECT_THAT(do_a_47_arg0, 47);
|
||||
|
||||
ON_CALL(a, Binary).WillByDefault(Return(true));
|
||||
ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
|
||||
EXPECT_THAT(a.Binary(14, 17), true);
|
||||
EXPECT_THAT(a.Binary(17, 14), false);
|
||||
}
|
||||
|
||||
TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
|
||||
MockB b;
|
||||
ON_CALL(b, DoB()).WillByDefault(Return(9));
|
||||
ON_CALL(b, DoB(5)).WillByDefault(Return(11));
|
||||
|
||||
EXPECT_THAT(b.DoB(), 9);
|
||||
EXPECT_THAT(b.DoB(1), 0); // default value
|
||||
EXPECT_THAT(b.DoB(5), 11);
|
||||
}
|
||||
|
||||
struct MockWithConstMethods {
|
||||
public:
|
||||
MOCK_CONST_METHOD1(Foo, int(int));
|
||||
MOCK_CONST_METHOD2(Bar, int(int, const char*));
|
||||
};
|
||||
|
||||
TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
|
||||
MockWithConstMethods mock;
|
||||
ON_CALL(mock, Foo).WillByDefault(Return(7));
|
||||
ON_CALL(mock, Bar).WillByDefault(Return(33));
|
||||
|
||||
EXPECT_THAT(mock.Foo(17), 7);
|
||||
EXPECT_THAT(mock.Bar(27, "purple"), 33);
|
||||
}
|
||||
|
||||
class MockConstOverload {
|
||||
public:
|
||||
MOCK_METHOD1(Overloaded, int(int));
|
||||
MOCK_CONST_METHOD1(Overloaded, int(int));
|
||||
};
|
||||
|
||||
TEST(ParameterlessExpectationsTest,
|
||||
CanSetExpectationsForConstOverloadedMethods) {
|
||||
MockConstOverload mock;
|
||||
ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
|
||||
ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
|
||||
ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
|
||||
ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
|
||||
|
||||
EXPECT_THAT(mock.Overloaded(1), 7);
|
||||
EXPECT_THAT(mock.Overloaded(5), 9);
|
||||
EXPECT_THAT(mock.Overloaded(7), 7);
|
||||
|
||||
const MockConstOverload& const_mock = mock;
|
||||
EXPECT_THAT(const_mock.Overloaded(1), 0);
|
||||
EXPECT_THAT(const_mock.Overloaded(5), 11);
|
||||
EXPECT_THAT(const_mock.Overloaded(7), 13);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Allows the user to define his own main and then invoke gmock_main
|
||||
// Allows the user to define their own main and then invoke gmock_main
|
||||
// from it. This might be necessary on some platforms which require
|
||||
// specific setup and teardown.
|
||||
#if GMOCK_RENAME_MAIN
|
||||
|
@ -2474,7 +2761,6 @@ int gmock_main(int argc, char **argv) {
|
|||
int main(int argc, char **argv) {
|
||||
#endif // GMOCK_RENAME_MAIN
|
||||
testing::InitGoogleMock(&argc, argv);
|
||||
|
||||
// Ensures that the tests pass no matter what value of
|
||||
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
|
||||
testing::GMOCK_FLAG(catch_leaked_mocks) = true;
|
||||
|
|
|
@ -26,13 +26,15 @@
|
|||
// 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++ Mocking Framework (Google Mock)
|
||||
//
|
||||
// Sometimes it's desirable to build most of Google Mock's own tests
|
||||
// by compiling a single file. This file serves this purpose.
|
||||
// Some users use a build system that Google Mock doesn't support directly,
|
||||
// yet they still want to build and run Google Mock's own tests. This file
|
||||
// includes most such tests, making it easier for these users to maintain
|
||||
// their build scripts (they just need to build this file, even though the
|
||||
// below list of actual *_test.cc files might change).
|
||||
#include "test/gmock-actions_test.cc"
|
||||
#include "test/gmock-cardinalities_test.cc"
|
||||
#include "test/gmock-generated-actions_test.cc"
|
||||
|
|
|
@ -0,0 +1,80 @@
|
|||
// 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.
|
||||
|
||||
|
||||
// Tests Google Mock's functionality that depends on exceptions.
|
||||
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
#if GTEST_HAS_EXCEPTIONS
|
||||
namespace {
|
||||
|
||||
using testing::HasSubstr;
|
||||
|
||||
using testing::internal::GoogleTestFailureException;
|
||||
|
||||
// A type that cannot be default constructed.
|
||||
class NonDefaultConstructible {
|
||||
public:
|
||||
explicit NonDefaultConstructible(int /* dummy */) {}
|
||||
};
|
||||
|
||||
class MockFoo {
|
||||
public:
|
||||
// A mock method that returns a user-defined type. Google Mock
|
||||
// doesn't know what the default value for this type is.
|
||||
MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible());
|
||||
};
|
||||
|
||||
TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {
|
||||
MockFoo mock;
|
||||
try {
|
||||
// No expectation is set on this method, so Google Mock must
|
||||
// return the default value. However, since Google Mock knows
|
||||
// nothing about the return type, it doesn't know what to return,
|
||||
// and has to throw (when exceptions are enabled) or abort
|
||||
// (otherwise).
|
||||
mock.GetNonDefaultConstructible();
|
||||
FAIL() << "GetNonDefaultConstructible()'s return type has no default "
|
||||
<< "value, so Google Mock should have thrown.";
|
||||
} catch (const GoogleTestFailureException& /* unused */) {
|
||||
FAIL() << "Google Test does not try to catch an exception of type "
|
||||
<< "GoogleTestFailureException, which is used for reporting "
|
||||
<< "a failure to other testing frameworks. Google Mock should "
|
||||
<< "not throw a GoogleTestFailureException as it will kill the "
|
||||
<< "entire test program instead of just the current TEST.";
|
||||
} catch (const std::exception& ex) {
|
||||
EXPECT_THAT(ex.what(), HasSubstr("has no default value"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} // unnamed namespace
|
||||
#endif
|
|
@ -31,59 +31,73 @@
|
|||
|
||||
"""Tests that leaked mock objects can be caught be Google Mock."""
|
||||
|
||||
__author__ = 'wan@google.com (Zhanyong Wan)'
|
||||
|
||||
|
||||
import gmock_test_utils
|
||||
|
||||
|
||||
PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')
|
||||
TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']
|
||||
TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*']
|
||||
TEST_MULTIPLE_LEAKS = [PROGRAM_PATH, '--gtest_filter=*MultipleLeaked*']
|
||||
|
||||
environ = gmock_test_utils.environ
|
||||
SetEnvVar = gmock_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(gmock_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)
|
||||
|
||||
|
||||
class GMockLeakTest(gmock_test_utils.TestCase):
|
||||
|
||||
def testCatchesLeakedMockByDefault(self):
|
||||
self.assertNotEqual(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL).exit_code)
|
||||
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL,
|
||||
env=environ).exit_code)
|
||||
self.assertNotEqual(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL).exit_code)
|
||||
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL,
|
||||
env=environ).exit_code)
|
||||
|
||||
def testDoesNotCatchLeakedMockWhenDisabled(self):
|
||||
self.assertEquals(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
|
||||
['--gmock_catch_leaked_mocks=0']).exit_code)
|
||||
['--gmock_catch_leaked_mocks=0'],
|
||||
env=environ).exit_code)
|
||||
self.assertEquals(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
|
||||
['--gmock_catch_leaked_mocks=0']).exit_code)
|
||||
['--gmock_catch_leaked_mocks=0'],
|
||||
env=environ).exit_code)
|
||||
|
||||
def testCatchesLeakedMockWhenEnabled(self):
|
||||
self.assertNotEqual(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
|
||||
['--gmock_catch_leaked_mocks']).exit_code)
|
||||
['--gmock_catch_leaked_mocks'],
|
||||
env=environ).exit_code)
|
||||
self.assertNotEqual(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +
|
||||
['--gmock_catch_leaked_mocks']).exit_code)
|
||||
['--gmock_catch_leaked_mocks'],
|
||||
env=environ).exit_code)
|
||||
|
||||
def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):
|
||||
self.assertNotEqual(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +
|
||||
['--gmock_catch_leaked_mocks=1']).exit_code)
|
||||
['--gmock_catch_leaked_mocks=1'],
|
||||
env=environ).exit_code)
|
||||
|
||||
def testCatchesMultipleLeakedMocks(self):
|
||||
self.assertNotEqual(
|
||||
0,
|
||||
gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS +
|
||||
['--gmock_catch_leaked_mocks']).exit_code)
|
||||
['--gmock_catch_leaked_mocks'],
|
||||
env=environ).exit_code)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue