Unverified Commit 21e51855 authored by Gennadiy Civil's avatar Gennadiy Civil Committed by GitHub
Browse files

Merge branch 'master' into josh/fix_scoped_class2

parents 3e2cb754 490554aa
...@@ -22,3 +22,33 @@ Win32-Debug/ ...@@ -22,3 +22,33 @@ Win32-Debug/
Win32-Release/ Win32-Release/
x64-Debug/ x64-Debug/
x64-Release/ x64-Release/
# Ignore autoconf / automake files
Makefile.in
aclocal.m4
configure
build-aux/
autom4te.cache/
googletest/m4/libtool.m4
googletest/m4/ltoptions.m4
googletest/m4/ltsugar.m4
googletest/m4/ltversion.m4
googletest/m4/lt~obsolete.m4
# Ignore generated directories.
googlemock/fused-src/
googletest/fused-src/
# macOS files
.DS_Store
# Ignore cmake generated directories and files.
CMakeFiles
CTestTestfile.cmake
Makefile
cmake_install.cmake
googlemock/CMakeFiles
googlemock/CTestTestfile.cmake
googlemock/Makefile
googlemock/cmake_install.cmake
googlemock/gtest
# Build matrix / environment variable are explained on: # Build matrix / environment variable are explained on:
# http://about.travis-ci.org/docs/user/build-configuration/ # https://docs.travis-ci.com/user/customizing-the-build/
# This file can be validated on: # This file can be validated on:
# http://lint.travis-ci.org/ # http://lint.travis-ci.org/
...@@ -12,28 +12,34 @@ matrix: ...@@ -12,28 +12,34 @@ matrix:
include: include:
- os: linux - os: linux
compiler: gcc compiler: gcc
sudo: true sudo : true
cache:
install: ./ci/install-linux.sh && ./ci/log-config.sh install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh script: ./ci/build-linux-bazel.sh
- os: linux - os: linux
compiler: clang compiler: clang
sudo: true sudo : true
cache:
install: ./ci/install-linux.sh && ./ci/log-config.sh install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh script: ./ci/build-linux-bazel.sh
- os: linux - os: linux
group: deprecated-2017Q4
compiler: gcc compiler: gcc
env: BUILD_TYPE=Debug VERBOSE=1 install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-autotools.sh
- os: linux - os: linux
group: deprecated-2017Q4
compiler: gcc compiler: gcc
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 env: BUILD_TYPE=Debug VERBOSE=1 CXX_FLAGS=-std=c++11
- os: linux - os: linux
group: deprecated-2017Q4
compiler: clang compiler: clang
env: BUILD_TYPE=Debug VERBOSE=1 env: BUILD_TYPE=Debug VERBOSE=1
- os: linux - os: linux
group: deprecated-2017Q4
compiler: clang compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11
- os: linux
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 NO_EXCEPTION=ON NO_RTTI=ON COMPILER_IS_GNUCXX=ON
- os: osx - os: osx
compiler: gcc compiler: gcc
env: BUILD_TYPE=Debug VERBOSE=1 env: BUILD_TYPE=Debug VERBOSE=1
...@@ -43,9 +49,10 @@ matrix: ...@@ -43,9 +49,10 @@ matrix:
- os: osx - os: osx
compiler: clang compiler: clang
env: BUILD_TYPE=Debug VERBOSE=1 env: BUILD_TYPE=Debug VERBOSE=1
if: type != pull_request
- os: osx - os: osx
compiler: clang
env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11
if: type != pull_request
# These are the install and build (script) phases for the most common entries in the matrix. They could be included # These are the install and build (script) phases for the most common entries in the matrix. They could be included
# in each entry in the matrix, but that is just repetitive. # in each entry in the matrix, but that is just repetitive.
......
# Copyright 2017 Google Inc. # Copyright 2017 Google Inc.
# All Rights Reserved. # All Rights Reserved.
# #
# #
...@@ -37,11 +37,21 @@ package(default_visibility = ["//visibility:public"]) ...@@ -37,11 +37,21 @@ package(default_visibility = ["//visibility:public"])
licenses(["notice"]) licenses(["notice"])
config_setting( config_setting(
name = "win", name = "windows",
values = {"cpu": "x64_windows"},
)
config_setting(
name = "windows_msvc",
values = {"cpu": "x64_windows_msvc"}, values = {"cpu": "x64_windows_msvc"},
) )
# Google Test including Google Mock config_setting(
name = "has_absl",
values = {"define": "absl=1"},
)
# Google Test including Google Mock
cc_library( cc_library(
name = "gtest", name = "gtest",
srcs = glob( srcs = glob(
...@@ -59,16 +69,25 @@ cc_library( ...@@ -59,16 +69,25 @@ cc_library(
"googlemock/src/gmock_main.cc", "googlemock/src/gmock_main.cc",
], ],
), ),
hdrs =glob([ hdrs = glob([
"googletest/include/gtest/*.h", "googletest/include/gtest/*.h",
"googlemock/include/gmock/*.h", "googlemock/include/gmock/*.h",
]), ]),
copts = select( copts = select(
{ {
":win": [], ":windows": [],
":windows_msvc": [],
"//conditions:default": ["-pthread"], "//conditions:default": ["-pthread"],
}, },
), ),
defines = select(
{
":has_absl": [
"GTEST_HAS_ABSL=1",
],
"//conditions:default": [],
},
),
includes = [ includes = [
"googlemock", "googlemock",
"googlemock/include", "googlemock/include",
...@@ -76,11 +95,25 @@ cc_library( ...@@ -76,11 +95,25 @@ cc_library(
"googletest/include", "googletest/include",
], ],
linkopts = select({ linkopts = select({
":win": [], ":windows": [],
":windows_msvc": [],
"//conditions:default": [ "//conditions:default": [
"-pthread", "-pthread",
], ],
}), }),
deps = select(
{
":has_absl": [
"@com_google_absl//absl/debugging:failure_signal_handler",
"@com_google_absl//absl/debugging:stacktrace",
"@com_google_absl//absl/debugging:symbolize",
"@com_google_absl//absl/strings",
"@com_google_absl//absl/types:optional",
"@com_google_absl//absl/types:variant",
],
"//conditions:default": [],
},
),
) )
cc_library( cc_library(
...@@ -88,7 +121,7 @@ cc_library( ...@@ -88,7 +121,7 @@ cc_library(
srcs = [ srcs = [
"googlemock/src/gmock_main.cc", "googlemock/src/gmock_main.cc",
], ],
deps = ["//:gtest"], deps = [":gtest"],
) )
# The following rules build samples of how to use gTest. # The following rules build samples of how to use gTest.
......
# How to become a contributor and submit your own code
## Contributor License Agreements
We'd love to accept your patches! Before we can take them, we
have to jump a couple of legal hurdles.
Please fill out either the individual or corporate Contributor License Agreement
(CLA).
* If you are an individual writing original source code and you're sure you
own the intellectual property, then you'll need to sign an
[individual CLA](https://developers.google.com/open-source/cla/individual).
* If you work for a company that wants to allow you to contribute your work,
then you'll need to sign a
[corporate CLA](https://developers.google.com/open-source/cla/corporate).
Follow either of the two links above to access the appropriate CLA and
instructions for how to sign and return it. Once we receive it, we'll be able to
accept your pull requests.
## Contributing A Patch
1. Submit an issue describing your proposed change to the
[issue tracker](https://github.com/google/googletest).
1. Please don't mix more than one logical change per submittal,
because it makes the history hard to follow. If you want to make a
change that doesn't have a corresponding issue in the issue
tracker, please create one.
1. Also, coordinate with team members that are listed on the issue in
question. This ensures that work isn't being duplicated and
communicating your plan early also generally leads to better
patches.
1. If your proposed change is accepted, and you haven't already done so, sign a
Contributor License Agreement (see details above).
1. Fork the desired repo, develop and test your code changes.
1. Ensure that your code adheres to the existing style in the sample to which
you are contributing.
1. Ensure that your code has an appropriate set of unit tests which all pass.
1. Submit a pull request.
If you are a Googler, it is preferable to first create an internal change and
have it reviewed and submitted, and then create an upstreaming pull
request here.
## The Google Test and Google Mock Communities ##
The Google Test community exists primarily through the
[discussion group](http://groups.google.com/group/googletestframework)
and the GitHub repository.
Likewise, the Google Mock community exists primarily through their own
[discussion group](http://groups.google.com/group/googlemock).
You are definitely encouraged to contribute to the
discussion and you can also help us to keep the effectiveness of the
group high by following and promoting the guidelines listed here.
### Please Be Friendly ###
Showing courtesy and respect to others is a vital part of the Google
culture, and we strongly encourage everyone participating in Google
Test development to join us in accepting nothing less. Of course,
being courteous is not the same as failing to constructively disagree
with each other, but it does mean that we should be respectful of each
other when enumerating the 42 technical reasons that a particular
proposal may not be the best choice. There's never a reason to be
antagonistic or dismissive toward anyone who is sincerely trying to
contribute to a discussion.
Sure, C++ testing is serious business and all that, but it's also
a lot of fun. Let's keep it that way. Let's strive to be one of the
friendliest communities in all of open source.
As always, discuss Google Test in the official GoogleTest discussion group.
You don't have to actually submit code in order to sign up. Your participation
itself is a valuable contribution.
## Style
To keep the source consistent, readable, diffable and easy to merge,
we use a fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project. All patches will be expected
to conform to the style outlined [here](https://google.github.io/styleguide/cppguide.html).
## Requirements for Contributors ###
If you plan to contribute a patch, you need to build Google Test,
Google Mock, and their own tests from a git checkout, which has
further requirements:
* [Python](https://www.python.org/) v2.3 or newer (for running some of
the tests and re-generating certain source files from templates)
* [CMake](https://cmake.org/) v2.6.4 or newer
* [GNU Build System](https://en.wikipedia.org/wiki/GNU_Build_System)
including automake (>= 1.9), autoconf (>= 2.59), and
libtool / libtoolize.
## Developing Google Test ##
This section discusses how to make your own changes to Google Test.
### Testing Google Test Itself ###
To make sure your changes work as intended and don't break existing
functionality, you'll want to compile and run Google Test's own tests.
For that you can use CMake:
mkdir mybuild
cd mybuild
cmake -Dgtest_build_tests=ON ${GTEST_DIR}
Make sure you have Python installed, as some of Google Test's tests
are written in Python. If the cmake command complains about not being
able to find Python (`Could NOT find PythonInterp (missing:
PYTHON_EXECUTABLE)`), try telling it explicitly where your Python
executable can be found:
cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR}
Next, you can build Google Test and all of its own tests. On \*nix,
this is usually done by 'make'. To run the tests, do
make test
All tests should pass.
### Regenerating Source Files ##
Some of Google Test's source files are generated from templates (not
in the C++ sense) using a script.
For example, the
file include/gtest/internal/gtest-type-util.h.pump is used to generate
gtest-type-util.h in the same directory.
You don't need to worry about regenerating the source files
unless you need to modify them. You would then modify the
corresponding `.pump` files and run the '[pump.py](googletest/scripts/pump.py)'
generator script. See the [Pump Manual](googletest/docs/PumpManual.md).
## 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 above to configure Google Mock.
Then, create a build output directory and enter it. Next,
${GMOCK_DIR}/configure # try --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.
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.
## Process this file with automake to produce Makefile.in
ACLOCAL_AMFLAGS = -I m4
AUTOMAKE_OPTIONS = foreign
# Build . before src so that our all-local and clean-local hooks kicks in at
# the right time.
SUBDIRS = googletest googlemock
EXTRA_DIST = \
BUILD.bazel \
CMakeLists.txt \
README.md \
WORKSPACE
...@@ -4,6 +4,12 @@ ...@@ -4,6 +4,12 @@
[![Build Status](https://travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest) [![Build Status](https://travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest)
[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) [![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master)
**Future Plans**:
* 1.8.x Release - the 1.8.x will be the last release that works with pre-C++11 compilers. The 1.8.1 will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical"
* Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release
* Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy)
Welcome to **Google Test**, Google's C++ test framework! Welcome to **Google Test**, Google's C++ test framework!
This repository is a merger of the formerly separate GoogleTest and This repository is a merger of the formerly separate GoogleTest and
...@@ -15,8 +21,8 @@ mailing list for questions, discussions, and development. There is ...@@ -15,8 +21,8 @@ mailing list for questions, discussions, and development. There is
also an IRC channel on [OFTC](https://webchat.oftc.net/) (irc.oftc.net) #gtest available. Please also an IRC channel on [OFTC](https://webchat.oftc.net/) (irc.oftc.net) #gtest available. Please
join us! join us!
Getting started information for **Google Test** is available in the Getting started information for **Google Test** is available in the
[Google Test Primer](googletest/docs/Primer.md) documentation. [Google Test Primer](googletest/docs/primer.md) documentation.
**Google Mock** is an extension to Google Test for writing and using C++ mock **Google Mock** is an extension to Google Test for writing and using C++ mock
classes. See the separate [Google Mock documentation](googlemock/README.md). classes. See the separate [Google Mock documentation](googlemock/README.md).
...@@ -103,7 +109,7 @@ package (as described below): ...@@ -103,7 +109,7 @@ package (as described below):
### Windows Requirements ### ### Windows Requirements ###
* Microsoft Visual C++ 2010 or newer * Microsoft Visual C++ 2015 or newer
### Cygwin Requirements ### ### Cygwin Requirements ###
...@@ -114,35 +120,9 @@ package (as described below): ...@@ -114,35 +120,9 @@ package (as described below):
* Mac OS X v10.4 Tiger or newer * Mac OS X v10.4 Tiger or newer
* Xcode Developer Tools * Xcode Developer Tools
### Requirements for Contributors ### ## Contributing change
We welcome patches. If you plan to contribute a patch, you need to
build Google Test and its own tests from a git checkout (described
below), which has further requirements:
* [Python](https://www.python.org/) v2.3 or newer (for running some of
the tests and re-generating certain source files from templates)
* [CMake](https://cmake.org/) v2.6.4 or newer
## Regenerating Source Files ##
Some of Google Test's source files are generated from templates (not
in the C++ sense) using a script.
For example, the
file include/gtest/internal/gtest-type-util.h.pump is used to generate
gtest-type-util.h in the same directory.
You don't need to worry about regenerating the source files
unless you need to modify them. You would then modify the
corresponding `.pump` files and run the '[pump.py](googletest/scripts/pump.py)'
generator script. See the [Pump Manual](googletest/docs/PumpManual.md).
### Contributing Code ###
We welcome patches. Please read the Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on
[Developer's Guide](googletest/docs/DevGuide.md) how to contribute to this project.
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.
Happy testing! Happy testing!
workspace(name = "com_google_googletest") workspace(name = "com_google_googletest")
# Abseil
http_archive(
name = "com_google_absl",
urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"],
strip_prefix = "abseil-cpp-master",
)
...@@ -11,28 +11,15 @@ environment: ...@@ -11,28 +11,15 @@ environment:
- compiler: msvc-15-seh - compiler: msvc-15-seh
generator: "Visual Studio 15 2017 Win64" generator: "Visual Studio 15 2017 Win64"
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
enabled_on_pr: yes
- compiler: msvc-14-seh - compiler: msvc-14-seh
generator: "Visual Studio 14 2015" generator: "Visual Studio 14 2015"
enabled_on_pr: yes
- compiler: msvc-14-seh - compiler: msvc-14-seh
generator: "Visual Studio 14 2015 Win64" generator: "Visual Studio 14 2015 Win64"
- compiler: msvc-12-seh
generator: "Visual Studio 12 2013"
- compiler: msvc-12-seh
generator: "Visual Studio 12 2013 Win64"
- compiler: msvc-11-seh
generator: "Visual Studio 11 2012"
- compiler: msvc-11-seh
generator: "Visual Studio 11 2012 Win64"
- compiler: msvc-10-seh
generator: "Visual Studio 10 2010"
- compiler: gcc-5.3.0-posix - compiler: gcc-5.3.0-posix
generator: "MinGW Makefiles" generator: "MinGW Makefiles"
cxx_path: 'C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin' cxx_path: 'C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin'
...@@ -43,7 +30,6 @@ environment: ...@@ -43,7 +30,6 @@ environment:
configuration: configuration:
- Debug - Debug
#- Release
build: build:
verbosity: minimal verbosity: minimal
...@@ -52,6 +38,14 @@ install: ...@@ -52,6 +38,14 @@ install:
- ps: | - ps: |
Write-Output "Compiler: $env:compiler" Write-Output "Compiler: $env:compiler"
Write-Output "Generator: $env:generator" Write-Output "Generator: $env:generator"
if (-not (Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER)) {
Write-Output "This is *NOT* a pull request build"
} else {
Write-Output "This is a pull request build"
if (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes") {
Write-Output "PR builds are *NOT* explicitly enabled"
}
}
# git bash conflicts with MinGW makefiles # git bash conflicts with MinGW makefiles
if ($env:generator -eq "MinGW Makefiles") { if ($env:generator -eq "MinGW Makefiles") {
...@@ -63,6 +57,10 @@ install: ...@@ -63,6 +57,10 @@ install:
build_script: build_script:
- ps: | - ps: |
# Only enable some builds for pull requests, the AppVeyor queue is too long.
if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
return
}
md _build -Force | Out-Null md _build -Force | Out-Null
cd _build cd _build
...@@ -74,17 +72,27 @@ build_script: ...@@ -74,17 +72,27 @@ build_script:
if ($LastExitCode -ne 0) { if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage" throw "Exec: $ErrorMessage"
} }
& cmake --build . --config $env:configuration $cmake_parallel = if ($env:generator -eq "MinGW Makefiles") {"-j2"} else {"/m"}
& cmake --build . --config $env:configuration -- $cmake_parallel
if ($LastExitCode -ne 0) { if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage" throw "Exec: $ErrorMessage"
} }
skip_commits:
files:
- '**/*.md'
test_script: test_script:
- ps: | - ps: |
# Only enable some builds for pull requests, the AppVeyor queue is too long.
if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) {
return
}
if ($env:generator -eq "MinGW Makefiles") { if ($env:generator -eq "MinGW Makefiles") {
return # No test available for MinGW return # No test available for MinGW
} }
& ctest -C $env:configuration --timeout 300 --output-on-failure & ctest -C $env:configuration --timeout 600 --output-on-failure
if ($LastExitCode -ne 0) { if ($LastExitCode -ne 0) {
throw "Exec: $ErrorMessage" throw "Exec: $ErrorMessage"
} }
......
#!/usr/bin/env bash
# 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.
set -e
. ci/get-nprocessors.sh
# Create the configuration script
autoreconf -i
# Run in a subdirectory to keep the sources clean
mkdir build || true
cd build
../configure
make -j ${NPROCESSORS:-2}
...@@ -33,3 +33,4 @@ set -e ...@@ -33,3 +33,4 @@ set -e
bazel build --curses=no //...:all bazel build --curses=no //...:all
bazel test --curses=no //...:all bazel test --curses=no //...:all
bazel test --curses=no //...:all --define absl=1
#!/usr/bin/env bash
# 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.
# This file is typically sourced by another script.
# if possible, ask for the precise number of processors,
# otherwise take 2 processors as reasonable default; see
# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization
if [ -x /usr/bin/getconf ]; then
NPROCESSORS=$(/usr/bin/getconf _NPROCESSORS_ONLN)
else
NPROCESSORS=2
fi
# as of 2017-09-04 Travis CI reports 32 processors, but GCC build
# crashes if parallelized too much (maybe memory consumption problem),
# so limit to 4 processors for the time being.
if [ $NPROCESSORS -gt 4 ] ; then
echo "$0:Note: Limiting processors to use by make from $NPROCESSORS to 4."
NPROCESSORS=4
fi
#!/usr/bin/env sh #!/usr/bin/env sh
set -evx set -evx
. ci/get-nprocessors.sh
# if possible, ask for the precise number of processors, # if possible, ask for the precise number of processors,
# otherwise take 2 processors as reasonable default; see # otherwise take 2 processors as reasonable default; see
# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization # https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization
...@@ -22,11 +24,19 @@ export MAKEFLAGS ...@@ -22,11 +24,19 @@ export MAKEFLAGS
env | sort env | sort
# Set default values to OFF for these variables if not specified.
: "${NO_EXCEPTION:=OFF}"
: "${NO_RTTI:=OFF}"
: "${COMPILER_IS_GNUCXX:=OFF}"
mkdir build || true mkdir build || true
cd build cd build
cmake -Dgtest_build_samples=ON \ cmake -Dgtest_build_samples=ON \
-Dgtest_build_tests=ON \ -Dgtest_build_tests=ON \
-Dgmock_build_tests=ON \ -Dgmock_build_tests=ON \
-Dcxx_no_exception=$NO_EXCEPTION \
-Dcxx_no_rtti=$NO_RTTI \
-DCMAKE_COMPILER_IS_GNUCXX=$COMPILER_IS_GNUCXX \
-DCMAKE_CXX_FLAGS=$CXX_FLAGS \ -DCMAKE_CXX_FLAGS=$CXX_FLAGS \
-DCMAKE_BUILD_TYPE=$BUILD_TYPE \ -DCMAKE_BUILD_TYPE=$BUILD_TYPE \
.. ..
......
AC_INIT([Google C++ Mocking and Testing Frameworks],
[1.8.0],
[googlemock@googlegroups.com],
[googletest])
# Provide various options to initialize the Autoconf and configure processes.
AC_PREREQ([2.59])
AC_CONFIG_SRCDIR([./README.md])
AC_CONFIG_AUX_DIR([build-aux])
AC_CONFIG_FILES([Makefile])
AC_CONFIG_SUBDIRS([googletest googlemock])
AM_INIT_AUTOMAKE
# Output the generated files. No further autoconf macros may be used.
AC_OUTPUT
...@@ -88,16 +88,23 @@ endif() ...@@ -88,16 +88,23 @@ endif()
# Google Mock libraries. We build them using more strict warnings than what # 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 # are used for other targets, to ensure that Google Mock can be compiled by
# a user aggressive about warnings. # a user aggressive about warnings.
cxx_library(gmock if (MSVC)
"${cxx_strict}" cxx_library(gmock
"${gtest_dir}/src/gtest-all.cc" "${cxx_strict}"
src/gmock-all.cc) "${gtest_dir}/src/gtest-all.cc"
src/gmock-all.cc)
cxx_library(gmock_main
"${cxx_strict}" cxx_library(gmock_main
"${gtest_dir}/src/gtest-all.cc" "${cxx_strict}"
src/gmock-all.cc "${gtest_dir}/src/gtest-all.cc"
src/gmock_main.cc) src/gmock-all.cc
src/gmock_main.cc)
else()
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
target_link_libraries(gmock gtest)
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
target_link_libraries(gmock_main gmock)
endif()
# If the CMake version supports it, attach header directory information # 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 # to the targets for when we are part of a parent build (ie being pulled
...@@ -112,22 +119,22 @@ endif() ...@@ -112,22 +119,22 @@ endif()
# Install rules # Install rules
if(INSTALL_GMOCK) if(INSTALL_GMOCK)
install(TARGETS gmock gmock_main install(TARGETS gmock gmock_main
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}")
install(DIRECTORY ${gmock_SOURCE_DIR}/include/gmock install(DIRECTORY "${gmock_SOURCE_DIR}/include/gmock"
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
# configure and install pkgconfig files # configure and install pkgconfig files
configure_file( configure_file(
cmake/gmock.pc.in cmake/gmock.pc.in
"${CMAKE_BINARY_DIR}/gmock.pc" "${gmock_BINARY_DIR}/gmock.pc"
@ONLY) @ONLY)
configure_file( configure_file(
cmake/gmock_main.pc.in cmake/gmock_main.pc.in
"${CMAKE_BINARY_DIR}/gmock_main.pc" "${gmock_BINARY_DIR}/gmock_main.pc"
@ONLY) @ONLY)
install(FILES "${CMAKE_BINARY_DIR}/gmock.pc" "${CMAKE_BINARY_DIR}/gmock_main.pc" install(FILES "${gmock_BINARY_DIR}/gmock.pc" "${gmock_BINARY_DIR}/gmock_main.pc"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
endif() endif()
...@@ -177,23 +184,33 @@ if (gmock_build_tests) ...@@ -177,23 +184,33 @@ if (gmock_build_tests)
############################################################ ############################################################
# C++ tests built with non-standard compiler flags. # C++ tests built with non-standard compiler flags.
cxx_library(gmock_main_no_exception "${cxx_no_exception}" if (MSVC)
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) 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 (NOT MSVC OR MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010. cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
# 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) "${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}" if (MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010.
gmock_main_use_own_tuple test/gmock-spec-builders_test.cc) # 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 gmock)
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc)
target_link_libraries(gmock_main_no_rtti gmock)
cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}" src/gmock_main.cc)
target_link_libraries(gmock_main_use_own_tuple gmock)
endif() endif()
cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}"
gmock_main_no_exception test/gmock-more-actions_test.cc) gmock_main_no_exception test/gmock-more-actions_test.cc)
......
...@@ -53,7 +53,7 @@ the Apache License, which is different from Google Mock's license. ...@@ -53,7 +53,7 @@ the Apache License, which is different from Google Mock's license.
If you are new to the project, we suggest that you read the user If you are new to the project, we suggest that you read the user
documentation in the following order: documentation in the following order:
* Learn the [basics](../../master/googletest/docs/Primer.md) of * Learn the [basics](../../master/googletest/docs/primer.md) of
Google Test, if you choose to use Google Mock with it (recommended). Google Test, if you choose to use Google Mock with it (recommended).
* Read [Google Mock for Dummies](../../master/googlemock/docs/ForDummies.md). * Read [Google Mock for Dummies](../../master/googlemock/docs/ForDummies.md).
* Read the instructions below on how to build Google Mock. * Read the instructions below on how to build Google Mock.
...@@ -129,20 +129,20 @@ build Google Mock and its tests, which has further requirements: ...@@ -129,20 +129,20 @@ build Google Mock and its tests, which has further requirements:
If you have CMake available, it is recommended that you follow the If you have CMake available, it is recommended that you follow the
[build instructions][gtest_cmakebuild] [build instructions][gtest_cmakebuild]
as described for Google Test. as described for Google Test.
If are using Google Mock with an If are using Google Mock with an
existing CMake project, the section existing CMake project, the section
[Incorporating Into An Existing CMake Project][gtest_incorpcmake] [Incorporating Into An Existing CMake Project][gtest_incorpcmake]
may be of particular interest. may be of particular interest.
To make it work for Google Mock you will need to change To make it work for Google Mock you will need to change
target_link_libraries(example gtest_main) target_link_libraries(example gtest_main)
to to
target_link_libraries(example gmock_main) target_link_libraries(example gmock_main)
This works because `gmock_main` library is compiled with Google Test. This works because `gmock_main` library is compiled with Google Test.
However, it does not automatically add Google Test includes. However, it does not automatically add Google Test includes.
Therefore you will also have to change Therefore you will also have to change
...@@ -161,8 +161,8 @@ to ...@@ -161,8 +161,8 @@ to
"${gtest_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}/include") "${gtest_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}/include")
endif() endif()
This will addtionally mark Google Mock includes as system, which will This will addtionally mark Google Mock includes as system, which will
silence compiler warnings when compiling your tests using clang with silence compiler warnings when compiling your tests using clang with
`-Wpedantic -Wall -Wextra -Wconversion`. `-Wpedantic -Wall -Wextra -Wconversion`.
...@@ -337,38 +337,6 @@ use the new matcher API ( ...@@ -337,38 +337,6 @@ use the new matcher API (
[polymorphic](./docs/CookBook.md#writing-new-polymorphic-matchers)). [polymorphic](./docs/CookBook.md#writing-new-polymorphic-matchers)).
Matchers defined using `MATCHER()` or `MATCHER_P*()` aren't affected. Matchers defined using `MATCHER()` or `MATCHER_P*()` aren't affected.
### 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 above to configure Google Mock.
Then, create a build output directory and enter it. Next,
${GMOCK_DIR}/configure # try --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.
#### Contributing a Patch ####
We welcome patches.
Please read the [Developer's Guide](docs/DevGuide.md)
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.
Happy testing! Happy testing!
[gtest_readme]: ../googletest/README.md "googletest" [gtest_readme]: ../googletest/README.md "googletest"
......
...@@ -129,7 +129,7 @@ AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"], ...@@ -129,7 +129,7 @@ AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"],
GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags` GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags`
GTEST_LIBS=`${GTEST_CONFIG} --libs` GTEST_LIBS=`${GTEST_CONFIG} --libs`
GTEST_VERSION=`${GTEST_CONFIG} --version`], GTEST_VERSION=`${GTEST_CONFIG} --version`],
[AC_CONFIG_SUBDIRS([../googletest]) [
# GTEST_CONFIG needs to be executable both in a Makefile environment 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. # in a shell script environment, so resolve an absolute path for it here.
GTEST_CONFIG="`pwd -P`/../googletest/scripts/gtest-config" GTEST_CONFIG="`pwd -P`/../googletest/scripts/gtest-config"
......
...@@ -178,6 +178,8 @@ divided into several categories: ...@@ -178,6 +178,8 @@ divided into several categories:
|`Ne(value)` |`argument != value`| |`Ne(value)` |`argument != value`|
|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| |`IsNull()` |`argument` is a `NULL` pointer (raw or smart).|
|`NotNull()` |`argument` is a non-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`.| |`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.| |`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.|
...@@ -227,7 +229,7 @@ The `argument` can be either a C string or a C++ string object: ...@@ -227,7 +229,7 @@ The `argument` can be either a C string or a C++ string object:
`ContainsRegex()` and `MatchesRegex()` use the regular expression `ContainsRegex()` and `MatchesRegex()` use the regular expression
syntax defined syntax defined
[here](../../googletest/docs/AdvancedGuide.md#regular-expression-syntax). [here](../../googletest/docs/advanced.md#regular-expression-syntax).
`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide `StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide
strings as well. strings as well.
...@@ -347,7 +349,7 @@ You can make a matcher from one or more other matchers: ...@@ -347,7 +349,7 @@ You can make a matcher from one or more other matchers:
## Matchers as Test Assertions ## ## 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`.| |`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`. | |`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. |
......
...@@ -1231,7 +1231,7 @@ that references the implementation object dies, the implementation ...@@ -1231,7 +1231,7 @@ that references the implementation object dies, the implementation
object will be deleted. object will be deleted.
Therefore, if you have some complex matcher that you want to use again Therefore, if you have some complex matcher that you want to use again
and again, there is no need to build it everytime. Just assign it to a and again, there is no need to build it every time. Just assign it to a
matcher variable and use that variable repeatedly! For example, matcher variable and use that variable repeatedly! For example,
``` ```
...@@ -1403,7 +1403,7 @@ edge from node A to node B wherever A must occur before B, we can get ...@@ -1403,7 +1403,7 @@ edge from node A to node B wherever A must occur before B, we can get
a DAG. We use the term "sequence" to mean a directed path in this a DAG. We use the term "sequence" to mean a directed path in this
DAG. Now, if we decompose the DAG into sequences, we just need to know DAG. Now, if we decompose the DAG into sequences, we just need to know
which sequences each `EXPECT_CALL()` belongs to in order to be able to which sequences each `EXPECT_CALL()` belongs to in order to be able to
reconstruct the orginal DAG. reconstruct the original DAG.
So, to specify the partial order on the expectations we need to do two So, to specify the partial order on the expectations we need to do two
things: first to define some `Sequence` objects, and then for each things: first to define some `Sequence` objects, and then for each
...@@ -2182,7 +2182,7 @@ the implementation object dies, the implementation object will be ...@@ -2182,7 +2182,7 @@ the implementation object dies, the implementation object will be
deleted. deleted.
If you have some complex action that you want to use again and again, If you have some complex action that you want to use again and again,
you may not have to build it from scratch everytime. If the action you may not have to build it from scratch every time. If the action
doesn't have an internal state (i.e. if it always does the same thing doesn't have an internal state (i.e. if it always does the same thing
no matter how many times it has been called), you can assign it to an no matter how many times it has been called), you can assign it to an
action variable and use that variable repeatedly. For example: action variable and use that variable repeatedly. For example:
...@@ -2229,77 +2229,71 @@ versus ...@@ -2229,77 +2229,71 @@ versus
## Mocking Methods That Use Move-Only Types ## ## Mocking Methods That Use Move-Only Types ##
C++11 introduced <em>move-only types</em>. A move-only-typed value can be moved from one object to another, but cannot be copied. `std::unique_ptr<T>` is probably the most commonly used move-only type. C++11 introduced *move-only types*. A move-only-typed value can be moved from
one object to another, but cannot be copied. `std::unique_ptr<T>` is
probably the most commonly used move-only type.
Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable. This recipe shows you how you can do it. Mocking a method that takes and/or returns move-only types presents some
challenges, but nothing insurmountable. This recipe shows you how you can do it.
Note that the support for move-only method arguments was only introduced to
gMock in April 2017; in older code, you may find more complex
[workarounds](#LegacyMoveOnly) for lack of this feature.
Let’s say we are working on a fictional project that lets one post and share snippets called “buzzes”. Your code uses these types: Let’s say we are working on a fictional project that lets one post and share
snippets called “buzzes”. Your code uses these types:
``` ```cpp
enum class AccessLevel { kInternal, kPublic }; enum class AccessLevel { kInternal, kPublic };
class Buzz { class Buzz {
public: public:
explicit Buzz(AccessLevel access) { } explicit Buzz(AccessLevel access) { ... }
... ...
}; };
class Buzzer { class Buzzer {
public: public:
virtual ~Buzzer() {} virtual ~Buzzer() {}
virtual std::unique_ptr<Buzz> MakeBuzz(const std::string& text) = 0; virtual std::unique_ptr<Buzz> MakeBuzz(StringPiece text) = 0;
virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) = 0; virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, int64_t timestamp) = 0;
... ...
}; };
``` ```
A `Buzz` object represents a snippet being posted. A class that implements the `Buzzer` interface is capable of creating and sharing `Buzz`. Methods in `Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`. Now we need to mock `Buzzer` in our tests. A `Buzz` object represents a snippet being posted. A class that implements the
`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in
To mock a method that returns a move-only type, you just use the familiar `MOCK_METHOD` syntax as usual: `Buzzer` may return a `unique_ptr<Buzz>` or take a
`unique_ptr<Buzz>`. Now we need to mock `Buzzer` in our tests.
```
class MockBuzzer : public Buzzer {
public:
MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
};
```
However, if you attempt to use the same `MOCK_METHOD` pattern to mock a method that takes a move-only parameter, you’ll get a compiler error currently:
```
// Does NOT compile!
MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, Time timestamp));
```
While it’s highly desirable to make this syntax just work, it’s not trivial and the work hasn’t been done yet. Fortunately, there is a trick you can apply today to get something that works nearly as well as this.
The trick, is to delegate the `ShareBuzz()` method to a mock method (let’s call it `DoShareBuzz()`) that does not take move-only parameters: To mock a method that accepts or returns move-only types, you just use the
familiar `MOCK_METHOD` syntax as usual:
``` ```cpp
class MockBuzzer : public Buzzer { class MockBuzzer : public Buzzer {
public: public:
MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text)); MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(StringPiece text));
MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, int64_t timestamp));
bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) {
return DoShareBuzz(buzz.get(), timestamp);
}
}; };
``` ```
Note that there's no need to define or declare `DoShareBuzz()` in a base class. You only need to define it as a `MOCK_METHOD` in the mock class. Now that we have the mock class defined, we can use it in tests. In the
following code examples, we assume that we have defined a `MockBuzzer` object
Now that we have the mock class defined, we can use it in tests. In the following code examples, we assume that we have defined a `MockBuzzer` object named `mock_buzzer_`: named `mock_buzzer_`:
``` ```cpp
MockBuzzer mock_buzzer_; MockBuzzer mock_buzzer_;
``` ```
First let’s see how we can set expectations on the `MakeBuzz()` method, which returns a `unique_ptr<Buzz>`. First let’s see how we can set expectations on the `MakeBuzz()` method, which
returns a `unique_ptr<Buzz>`.
As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or `.WillRepeated()` clause), when that expectation fires, the default action for that method will be taken. Since `unique_ptr<>` has a default constructor that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an action: As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or
`.WillRepeated()` clause), when that expectation fires, the default action for
that method will be taken. Since `unique_ptr<>` has a default constructor
that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an
action:
``` ```cpp
// Use the default action. // Use the default action.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); EXPECT_CALL(mock_buzzer_, MakeBuzz("hello"));
...@@ -2307,32 +2301,13 @@ As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or ...@@ -2307,32 +2301,13 @@ As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or
EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello"));
``` ```
If you are not happy with the default action, you can tweak it. Depending on what you need, you may either tweak the default action for a specific (mock object, mock method) combination using `ON_CALL()`, or you may tweak the default action for all mock methods that return a specific type. The usage of `ON_CALL()` is similar to `EXPECT_CALL()`, so we’ll skip it and just explain how to do the latter (tweaking the default action for a specific return type). You do this via the `DefaultValue<>::SetFactory()` and `DefaultValue<>::Clear()` API: If you are not happy with the default action, you can tweak it as usual; see
[Setting Default Actions](#OnCall).
```
// Sets the default action for return type std::unique_ptr<Buzz> to
// creating a new Buzz every time.
DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
// When this fires, the default action of MakeBuzz() will run, which
// will return a new Buzz object.
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
auto buzz1 = mock_buzzer_.MakeBuzz("hello"); If you just need to return a pre-defined move-only value, you can use the
auto buzz2 = mock_buzzer_.MakeBuzz("hello"); `Return(ByMove(...))` action:
EXPECT_NE(nullptr, buzz1);
EXPECT_NE(nullptr, buzz2);
EXPECT_NE(buzz1, buzz2);
// Resets the default action for return type std::unique_ptr<Buzz>, ```cpp
// to avoid interfere with other tests.
DefaultValue<std::unique_ptr<Buzz>>::Clear();
```
What if you want the method to do something other than the default action? If you just need to return a pre-defined move-only value, you can use the `Return(ByMove(...))` action:
```
// When this fires, the unique_ptr<> specified by ByMove(...) will // When this fires, the unique_ptr<> specified by ByMove(...) will
// be returned. // be returned.
EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) EXPECT_CALL(mock_buzzer_, MakeBuzz("world"))
...@@ -2343,81 +2318,87 @@ What if you want the method to do something other than the default action? If y ...@@ -2343,81 +2318,87 @@ What if you want the method to do something other than the default action? If y
Note that `ByMove()` is essential here - if you drop it, the code won’t compile. Note that `ByMove()` is essential here - if you drop it, the code won’t compile.
Quiz time! What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write `….WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))` can only be run once. Quiz time! What do you think will happen if a `Return(ByMove(...))` action is
performed more than once (e.g. you write
`.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first
time the action runs, the source value will be consumed (since it’s a move-only
value), so the next time around, there’s no value to move from -- you’ll get a
run-time error that `Return(ByMove(...))` can only be run once.
If you need your mock method to do more than just moving a pre-defined value, remember that you can always use `Invoke()` to call a lambda or a callable object, which can do pretty much anything you want: If you need your mock method to do more than just moving a pre-defined value,
remember that you can always use a lambda or a callable object, which can do
pretty much anything you want:
``` ```cpp
EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) EXPECT_CALL(mock_buzzer_, MakeBuzz("x"))
.WillRepeatedly(Invoke([](const std::string& text) { .WillRepeatedly([](StringPiece text) {
return std::make_unique<Buzz>(AccessLevel::kInternal); return MakeUnique<Buzz>(AccessLevel::kInternal);
})); });
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x"));
``` ```
Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created and returned. You cannot do this with `Return(ByMove(...))`. Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be
created and returned. You cannot do this with `Return(ByMove(...))`.
Now there’s one topic we haven’t covered: how do you set expectations on `ShareBuzz()`, which takes a move-only-typed parameter? The answer is you don’t. Instead, you set expectations on the `DoShareBuzz()` mock method (remember that we defined a `MOCK_METHOD` for `DoShareBuzz()`, not `ShareBuzz()`): That covers returning move-only values; but how do we work with methods
accepting move-only arguments? The answer is that they work normally, although
some actions will not compile when any of method's arguments are move-only. You
can always use `Return`, or a [lambda or functor](#FunctionsAsActions):
``` ```cpp
EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); using ::testing::Unused;
// When one calls ShareBuzz() on the MockBuzzer like this, the call is EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)) .WillOnce(Return(true));
// forwarded to DoShareBuzz(), which is mocked. Therefore this statement EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)),
// will trigger the above EXPECT_CALL. 0);
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal),
::base::Now()); EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)) .WillOnce(
[](std::unique_ptr<Buzz> buzz, Unused) { return buzz != nullptr; });
EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0));
``` ```
Some of you may have spotted one problem with this approach: the `DoShareBuzz()` mock method differs from the real `ShareBuzz()` method in that it cannot take ownership of the buzz parameter - `ShareBuzz()` will always delete buzz after `DoShareBuzz()` returns. What if you need to save the buzz object somewhere for later use when `ShareBuzz()` is called? Indeed, you'd be stuck. Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...)
could in principle support move-only arguments, but the support for this is not
implemented yet. If this is blocking you, please file a bug.
Another problem with the `DoShareBuzz()` we had is that it can surprise people reading or maintaining the test, as one would expect that `DoShareBuzz()` has (logically) the same contract as `ShareBuzz()`. A few actions (e.g. `DoAll`) copy their arguments internally, so they can never
work with non-copyable objects; you'll have to use functors instead.
Fortunately, these problems can be fixed with a bit more code. Let's try to get it right this time: ##### Legacy workarounds for move-only types {#LegacyMoveOnly}
``` Support for move-only function arguments was only introduced to gMock in April
2017. In older code, you may encounter the following workaround for the lack of
this feature (it is no longer necessary - we're including it just for
reference):
```cpp
class MockBuzzer : public Buzzer { class MockBuzzer : public Buzzer {
public: public:
MockBuzzer() {
// Since DoShareBuzz(buzz, time) is supposed to take ownership of
// buzz, define a default behavior for DoShareBuzz(buzz, time) to
// delete buzz.
ON_CALL(*this, DoShareBuzz(_, _))
.WillByDefault(Invoke([](Buzz* buzz, Time timestamp) {
delete buzz;
return true;
}));
}
MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text));
// Takes ownership of buzz.
MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp));
bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) { bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) override {
return DoShareBuzz(buzz.release(), timestamp); return DoShareBuzz(buzz.get(), timestamp);
} }
}; };
``` ```
Now, the mock `DoShareBuzz()` method is free to save the buzz argument for later use if this is what you want: The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call
it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of
setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock
method:
``` ```cpp
std::unique_ptr<Buzz> intercepted_buzz; MockBuzzer mock_buzzer_;
EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)) EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _));
.WillOnce(Invoke([&intercepted_buzz](Buzz* buzz, Time timestamp) {
// Save buzz in intercepted_buzz for analysis later.
intercepted_buzz.reset(buzz);
return false;
}));
mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), // When one calls ShareBuzz() on the MockBuzzer like this, the call is
Now()); // forwarded to DoShareBuzz(), which is mocked. Therefore this statement
EXPECT_NE(nullptr, intercepted_buzz); // will trigger the above EXPECT_CALL.
mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0);
``` ```
Using the tricks covered in this recipe, you are now able to mock methods that take and/or return move-only types. Put your newly-acquired power to good use - when you design a new API, you can now feel comfortable using `unique_ptrs` as appropriate, without fearing that doing so will compromise your tests.
## Making the Compilation Faster ## ## Making the Compilation Faster ##
...@@ -3674,6 +3655,6 @@ This printer knows how to print built-in C++ types, native arrays, STL ...@@ -3674,6 +3655,6 @@ This printer knows how to print built-in C++ types, native arrays, STL
containers, and any type that supports the `<<` operator. For other containers, and any type that supports the `<<` operator. For other
types, it prints the raw bytes in the value and hopes that you the types, it prints the raw bytes in the value and hopes that you the
user can figure it out. user can figure it out.
[Google Test's advanced guide](../../googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values) [Google Test's advanced guide](../../googletest/docs/advanced.md#teaching-google-test-how-to-print-your-values)
explains how to extend the printer to do a better job at explains how to extend the printer to do a better job at
printing your particular type than to dump the bytes. printing your particular type than to dump the bytes.
If you are interested in understanding the internals of Google Mock,
building from source, or contributing ideas or modifications to the
project, then this document is for you.
# Introduction #
First, let's give you some background of the project.
## Licensing ##
All Google Mock source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php).
## The Google Mock Community ##
The Google Mock community exists primarily through the [discussion group](http://groups.google.com/group/googlemock), the
[issue tracker](https://github.com/google/googletest/issues) and, to a lesser extent, the [source control repository](../). You are definitely encouraged to contribute to the
discussion and you can also help us to keep the effectiveness of the
group high by following and promoting the guidelines listed here.
### Please Be Friendly ###
Showing courtesy and respect to others is a vital part of the Google
culture, and we strongly encourage everyone participating in Google
Mock development to join us in accepting nothing less. Of course,
being courteous is not the same as failing to constructively disagree
with each other, but it does mean that we should be respectful of each
other when enumerating the 42 technical reasons that a particular
proposal may not be the best choice. There's never a reason to be
antagonistic or dismissive toward anyone who is sincerely trying to
contribute to a discussion.
Sure, C++ testing is serious business and all that, but it's also
a lot of fun. Let's keep it that way. Let's strive to be one of the
friendliest communities in all of open source.
### Where to Discuss Google Mock ###
As always, discuss Google Mock in the official [Google C++ Mocking Framework discussion group](http://groups.google.com/group/googlemock). You don't have to actually submit
code in order to sign up. Your participation itself is a valuable
contribution.
# Working with the Code #
If you want to get your hands dirty with the code inside Google Mock,
this is the section for you.
## Checking Out the Source from Subversion ##
Checking out the Google Mock source is most useful if you plan to
tweak it yourself. You check out the source for Google Mock using a
[Subversion](http://subversion.tigris.org/) client as you would for any
other project hosted on Google Code. Please see the instruction on
the [source code access page](../) for how to do it.
## Compiling from Source ##
Once you check out the code, you can find instructions on how to
compile it in the [README](../README.md) file.
## Testing ##
A mocking framework is of no good if itself is not thoroughly tested.
Tests should be written for any new code, and changes should be
verified to not break existing tests before they are submitted for
review. To perform the tests, follow the instructions in [README](../README.md) and
verify that there are no failures.
# Contributing Code #
We are excited that Google Mock is now open source, and hope to get
great patches from the community. Before you fire up your favorite IDE
and begin hammering away at that new feature, though, please take the
time to read this section and understand the process. While it seems
rigorous, we want to keep a high standard of quality in the code
base.
## Contributor License Agreements ##
You must sign a Contributor License Agreement (CLA) before we can
accept any code. The CLA protects you and us.
* If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html).
* If you work for a company that wants to allow you to contribute your work to Google Mock, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html).
Follow either of the two links above to access the appropriate CLA and
instructions for how to sign and return it.
## Coding Style ##
To keep the source consistent, readable, diffable and easy to merge,
we use a fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project. All patches will be expected
to conform to the style outlined [here](https://google.github.io/styleguide/cppguide.html).
## Submitting Patches ##
Please do submit code. Here's what you need to do:
1. Normally you should make your change against the SVN trunk instead of a branch or a tag, as the latter two are for release control and should be treated mostly as read-only.
1. Decide which code you want to submit. A submission should be a set of changes that addresses one issue in the [Google Mock issue tracker](https://github.com/google/googletest/issues). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one.
1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches.
1. Ensure that your code adheres to the [Google Mock source code style](#Coding_Style.md).
1. Ensure that there are unit tests for your code.
1. Sign a Contributor License Agreement.
1. Create a patch file using `svn diff`.
1. We use [Rietveld](http://codereview.appspot.com/) to do web-based code reviews. You can read about the tool [here](https://github.com/rietveld-codereview/rietveld/wiki). When you are ready, upload your patch via Rietveld and notify `googlemock@googlegroups.com` to review it. There are several ways to upload the patch. We recommend using the [upload\_gmock.py](../scripts/upload_gmock.py) script, which you can find in the `scripts/` folder in the SVN trunk.
## Google Mock Committers ##
The current members of the Google Mock engineering team are the only
committers at present. In the great tradition of eating one's own
dogfood, we will be requiring each new Google Mock engineering team
member to earn the right to become a committer by following the
procedures in this document, writing consistently great code, and
demonstrating repeatedly that he or she truly gets the zen of Google
Mock.
# Release Process #
We follow the typical release process for Subversion-based projects:
1. A release branch named `release-X.Y` is created.
1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable.
1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch.
1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time).
1. Go back to step 1 to create another release branch and so on.
---
This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project. Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/).
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment