Merge pull request #2742 from kuzkry:c++17-type-printers
PiperOrigin-RevId: 314593695
diff --git a/.travis.yml b/.travis.yml
index 04b51dd..d7b23b9 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -14,30 +14,29 @@
install: ./ci/install-platformio.sh
script: ./ci/build-platformio.sh
- os: linux
- dist: xenial
+ dist: bionic
compiler: gcc
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
- dist: xenial
+ dist: bionic
compiler: clang
install: ./ci/install-linux.sh && ./ci/log-config.sh
script: ./ci/build-linux-bazel.sh
- os: linux
+ dist: bionic
compiler: gcc
- env: BUILD_TYPE=Debug VERBOSE=1 CXX_FLAGS=-std=c++11
+ env: BUILD_TYPE=Debug VERBOSE=1 CXX_FLAGS="-std=c++11 -Wdeprecated"
- os: linux
+ dist: bionic
compiler: clang
- env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 -Wgnu-zero-variadic-macro-arguments
- - 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
+ env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS="-std=c++11 -Wdeprecated" NO_EXCEPTION=ON NO_RTTI=ON COMPILER_IS_GNUCXX=ON
- os: osx
compiler: gcc
- env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
+ env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS="-std=c++11 -Wdeprecated" HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
- os: osx
compiler: clang
- env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
+ env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS="-std=c++11 -Wdeprecated" HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp
# 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.
@@ -51,16 +50,9 @@
# This section installs the necessary dependencies.
addons:
apt:
- # List of whitelisted in travis packages for ubuntu-precise can be found here:
- # https://github.com/travis-ci/apt-package-whitelist/blob/master/ubuntu-precise
- # List of whitelisted in travis apt-sources:
- # https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json
- sources:
- - ubuntu-toolchain-r-test
- - llvm-toolchain-precise-3.9
packages:
- - g++-4.9
- - clang-3.9
+ - g++
+ - clang
update: true
homebrew:
packages:
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d883409..37e7b61 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -10,7 +10,7 @@
project(googletest-distribution)
set(GOOGLETEST_VERSION 1.10.0)
-if (CMAKE_VERSION VERSION_GREATER_EQUAL "3.1")
+if (CMAKE_VERSION VERSION_GREATER "3.0.2")
if(NOT CYGWIN AND NOT MSYS)
set(CMAKE_CXX_EXTENSIONS OFF)
endif()
diff --git a/README.md b/README.md
index e332e9a..1727866 100644
--- a/README.md
+++ b/README.md
@@ -102,9 +102,9 @@
is a VS Code extension allowing to view Google Tests in a tree view, and
run/debug your tests.
-[Catch2 and Google Test Explorer](https://github.com/matepek/vscode-catch2-test-adapter)
-is a VS Code extension allowing to view Google Tests in a tree view, and
-run/debug your tests.
+[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS
+Code extension allowing to view Google Tests in a tree view, and run/debug your
+tests.
[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
that generates stub code for Google Test.
diff --git a/ci/build-linux-bazel.sh b/ci/build-linux-bazel.sh
index ae8fb75..cfb06a9 100755
--- a/ci/build-linux-bazel.sh
+++ b/ci/build-linux-bazel.sh
@@ -32,6 +32,5 @@
set -e
bazel version
-bazel build --curses=no //...:all
bazel test --curses=no //...:all
bazel test --curses=no //...:all --define absl=1
diff --git a/ci/env-linux.sh b/ci/env-linux.sh
index 37800d6..7d2b8a8 100755
--- a/ci/env-linux.sh
+++ b/ci/env-linux.sh
@@ -36,6 +36,6 @@
# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}.
if [ "${TRAVIS_OS_NAME}" = "linux" ]; then
- if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi
- if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.9" CC="clang-3.9"; fi
+ if [ "$CXX" = "g++" ]; then export CXX="g++" CC="gcc"; fi
+ if [ "$CXX" = "clang++" ]; then export CXX="clang++" CC="clang"; fi
fi
diff --git a/ci/install-linux.sh b/ci/install-linux.sh
index 05e2cb2..f98ac7d 100755
--- a/ci/install-linux.sh
+++ b/ci/install-linux.sh
@@ -41,7 +41,7 @@
echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | \
sudo tee /etc/apt/sources.list.d/bazel.list
curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -
- sudo apt-get update && sudo apt-get install -y bazel gcc-4.9 g++-4.9 clang-3.9
+ sudo apt-get update && sudo apt-get install -y bazel gcc g++ clang
elif [ "${CXX}" = "clang++" ]; then
# Use ccache, assuming $HOME/bin is in the path, which is true in the Travis build environment.
ln -sf /usr/bin/ccache $HOME/bin/${CXX};
diff --git a/ci/travis.sh b/ci/travis.sh
index 9ff3bad..a248822 100755
--- a/ci/travis.sh
+++ b/ci/travis.sh
@@ -3,21 +3,6 @@
. ci/get-nprocessors.sh
-# 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
# Tell make to use the processors. No preceding '-' required.
MAKEFLAGS="j${NPROCESSORS}"
export MAKEFLAGS
@@ -34,11 +19,11 @@
cmake -Dgtest_build_samples=ON \
-Dgtest_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_BUILD_TYPE=$BUILD_TYPE \
+ -Dcxx_no_exception="$NO_EXCEPTION" \
+ -Dcxx_no_rtti="$NO_RTTI" \
+ -DCMAKE_COMPILER_IS_GNUCXX="$COMPILER_IS_GNUCXX" \
+ -DCMAKE_CXX_FLAGS="$CXX_FLAGS" \
+ -DCMAKE_BUILD_TYPE="$BUILD_TYPE" \
..
make
CTEST_OUTPUT_ON_FAILURE=1 make test
diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt
index 8ab59d7..079c8c9 100644
--- a/googlemock/CMakeLists.txt
+++ b/googlemock/CMakeLists.txt
@@ -100,8 +100,10 @@
else()
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
target_link_libraries(gmock PUBLIC gtest)
+ set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
target_link_libraries(gmock_main PUBLIC gmock)
+ set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
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
diff --git a/googlemock/README.md b/googlemock/README.md
index 183fdb8..11414f9 100644
--- a/googlemock/README.md
+++ b/googlemock/README.md
@@ -7,26 +7,26 @@
It is inspired by:
-* [jMock](http://www.jmock.org/),
-* [EasyMock](http://www.easymock.org/), and
-* [Hamcrest](http://code.google.com/p/hamcrest/),
+* [jMock](http://www.jmock.org/)
+* [EasyMock](http://www.easymock.org/)
+* [Hamcrest](http://code.google.com/p/hamcrest/)
-and designed with C++'s specifics in mind.
+It is designed with C++'s specifics in mind.
gMock:
-- provides a declarative syntax for defining mocks,
-- can define partial (hybrid) mocks, which are a cross of real and mock
- objects,
-- handles functions of arbitrary types and overloaded functions,
-- comes with a rich set of matchers for validating function arguments,
-- uses an intuitive syntax for controlling the behavior of a mock,
-- does automatic verification of expectations (no record-and-replay needed),
-- allows arbitrary (partial) ordering constraints on function calls to be
- expressed,
-- lets a user extend it by defining new matchers and actions.
-- does not use exceptions, and
-- is easy to learn and use.
+- Provides a declarative syntax for defining mocks.
+- Can define partial (hybrid) mocks, which are a cross of real and mock
+ objects.
+- Handles functions of arbitrary types and overloaded functions.
+- Comes with a rich set of matchers for validating function arguments.
+- Uses an intuitive syntax for controlling the behavior of a mock.
+- Does automatic verification of expectations (no record-and-replay needed).
+- Allows arbitrary (partial) ordering constraints on function calls to be
+ expressed.
+- Lets a user extend it by defining new matchers and actions.
+- Does not use exceptions.
+- Is easy to learn and use.
Details and examples can be found here:
diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in
index 5780fca..23c67b5 100644
--- a/googlemock/cmake/gmock.pc.in
+++ b/googlemock/cmake/gmock.pc.in
@@ -5,6 +5,6 @@
Description: GoogleMock (without main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
-Requires: gtest
+Requires: gtest = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in
index f2dfe69..66ffea7 100644
--- a/googlemock/cmake/gmock_main.pc.in
+++ b/googlemock/cmake/gmock_main.pc.in
@@ -5,6 +5,6 @@
Description: GoogleMock (with main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
-Requires: gmock
+Requires: gmock = @PROJECT_VERSION@
Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
diff --git a/googlemock/docs/cheat_sheet.md b/googlemock/docs/cheat_sheet.md
index 1e0541b..f2fb272 100644
--- a/googlemock/docs/cheat_sheet.md
+++ b/googlemock/docs/cheat_sheet.md
@@ -239,6 +239,11 @@
| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
<!-- mdformat on -->
+**Note:** Although equality matching via `EXPECT_THAT(actual_value,
+expected_value)` is supported, prefer to make the comparison explicit via
+`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,
+expected_value)`.
+
Built-in matchers (where `argument` is the function argument, e.g.
`actual_value` in the example above, or when used in the context of
`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are
diff --git a/googlemock/docs/community_created_documentation.md b/googlemock/docs/community_created_documentation.md
new file mode 100644
index 0000000..dfd87f7
--- /dev/null
+++ b/googlemock/docs/community_created_documentation.md
@@ -0,0 +1,9 @@
+# Community-Created Documentation
+
+go/gunit-community-created-docs
+
+The following is a list, in no particular order, of links to documentation
+created by the Googletest community.
+
+* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md),
+ by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy)
diff --git a/googlemock/docs/cook_book.md b/googlemock/docs/cook_book.md
index 7209ea0..bffbb3c 100644
--- a/googlemock/docs/cook_book.md
+++ b/googlemock/docs/cook_book.md
@@ -410,8 +410,8 @@
methods with expectations, but they don't match). See
[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected).
-There are some caveats though (I dislike them just as much as the next guy, but
-sadly they are side effects of C++'s limitations):
+There are some caveats though (sadly they are side effects of C++'s
+limitations):
1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods
defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class.
@@ -421,7 +421,7 @@
`NiceMock<StrictMock<MockFoo> >`) is **not** supported.
2. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` may not work correctly if the
destructor of `MockFoo` is not virtual. We would like to fix this, but it
- requires cleaning up existing tests. http://b/28934720 tracks the issue.
+ requires cleaning up existing tests.
3. During the constructor or destructor of `MockFoo`, the mock object is *not*
nice or strict. This may cause surprises if the constructor or destructor
calls a mock method on `this` object. (This behavior, however, is consistent
@@ -1712,8 +1712,8 @@
the test should reflect our real intent, instead of being overly constraining.
gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the
-calls. One way to express the DAG is to use the [After](#AfterClause) clause of
-`EXPECT_CALL`.
+calls. One way to express the DAG is to use the
+[After](cheat_sheet.md#AfterClause) clause of `EXPECT_CALL`.
Another way is via the `InSequence()` clause (not the same as the `InSequence`
class), which we borrowed from jMock 2. It's less flexible than `After()`, but
@@ -2686,7 +2686,7 @@
EventQueue event_queue(&mock_event_dispatcher);
const int32 kEventId = 321;
- Notification done;
+ absl::Notification done;
EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId))
.WillOnce(Notify(&done));
diff --git a/googlemock/docs/for_dummies.md b/googlemock/docs/for_dummies.md
index 93cf06f..8f5d17a 100644
--- a/googlemock/docs/for_dummies.md
+++ b/googlemock/docs/for_dummies.md
@@ -257,8 +257,8 @@
...
```
-**Tip 1:** If you run the test from an Emacs buffer, you can hit <Enter> on the
-line number to jump right to the failed expectation.
+**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on
+the line number to jump right to the failed expectation.
**Tip 2:** If your mock objects are never deleted, the final verification won't
happen. Therefore it's a good idea to turn on the heap checker in your tests
@@ -374,7 +374,7 @@
In the above examples, `100` and `50` are also matchers; implicitly, they are
the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
equal (using `operator==`) to the matcher argument. There are many
-[built-in matchers](#MatcherList) for common types (as well as
+[built-in matchers](cheat_sheet.md#MatcherList) for common types (as well as
[custom matchers](cook_book.md#NewMatchers)); for example:
```cpp
diff --git a/googlemock/docs/gmock_faq.md b/googlemock/docs/gmock_faq.md
index 214aabf..7f8c647 100644
--- a/googlemock/docs/gmock_faq.md
+++ b/googlemock/docs/gmock_faq.md
@@ -5,7 +5,7 @@
### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?
In order for a method to be mocked, it must be *virtual*, unless you use the
-[high-perf dependency injection technique](#MockingNonVirtualMethods).
+[high-perf dependency injection technique](cook_book.md#MockingNonVirtualMethods).
### Can I mock a variadic function?
diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h
index b4127e9..ecf47c4 100644
--- a/googlemock/include/gmock/gmock-actions.h
+++ b/googlemock/include/gmock/gmock-actions.h
@@ -138,6 +138,7 @@
#include <functional>
#include <memory>
#include <string>
+#include <tuple>
#include <type_traits>
#include <utility>
@@ -570,13 +571,9 @@
private:
Impl impl_;
-
- GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
};
Impl impl_;
-
- GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
};
// Creates an Action from its implementation and returns it. The
@@ -717,13 +714,9 @@
private:
bool performed_;
const std::shared_ptr<R> wrapper_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const std::shared_ptr<R> value_;
-
- GTEST_DISALLOW_ASSIGN_(ReturnAction);
};
// Implements the ReturnNull() action.
@@ -784,13 +777,9 @@
private:
T& ref_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
T& ref_;
-
- GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
};
// Implements the polymorphic ReturnRefOfCopy(x) action, which can be
@@ -831,13 +820,9 @@
private:
T value_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const T value_;
-
- GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
};
// Implements the polymorphic ReturnRoundRobin(v) action, which can be
@@ -894,8 +879,6 @@
private:
T1* const ptr_;
const T2 value_;
-
- GTEST_DISALLOW_ASSIGN_(AssignAction);
};
#if !GTEST_OS_WINDOWS_MOBILE
@@ -917,8 +900,6 @@
private:
const int errno_;
const T result_;
-
- GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
};
#endif // !GTEST_OS_WINDOWS_MOBILE
@@ -970,7 +951,8 @@
Class* const obj_ptr;
const MethodPtr method_ptr;
- using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
+ using ReturnType =
+ decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
template <typename... Args>
ReturnType operator()(const Args&...) const {
@@ -1023,13 +1005,9 @@
OriginalFunction;
const Action<OriginalFunction> action_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const A action_;
-
- GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
};
template <typename InnerAction, size_t... I>
@@ -1310,6 +1288,31 @@
namespace internal {
+template <typename T, typename... Params>
+struct ReturnNewAction {
+ T* operator()() const {
+ return internal::Apply(
+ [](const Params&... unpacked_params) {
+ return new T(unpacked_params...);
+ },
+ params);
+ }
+ std::tuple<Params...> params;
+};
+
+} // namespace internal
+
+// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
+// instance of type T, constructed on the heap with constructor arguments
+// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
+template <typename T, typename... Params>
+internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
+ Params&&... params) {
+ return {std::forward_as_tuple(std::forward<Params>(params)...)};
+}
+
+namespace internal {
+
// A macro from the ACTION* family (defined later in gmock-generated-actions.h)
// defines an action that can be used in a mock function. Typically,
// these actions only care about a subset of the arguments of the mock
@@ -1332,15 +1335,17 @@
public:
template <typename... Ts>
static Result Perform(Impl* impl, const std::tuple<Ts...>& args) {
- return Apply(impl, args, MakeIndexSequence<sizeof...(Ts)>{},
- MakeIndexSequence<10 - sizeof...(Ts)>{});
+ static constexpr size_t kMaxArgs = sizeof...(Ts) <= 10 ? sizeof...(Ts) : 10;
+ return Apply(impl, args, MakeIndexSequence<kMaxArgs>{},
+ MakeIndexSequence<10 - kMaxArgs>{});
}
private:
template <typename... Ts, std::size_t... tuple_ids, std::size_t... rest_ids>
static Result Apply(Impl* impl, const std::tuple<Ts...>& args,
IndexSequence<tuple_ids...>, IndexSequence<rest_ids...>) {
- return impl->template gmock_PerformImpl<Ts...>(
+ return impl->template gmock_PerformImpl<
+ typename std::tuple_element<tuple_ids, std::tuple<Ts...>>::type...>(
args, std::get<tuple_ids>(args)...,
((void)rest_ids, ExcessiveArg())...);
}
@@ -1466,13 +1471,7 @@
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
GMOCK_ACTION_FIELD_PARAMS_(params) \
- \
- private: \
- GTEST_DISALLOW_ASSIGN_(gmock_Impl); \
}; \
- \
- private: \
- GTEST_DISALLOW_ASSIGN_(full_name); \
}; \
template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
@@ -1511,13 +1510,7 @@
} \
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
- \
- private: \
- GTEST_DISALLOW_ASSIGN_(gmock_Impl); \
}; \
- \
- private: \
- GTEST_DISALLOW_ASSIGN_(name##Action); \
}; \
inline name##Action name() { return name##Action(); } \
template <typename F> \
diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h
index c78debe..7030a98 100644
--- a/googlemock/include/gmock/gmock-generated-actions.h
+++ b/googlemock/include/gmock/gmock-generated-actions.h
@@ -435,16 +435,12 @@
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>\
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;\
GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
};\
template <typename F> operator ::testing::Action<F>() const {\
return ::testing::Action<F>(\
new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
}\
GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
};\
template <GMOCK_INTERNAL_DECL_##template_params\
GMOCK_INTERNAL_DECL_TYPE_##value_params>\
@@ -602,77 +598,6 @@
p8, p9);
}
-// Various overloads for ReturnNew<T>().
-//
-// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
-// instance of type T, constructed on the heap with constructor arguments
-// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_0_VALUE_PARAMS()) {
- return new T();
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_1_VALUE_PARAMS(p0)) {
- return new T(p0);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_2_VALUE_PARAMS(p0, p1)) {
- return new T(p0, p1);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_3_VALUE_PARAMS(p0, p1, p2)) {
- return new T(p0, p1, p2);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_4_VALUE_PARAMS(p0, p1, p2, p3)) {
- return new T(p0, p1, p2, p3);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) {
- return new T(p0, p1, p2, p3, p4);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) {
- return new T(p0, p1, p2, p3, p4, p5);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) {
- return new T(p0, p1, p2, p3, p4, p5, p6);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8);
-}
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) {
- return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9);
-}
-
#ifdef _MSC_VER
# pragma warning(pop)
#endif
diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump
index be9d99f..3430204 100644
--- a/googlemock/include/gmock/gmock-generated-actions.h.pump
+++ b/googlemock/include/gmock/gmock-generated-actions.h.pump
@@ -253,16 +253,12 @@
template <GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>\
return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;\
GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(gmock_Impl);\
};\
template <typename F> operator ::testing::Action<F>() const {\
return ::testing::Action<F>(\
new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\
}\
GMOCK_INTERNAL_DEFN_##value_params\
- private:\
- GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\
};\
template <GMOCK_INTERNAL_DECL_##template_params\
GMOCK_INTERNAL_DECL_TYPE_##value_params>\
@@ -344,24 +340,6 @@
]]
-// Various overloads for ReturnNew<T>().
-//
-// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
-// instance of type T, constructed on the heap with constructor arguments
-// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
-$range i 0..n
-$for i [[
-$range j 0..i-1
-$var ps = [[$for j, [[p$j]]]]
-
-ACTION_TEMPLATE(ReturnNew,
- HAS_1_TEMPLATE_PARAMS(typename, T),
- AND_$i[[]]_VALUE_PARAMS($ps)) {
- return new T($ps);
-}
-
-]]
-
#ifdef _MSC_VER
# pragma warning(pop)
#endif
diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h
index fe88a7c..08fd6d1 100644
--- a/googlemock/include/gmock/gmock-matchers.h
+++ b/googlemock/include/gmock/gmock-matchers.h
@@ -444,8 +444,6 @@
private:
const Matcher<U> source_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
};
@@ -861,13 +859,9 @@
private:
const Super& object_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
T& object_;
-
- GTEST_DISALLOW_ASSIGN_(RefMatcher);
};
// Polymorphic helper functions for narrow and wide string matchers.
@@ -970,8 +964,6 @@
const StringType string_;
const bool expect_eq_;
const bool case_sensitive_;
-
- GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
};
// Implements the polymorphic HasSubstr(substring) matcher, which
@@ -1026,8 +1018,6 @@
private:
const StringType substring_;
-
- GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
};
// Implements the polymorphic StartsWith(substring) matcher, which
@@ -1083,8 +1073,6 @@
private:
const StringType prefix_;
-
- GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
};
// Implements the polymorphic EndsWith(substring) matcher, which
@@ -1139,8 +1127,6 @@
private:
const StringType suffix_;
-
- GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
};
// Implements a matcher that compares the two fields of a 2-tuple
@@ -1234,8 +1220,6 @@
private:
const Matcher<T> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
};
// Implements the Not(m) matcher, which matches a value that doesn't
@@ -1254,8 +1238,6 @@
private:
InnerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(NotMatcher);
};
// Implements the AllOf(m1, m2) matcher for a particular argument type
@@ -1317,8 +1299,6 @@
private:
const std::vector<Matcher<T> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl);
};
// VariadicMatcher is used for the variadic implementation of
@@ -1333,6 +1313,9 @@
static_assert(sizeof...(Args) > 0, "Must have at least one matcher.");
}
+ VariadicMatcher(const VariadicMatcher&) = default;
+ VariadicMatcher& operator=(const VariadicMatcher&) = delete;
+
// This template type conversion operator allows an
// VariadicMatcher<Matcher1, Matcher2...> object to match any type that
// all of the provided matchers (Matcher1, Matcher2, ...) can match.
@@ -1357,8 +1340,6 @@
std::integral_constant<size_t, sizeof...(Args)>) const {}
std::tuple<Args...> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
};
template <typename... Args>
@@ -1423,8 +1404,6 @@
private:
const std::vector<Matcher<T> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(AnyOfMatcherImpl);
};
// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
@@ -1452,8 +1431,6 @@
private:
const ::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(SomeOfArrayMatcher);
};
template <typename T>
@@ -1497,8 +1474,6 @@
private:
Predicate predicate_;
-
- GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
};
// Used for implementing Matches(matcher), which turns a matcher into
@@ -1535,8 +1510,6 @@
private:
M matcher_;
-
- GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
};
// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
@@ -1587,8 +1560,6 @@
private:
const M matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
};
// A helper function for converting a matcher to a predicate-formatter
@@ -1740,8 +1711,6 @@
const bool nan_eq_nan_;
// max_abs_error will be used for value comparison when >= 0.
const FloatType max_abs_error_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
// The following 3 type conversion operators allow FloatEq(expected) and
@@ -1770,8 +1739,6 @@
const bool nan_eq_nan_;
// max_abs_error will be used for value comparison when >= 0.
const FloatType max_abs_error_;
-
- GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
};
// A 2-tuple ("binary") wrapper around FloatingEqMatcher:
@@ -1901,13 +1868,9 @@
private:
const Matcher<const Pointee&> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const InnerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
};
#if GTEST_HAS_RTTI
@@ -1944,8 +1907,6 @@
static void GetCastTypeDescription(::std::ostream* os) {
*os << "when dynamic_cast to " << GetToName() << ", ";
}
-
- GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
};
// Primary template.
@@ -2043,8 +2004,6 @@
// Contains either "whose given field " if the name of the field is unknown
// or "whose field `name_of_field` " if the name is known.
const std::string whose_field_;
-
- GTEST_DISALLOW_ASSIGN_(FieldMatcher);
};
// Implements the Property() matcher for matching a property
@@ -2113,8 +2072,6 @@
// Contains either "whose given property " if the name of the property is
// unknown or "whose property `name_of_property` " if the name is known.
const std::string whose_property_;
-
- GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
};
// Type traits specifying various features of different functors for ResultOf.
@@ -2204,14 +2161,10 @@
// how many times the callable will be invoked.
mutable CallableStorageType callable_;
const Matcher<ResultType> matcher_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
}; // class Impl
const CallableStorageType callable_;
const InnerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
};
// Implements a matcher that checks the size of an STL-style container.
@@ -2256,12 +2209,10 @@
private:
const Matcher<SizeType> size_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const SizeMatcher size_matcher_;
- GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
};
// Implements a matcher that checks the begin()..end() distance of an STL-style
@@ -2313,12 +2264,10 @@
private:
const Matcher<DistanceType> distance_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const DistanceMatcher distance_matcher_;
- GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
};
// Implements an equality matcher for any STL-style container whose elements
@@ -2411,8 +2360,6 @@
private:
const StlContainer expected_;
-
- GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
};
// A comparator functor that uses the < operator to compare two values.
@@ -2494,8 +2441,6 @@
private:
const Comparator comparator_;
const ContainerMatcher matcher_;
-
- GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
};
// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
@@ -2611,15 +2556,11 @@
private:
const Matcher<InnerMatcherArg> mono_tuple_matcher_;
const RhsStlContainer rhs_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const TupleMatcher tuple_matcher_;
const RhsStlContainer rhs_;
-
- GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
};
// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
@@ -2662,8 +2603,6 @@
protected:
const Matcher<const Element&> inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
};
// Implements Contains(element_matcher) for the given argument type Container.
@@ -2690,9 +2629,6 @@
MatchResultListener* listener) const override {
return this->MatchAndExplainImpl(false, container, listener);
}
-
- private:
- GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
};
// Implements Each(element_matcher) for the given argument type Container.
@@ -2719,9 +2655,6 @@
MatchResultListener* listener) const override {
return this->MatchAndExplainImpl(true, container, listener);
}
-
- private:
- GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
};
// Implements polymorphic Contains(element_matcher).
@@ -2738,8 +2671,6 @@
private:
const M inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
};
// Implements polymorphic Each(element_matcher).
@@ -2756,8 +2687,6 @@
private:
const M inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(EachMatcher);
};
struct Rank1 {};
@@ -2828,8 +2757,6 @@
private:
const Matcher<const KeyType&> inner_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
};
// Implements polymorphic Key(matcher_for_key).
@@ -2846,8 +2773,6 @@
private:
const M matcher_for_key_;
-
- GTEST_DISALLOW_ASSIGN_(KeyMatcher);
};
// Implements Pair(first_matcher, second_matcher) for the given argument pair
@@ -2933,8 +2858,6 @@
const Matcher<const FirstType&> first_matcher_;
const Matcher<const SecondType&> second_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
};
// Implements polymorphic Pair(first_matcher, second_matcher).
@@ -2953,8 +2876,6 @@
private:
const FirstMatcher first_matcher_;
const SecondMatcher second_matcher_;
-
- GTEST_DISALLOW_ASSIGN_(PairMatcher);
};
// Implements ElementsAre() and ElementsAreArray().
@@ -3100,8 +3021,6 @@
size_t count() const { return matchers_.size(); }
::std::vector<Matcher<const Element&> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
};
// Connectivity matrix of (elements X matchers), in element-major order.
@@ -3204,8 +3123,6 @@
private:
UnorderedMatcherRequire::Flags match_flags_;
MatcherDescriberVec matcher_describers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
};
// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and
@@ -3301,8 +3218,6 @@
}
::std::vector<Matcher<const Element&> > matchers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
};
// Functor for use in TransformTuple.
@@ -3340,7 +3255,6 @@
private:
const MatcherTuple matchers_;
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
};
// Implements ElementsAre.
@@ -3370,7 +3284,6 @@
private:
const MatcherTuple matchers_;
- GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
};
// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().
@@ -3392,8 +3305,6 @@
private:
UnorderedMatcherRequire::Flags match_flags_;
::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
};
// Implements ElementsAreArray().
@@ -3415,8 +3326,6 @@
private:
const ::std::vector<T> matchers_;
-
- GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
};
// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
@@ -3478,8 +3387,6 @@
private:
const Matcher<const ArgTuple&> mono_tuple2_matcher_;
const Second second_value_;
-
- GTEST_DISALLOW_ASSIGN_(Impl);
};
const Tuple2Matcher tuple2_matcher_;
@@ -3552,12 +3459,10 @@
private:
const Matcher<ValueType> value_matcher_;
- GTEST_DISALLOW_ASSIGN_(Impl);
};
private:
const ValueMatcher value_matcher_;
- GTEST_DISALLOW_ASSIGN_(OptionalMatcher);
};
namespace variant_matcher {
@@ -4784,7 +4689,7 @@
// and is printable using 'PrintToString'. It is compatible with
// std::optional/std::experimental::optional.
// Note that to compare an optional type variable against nullopt you should
-// use Eq(nullopt) and not Optional(Eq(nullopt)). The latter implies that the
+// use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the
// optional value contains an optional itself.
template <typename ValueMatcher>
inline internal::OptionalMatcher<ValueMatcher> Optional(
diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h
index 718c948..ac21550 100644
--- a/googlemock/include/gmock/gmock-spec-builders.h
+++ b/googlemock/include/gmock/gmock-spec-builders.h
@@ -499,7 +499,10 @@
public:
// Constructs a null object that doesn't reference any expectation.
Expectation();
-
+ Expectation(Expectation&&) = default;
+ Expectation(const Expectation&) = default;
+ Expectation& operator=(Expectation&&) = default;
+ Expectation& operator=(const Expectation&) = default;
~Expectation();
// This single-argument ctor must not be explicit, in order to support the
@@ -879,8 +882,6 @@
Clause last_clause_;
mutable bool action_count_checked_; // Under mutex_.
mutable Mutex mutex_; // Protects action_count_checked_.
-
- GTEST_DISALLOW_ASSIGN_(ExpectationBase);
}; // class ExpectationBase
// Impements an expectation for the given function type.
@@ -1295,8 +1296,6 @@
internal::FunctionMocker<F>* const function_mocker_;
// The argument matchers specified in the spec.
ArgumentMatcherTuple matchers_;
-
- GTEST_DISALLOW_ASSIGN_(MockSpec);
}; // class MockSpec
// Wrapper type for generically holding an ordinary value or lvalue reference.
@@ -1786,10 +1785,79 @@
} // namespace internal
-// A MockFunction<F> class has one mock method whose type is F. It is
-// useful when you just want your test code to emit some messages and
-// have Google Mock verify the right messages are sent (and perhaps at
-// the right times). For example, if you are exercising code:
+namespace internal {
+
+template <typename F>
+class MockFunction;
+
+template <typename R, typename... Args>
+class MockFunction<R(Args...)> {
+ public:
+ MockFunction(const MockFunction&) = delete;
+ MockFunction& operator=(const MockFunction&) = delete;
+
+ std::function<R(Args...)> AsStdFunction() {
+ return [this](Args... args) -> R {
+ return this->Call(std::forward<Args>(args)...);
+ };
+ }
+
+ // Implementation detail: the expansion of the MOCK_METHOD macro.
+ R Call(Args... args) {
+ mock_.SetOwnerAndName(this, "Call");
+ return mock_.Invoke(std::forward<Args>(args)...);
+ }
+
+ MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
+ mock_.RegisterOwner(this);
+ return mock_.With(std::move(m)...);
+ }
+
+ MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
+ return this->gmock_Call(::testing::A<Args>()...);
+ }
+
+ protected:
+ MockFunction() = default;
+ ~MockFunction() = default;
+
+ private:
+ FunctionMocker<R(Args...)> mock_;
+};
+
+/*
+The SignatureOf<F> struct is a meta-function returning function signature
+corresponding to the provided F argument.
+
+It makes use of MockFunction easier by allowing it to accept more F arguments
+than just function signatures.
+
+Specializations provided here cover only a signature type itself and
+std::function. However, if need be it can be easily extended to cover also other
+types (like for example boost::function).
+*/
+
+template <typename F>
+struct SignatureOf;
+
+template <typename R, typename... Args>
+struct SignatureOf<R(Args...)> {
+ using type = R(Args...);
+};
+
+template <typename F>
+struct SignatureOf<std::function<F>> : SignatureOf<F> {};
+
+template <typename F>
+using SignatureOfT = typename SignatureOf<F>::type;
+
+} // namespace internal
+
+// A MockFunction<F> type has one mock method whose type is
+// internal::SignatureOfT<F>. It is useful when you just want your
+// test code to emit some messages and have Google Mock verify the
+// right messages are sent (and perhaps at the right times). For
+// example, if you are exercising code:
//
// Foo(1);
// Foo(2);
@@ -1823,49 +1891,34 @@
// 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:
+// std::function<internal::SignatureOfT<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());
// }
+//
+// The internal::SignatureOfT<F> indirection allows to use other types
+// than just function signature type. This is typically useful when
+// providing a mock for a predefined std::function type. Example:
+//
+// using FilterPredicate = std::function<bool(string)>;
+// void MyFilterAlgorithm(FilterPredicate predicate);
+//
+// TEST(FooTest, FilterPredicateAlwaysAccepts) {
+// MockFunction<FilterPredicate> predicateMock;
+// EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
+// MyFilterAlgorithm(predicateMock.AsStdFunction());
+// }
template <typename F>
-class MockFunction;
+class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
+ using Base = internal::MockFunction<internal::SignatureOfT<F>>;
-template <typename R, typename... Args>
-class MockFunction<R(Args...)> {
public:
- MockFunction() {}
- MockFunction(const MockFunction&) = delete;
- MockFunction& operator=(const MockFunction&) = delete;
-
- std::function<R(Args...)> AsStdFunction() {
- return [this](Args... args) -> R {
- return this->Call(std::forward<Args>(args)...);
- };
- }
-
- // Implementation detail: the expansion of the MOCK_METHOD macro.
- R Call(Args... args) {
- mock_.SetOwnerAndName(this, "Call");
- return mock_.Invoke(std::forward<Args>(args)...);
- }
-
- internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
- mock_.RegisterOwner(this);
- return mock_.With(std::move(m)...);
- }
-
- internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
- R (*)(Args...)) {
- return this->gmock_Call(::testing::A<Args>()...);
- }
-
- private:
- internal::FunctionMocker<R(Args...)> mock_;
+ using Base::Base;
};
// The style guide prohibits "using" statements in a namespace scope
diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h
index 66cf857..5580dcb 100644
--- a/googlemock/include/gmock/internal/gmock-internal-utils.h
+++ b/googlemock/include/gmock/internal/gmock-internal-utils.h
@@ -422,11 +422,13 @@
// 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),
- MakeIndexSequence<std::tuple_size<Tuple>::value>())) {
+auto Apply(F&& f, Tuple&& args) -> decltype(
+ ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
+ MakeIndexSequence<std::tuple_size<
+ typename std::remove_reference<Tuple>::type>::value>())) {
return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
- MakeIndexSequence<std::tuple_size<Tuple>::value>());
+ MakeIndexSequence<std::tuple_size<
+ typename std::remove_reference<Tuple>::type>::value>());
}
// Template struct Function<F>, where F must be a function type, contains
diff --git a/googlemock/include/gmock/internal/gmock-pp.h b/googlemock/include/gmock/internal/gmock-pp.h
index d13e75f..23615c5 100644
--- a/googlemock/include/gmock/internal/gmock-pp.h
+++ b/googlemock/include/gmock/internal/gmock-pp.h
@@ -28,16 +28,16 @@
// Requires: the number of arguments after expansion is at most 15.
#define GMOCK_PP_NARG(...) \
GMOCK_PP_INTERNAL_16TH( \
- (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
+ (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
// Returns 1 if the expansion of arguments has an unprotected comma. Otherwise
// returns 0. Requires no more than 15 unprotected commas.
#define GMOCK_PP_HAS_COMMA(...) \
GMOCK_PP_INTERNAL_16TH( \
- (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0))
+ (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))
// Returns the first argument.
-#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__))
+#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))
// Returns the tail. A variadic list of all arguments minus the first. Requires
// at least one argument.
diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc
index 4f73e0a..dded437 100644
--- a/googlemock/src/gmock-matchers.cc
+++ b/googlemock/src/gmock-matchers.cc
@@ -218,8 +218,6 @@
// right_[left_[i]] = i.
::std::vector<size_t> left_;
::std::vector<size_t> right_;
-
- GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState);
};
const size_t MaxBipartiteMatchState::kUnused;
diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel
index da95ed5..4aa9a75 100644
--- a/googlemock/test/BUILD.bazel
+++ b/googlemock/test/BUILD.bazel
@@ -28,8 +28,6 @@
# (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
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc
index d1229ac..1838728 100644
--- a/googlemock/test/gmock-actions_test.cc
+++ b/googlemock/test/gmock-actions_test.cc
@@ -32,11 +32,13 @@
//
// This file tests the built-in actions.
-// Silence C4800 (C4800: 'int *const ': forcing value
-// to bool 'true' or 'false') for MSVC 15
+// Silence C4100 (unreferenced formal parameter) for MSVC
#ifdef _MSC_VER
-#if _MSC_VER == 1900
# 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 15
# pragma warning(disable:4800)
#endif
#endif
@@ -54,35 +56,34 @@
namespace {
-// 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::DoAll;
-using testing::DoDefault;
-using testing::IgnoreResult;
-using testing::Invoke;
-using testing::InvokeWithoutArgs;
-using testing::MakePolymorphicAction;
-using testing::Ne;
-using testing::PolymorphicAction;
-using testing::Return;
-using testing::ReturnNull;
-using testing::ReturnRef;
-using testing::ReturnRefOfCopy;
-using testing::ReturnRoundRobin;
-using testing::SetArgPointee;
-using testing::SetArgumentPointee;
-using testing::Unused;
-using testing::WithArgs;
-using testing::internal::BuiltInDefaultValue;
+using ::testing::_;
+using ::testing::Action;
+using ::testing::ActionInterface;
+using ::testing::Assign;
+using ::testing::ByMove;
+using ::testing::ByRef;
+using ::testing::DefaultValue;
+using ::testing::DoAll;
+using ::testing::DoDefault;
+using ::testing::IgnoreResult;
+using ::testing::Invoke;
+using ::testing::InvokeWithoutArgs;
+using ::testing::MakePolymorphicAction;
+using ::testing::PolymorphicAction;
+using ::testing::Return;
+using ::testing::ReturnNew;
+using ::testing::ReturnNull;
+using ::testing::ReturnRef;
+using ::testing::ReturnRefOfCopy;
+using ::testing::ReturnRoundRobin;
+using ::testing::SetArgPointee;
+using ::testing::SetArgumentPointee;
+using ::testing::Unused;
+using ::testing::WithArgs;
+using ::testing::internal::BuiltInDefaultValue;
#if !GTEST_OS_WINDOWS_MOBILE
-using testing::SetErrnoAndReturn;
+using ::testing::SetErrnoAndReturn;
#endif
// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
@@ -575,8 +576,6 @@
private:
bool* const converted_;
-
- GTEST_DISALLOW_ASSIGN_(FromType);
};
class ToType {
@@ -1292,6 +1291,52 @@
EXPECT_EQ(expected.str(), actual.str());
}
+struct UnaryConstructorClass {
+ explicit UnaryConstructorClass(int v) : value(v) {}
+ int value;
+};
+
+// Tests using ReturnNew() with a unary constructor.
+TEST(ReturnNewTest, Unary) {
+ Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
+ UnaryConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
+ Action<UnaryConstructorClass*(bool, int)> a =
+ ReturnNew<UnaryConstructorClass>(4000);
+ UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
+ Action<const UnaryConstructorClass*()> a =
+ ReturnNew<UnaryConstructorClass>(4000);
+ const UnaryConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(4000, c->value);
+ delete c;
+}
+
+class TenArgConstructorClass {
+ public:
+ TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
+ int a8, int a9, int a10)
+ : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
+ int value_;
+};
+
+// Tests using ReturnNew() with a 10-argument constructor.
+TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
+ Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
+ 1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
+ 0);
+ TenArgConstructorClass* c = a.Perform(std::make_tuple());
+ EXPECT_EQ(1234567890, c->value_);
+ delete c;
+}
std::unique_ptr<int> UniquePtrSource() {
return std::unique_ptr<int>(new int(19));
@@ -1507,6 +1552,26 @@
EXPECT_EQ(x, 3);
}
+ACTION(ReturnArity) {
+ return std::tuple_size<args_type>::value;
+}
+
+TEST(ActionMacro, LargeArity) {
+ EXPECT_EQ(
+ 1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
+ EXPECT_EQ(
+ 10,
+ testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
+ ReturnArity())
+ .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
+ EXPECT_EQ(
+ 20,
+ testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
+ int, int, int, int, int, int, int, int, int)>(
+ ReturnArity())
+ .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
+ 14, 15, 16, 17, 18, 19)));
+}
} // Unnamed namespace
diff --git a/googlemock/test/gmock-function-mocker_test.cc b/googlemock/test/gmock-function-mocker_test.cc
index 019e3cb..94aaafb 100644
--- a/googlemock/test/gmock-function-mocker_test.cc
+++ b/googlemock/test/gmock-function-mocker_test.cc
@@ -40,6 +40,7 @@
# include <objbase.h>
#endif // GTEST_OS_WINDOWS
+#include <functional>
#include <map>
#include <string>
#include <type_traits>
@@ -778,6 +779,56 @@
EXPECT_EQ(-1, call(foo.AsStdFunction(), i));
}
+namespace {
+
+template <typename Expected, typename F>
+static constexpr bool IsMockFunctionTemplateArgumentDeducedTo(
+ const MockFunction<F>&) {
+ return std::is_same<F, Expected>::value;
+}
+
+} // namespace
+
+template <typename F>
+class MockMethodMockFunctionSignatureTest : public Test {};
+
+using MockMethodMockFunctionSignatureTypes =
+ Types<void(), int(), void(int), int(int), int(bool, int),
+ int(bool, char, int, int, int, int, int, char, int, bool)>;
+TYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest,
+ MockMethodMockFunctionSignatureTypes);
+
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+ IsMockFunctionTemplateArgumentDeducedForRawSignature) {
+ using Argument = TypeParam;
+ MockFunction<Argument> foo;
+ EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<Argument>(foo));
+}
+
+TYPED_TEST(MockMethodMockFunctionSignatureTest,
+ IsMockFunctionTemplateArgumentDeducedForStdFunction) {
+ using Argument = std::function<TypeParam>;
+ MockFunction<Argument> foo;
+ EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<Argument>(foo));
+}
+
+TYPED_TEST(
+ MockMethodMockFunctionSignatureTest,
+ IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) {
+ using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);
+ using ForStdFunction =
+ decltype(&MockFunction<std::function<TypeParam>>::Call);
+ EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
+}
+
+TYPED_TEST(
+ MockMethodMockFunctionSignatureTest,
+ IsMockFunctionAsStdFunctionMethodSignatureTheSameForRawSignatureAndStdFunction) {
+ using ForRawSignature = decltype(&MockFunction<TypeParam>::AsStdFunction);
+ using ForStdFunction =
+ decltype(&MockFunction<std::function<TypeParam>>::AsStdFunction);
+ EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));
+}
struct MockMethodSizes0 {
MOCK_METHOD(void, func, ());
diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc
index 4c649a7..ef39dff 100644
--- a/googlemock/test/gmock-generated-actions_test.cc
+++ b/googlemock/test/gmock-generated-actions_test.cc
@@ -53,7 +53,6 @@
using testing::DoAll;
using testing::Invoke;
using testing::Return;
-using testing::ReturnNew;
using testing::SetArgPointee;
using testing::StaticAssertTypeEq;
using testing::Unused;
@@ -844,49 +843,6 @@
EXPECT_EQ(55, a.Perform(empty));
}
-class NullaryConstructorClass {
- public:
- NullaryConstructorClass() : value_(123) {}
- int value_;
-};
-
-// Tests using ReturnNew() with a nullary constructor.
-TEST(ReturnNewTest, NoArgs) {
- Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>();
- NullaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(123, c->value_);
- delete c;
-}
-
-class UnaryConstructorClass {
- public:
- explicit UnaryConstructorClass(int value) : value_(value) {}
- int value_;
-};
-
-// Tests using ReturnNew() with a unary constructor.
-TEST(ReturnNewTest, Unary) {
- Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
- UnaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
- Action<UnaryConstructorClass*(bool, int)> a =
- ReturnNew<UnaryConstructorClass>(4000);
- UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
-
-TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
- Action<const UnaryConstructorClass*()> a =
- ReturnNew<UnaryConstructorClass>(4000);
- const UnaryConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(4000, c->value_);
- delete c;
-}
class TenArgConstructorClass {
public:
@@ -897,17 +853,6 @@
int value_;
};
-// Tests using ReturnNew() with a 10-argument constructor.
-TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
- Action<TenArgConstructorClass*()> a =
- ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000,
- 4000000, 500000, 60000,
- 7000, 800, 90, 0);
- TenArgConstructorClass* c = a.Perform(std::make_tuple());
- EXPECT_EQ(1234567890, c->value_);
- delete c;
-}
-
// Tests that ACTION_TEMPLATE works when there is no value parameter.
ACTION_TEMPLATE(CreateNew,
HAS_1_TEMPLATE_PARAMS(typename, T),
diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc
index 3619959..5db0a7a 100644
--- a/googlemock/test/gmock-matchers_test.cc
+++ b/googlemock/test/gmock-matchers_test.cc
@@ -3746,17 +3746,11 @@
const double y; // A const field.
Uncopyable z; // An uncopyable field.
const char* p; // A pointer field.
-
- private:
- GTEST_DISALLOW_ASSIGN_(AStruct);
};
// A derived struct for testing Field().
struct DerivedStruct : public AStruct {
char ch;
-
- private:
- GTEST_DISALLOW_ASSIGN_(DerivedStruct);
};
// Tests that Field(&Foo::field, ...) works when field is non-const.
@@ -4726,20 +4720,18 @@
Matcher<vector<int> > m1 = SizeIs(2);
Matcher<vector<int> > m2 = SizeIs(Lt(2u));
Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
- Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
+ Matcher<vector<int> > m4 = SizeIs(Gt(1u));
vector<int> container;
EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
EXPECT_EQ("whose size 0 matches", Explain(m2, container));
EXPECT_EQ("whose size 0 matches", Explain(m3, container));
- EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
- Explain(m4, container));
+ EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
container.push_back(0);
container.push_back(0);
EXPECT_EQ("whose size 2 matches", Explain(m1, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
- EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
- Explain(m4, container));
+ EXPECT_EQ("whose size 2 matches", Explain(m4, container));
}
#if GTEST_HAS_TYPED_TEST
diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt
index 4fd7b52..f538c96 100644
--- a/googletest/CMakeLists.txt
+++ b/googletest/CMakeLists.txt
@@ -126,7 +126,9 @@
# are used for other targets, to ensure that gtest can be compiled by a user
# aggressive about warnings.
cxx_library(gtest "${cxx_strict}" src/gtest-all.cc)
+set_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})
cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc)
+set_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
# If the CMake version supports it, attach header directory information
# to the targets for when we are part of a parent build (ie being pulled
# in via add_subdirectory() rather than being a standalone build).
diff --git a/googletest/README.md b/googletest/README.md
index 904048f..8520549 100644
--- a/googletest/README.md
+++ b/googletest/README.md
@@ -189,9 +189,9 @@
When Google Test uses pthread, you may need to add flags to your compiler and/or
linker to select the pthread library, or you'll get link errors. If you use the
-CMake script or the deprecated Autotools script, this is taken care of for you.
-If you use your own build script, you'll need to read your compiler and linker's
-manual to figure out what flags to add.
+CMake script, this is taken care of for you. If you use your own build script,
+you'll need to read your compiler and linker's manual to figure out what flags
+to add.
### As a Shared Library (DLL)
diff --git a/googletest/cmake/gtest_main.pc.in b/googletest/cmake/gtest_main.pc.in
index 1e01bd1..38c88c5 100644
--- a/googletest/cmake/gtest_main.pc.in
+++ b/googletest/cmake/gtest_main.pc.in
@@ -5,6 +5,6 @@
Description: GoogleTest (with main() function)
Version: @PROJECT_VERSION@
URL: https://github.com/google/googletest
-Requires: gtest
+Requires: gtest = @PROJECT_VERSION@
Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md
index 5677643..60c1a2b 100644
--- a/googletest/docs/advanced.md
+++ b/googletest/docs/advanced.md
@@ -401,7 +401,7 @@
your [own matchers](../../googlemock/docs/cook_book.md#NewMatchers) too.
gMock is bundled with googletest, so you don't need to add any build dependency
-in order to take advantage of this. Just include `"testing/base/public/gmock.h"`
+in order to take advantage of this. Just include `"gmock/gmock.h"`
and you're ready to go.
### More String Assertions
@@ -863,7 +863,7 @@
```c++
int main(int argc, char** argv) {
- InitGoogle(argv[0], &argc, &argv, true);
+ ::testing::InitGoogleTest(&argc, argv);
::testing::FLAGS_gtest_death_test_style = "fast";
return RUN_ALL_TESTS();
}
@@ -1006,7 +1006,7 @@
// in Subroutine() to abort the entire test.
// The actual behavior: the function goes on after Subroutine() returns.
- int* p = NULL;
+ int* p = nullptr;
*p = 3; // Segfault!
}
```
@@ -1193,7 +1193,7 @@
// Can be omitted if not needed.
static void TearDownTestSuite() {
delete shared_resource_;
- shared_resource_ = NULL;
+ shared_resource_ = nullptr;
}
// You can define per-test set-up logic as usual.
@@ -1206,7 +1206,7 @@
static T* shared_resource_;
};
-T* FooTest::shared_resource_ = NULL;
+T* FooTest::shared_resource_ = nullptr;
TEST_F(FooTest, Test1) {
... you can refer to shared_resource_ here ...
@@ -1776,7 +1776,7 @@
the exception and assert on it. But googletest doesn't use exceptions, so how do
we test that a piece of code generates an expected failure?
-gunit-spi.h contains some constructs to do this. After #including this header,
+`"gtest/gtest-spi.h"` contains some constructs to do this. After #including this header,
you can use
```c++
@@ -1924,8 +1924,8 @@
```
`current_test_info()` returns a null pointer if no test is running. In
-particular, you cannot find the test suite name in `TestSuiteSetUp()`,
-`TestSuiteTearDown()` (where you know the test suite name implicitly), or
+particular, you cannot find the test suite name in `SetUpTestSuite()`,
+`TearDownTestSuite()` (where you know the test suite name implicitly), or
functions called from them.
## Extending googletest by Handling Test Events
@@ -2116,6 +2116,15 @@
everything in test suite `FooTest` except `FooTest.Bar` and everything in
test suite `BarTest` except `BarTest.Foo`.
+#### Stop test execution upon first failure
+
+By default, a googletest program runs all tests the user has defined. In some
+cases (e.g. iterative test development & execution) it may be desirable stop
+test execution upon first failure (trading improved latency for completeness).
+If `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,
+the test runner will stop execution as soon as the first test failure is
+found.
+
#### Temporarily Disabling Tests
If you have a broken test that you cannot fix right away, you can add the
@@ -2252,6 +2261,12 @@
will use colors if and only if the output goes to a terminal and (on non-Windows
platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.
+#### Suppressing test passes
+
+By default, googletest prints 1 line of output for each test, indicating if it
+passed or failed. To show only test failures, run the test program with
+`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.
+
#### Suppressing the Elapsed Time
By default, googletest prints the time it takes to run each test. To disable
@@ -2273,8 +2288,7 @@
googletest can emit a detailed XML report to a file in addition to its normal
textual output. The report contains the duration of each test, and thus can help
-you identify slow tests. The report is also used by the http://unittest
-dashboard to show per-test-method error messages.
+you identify slow tests.
To generate the XML report, set the `GTEST_OUTPUT` environment variable or the
`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will
@@ -2553,6 +2567,18 @@
### Controlling How Failures Are Reported
+#### Detecting Test Premature Exit
+
+Google Test implements the _premature-exit-file_ protocol for test runners
+to catch any kind of unexpected exits of test programs. Upon start,
+Google Test creates the file which will be automatically deleted after
+all work has been finished. Then, the test runner can check if this file
+exists. In case the file remains undeleted, the inspected test has exited
+prematurely.
+
+This feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment
+variable has been set.
+
#### Turning Assertion Failures into Break-Points
When running test programs under a debugger, it's very convenient if the
diff --git a/googletest/docs/pkgconfig.md b/googletest/docs/pkgconfig.md
index 117166c..b9bef3f 100644
--- a/googletest/docs/pkgconfig.md
+++ b/googletest/docs/pkgconfig.md
@@ -45,77 +45,6 @@
goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens
to discard `-L` flags and `-pthread`.
-### Autotools
-
-Finding GoogleTest in Autoconf and using it from Automake is also fairly easy:
-
-In your `configure.ac`:
-
-```
-AC_PREREQ([2.69])
-AC_INIT([my_gtest_pkgconfig], [0.0.1])
-AC_CONFIG_SRCDIR([samples/sample3_unittest.cc])
-AC_PROG_CXX
-
-PKG_CHECK_MODULES([GTEST], [gtest_main])
-
-AM_INIT_AUTOMAKE([foreign subdir-objects])
-AC_CONFIG_FILES([Makefile])
-AC_OUTPUT
-```
-
-and in your `Makefile.am`:
-
-```
-check_PROGRAMS = testapp
-TESTS = $(check_PROGRAMS)
-
-testapp_SOURCES = samples/sample3_unittest.cc
-testapp_CXXFLAGS = $(GTEST_CFLAGS)
-testapp_LDADD = $(GTEST_LIBS)
-```
-
-### Meson
-
-Meson natively uses pkgconfig to query dependencies:
-
-```
-project('my_gtest_pkgconfig', 'cpp', version : '0.0.1')
-
-gtest_dep = dependency('gtest_main')
-
-testapp = executable(
- 'testapp',
- files(['samples/sample3_unittest.cc']),
- dependencies : gtest_dep,
- install : false)
-
-test('first_and_only_test', testapp)
-```
-
-### Plain Makefiles
-
-Since `pkg-config` is a small Unix command-line utility, it can be used in
-handwritten `Makefile`s too:
-
-```makefile
-GTEST_CFLAGS = `pkg-config --cflags gtest_main`
-GTEST_LIBS = `pkg-config --libs gtest_main`
-
-.PHONY: tests all
-
-tests: all
- ./testapp
-
-all: testapp
-
-testapp: testapp.o
- $(CXX) $(CXXFLAGS) $(LDFLAGS) $< -o $@ $(GTEST_LIBS)
-
-testapp.o: samples/sample3_unittest.cc
- $(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ $(GTEST_CFLAGS)
-```
-
### Help! pkg-config can't find GoogleTest!
Let's say you have a `CMakeLists.txt` along the lines of the one in this
diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md
index f581d77..2f459fd 100644
--- a/googletest/docs/primer.md
+++ b/googletest/docs/primer.md
@@ -169,7 +169,7 @@
`<<` is supported, it will be called to print the arguments when the assertion
fails; otherwise googletest will attempt to print them in the best way it can.
For more details and how to customize the printing of the arguments, see the
-[documentation](../../googlemock/docs/cook_book.md#teaching-gmock-how-to-print-your-values).
+[documentation](./advanced.md#teaching-googletest-how-to-print-your-values).
These assertions can work with a user-defined type, but only if you define the
corresponding comparison operator (e.g., `==` or `<`). Since this is discouraged
diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h
index dc878ff..2bd41cf 100644
--- a/googletest/include/gtest/gtest-death-test.h
+++ b/googletest/include/gtest/gtest-death-test.h
@@ -190,11 +190,10 @@
class GTEST_API_ ExitedWithCode {
public:
explicit ExitedWithCode(int exit_code);
+ ExitedWithCode(const ExitedWithCode&) = default;
+ void operator=(const ExitedWithCode& other) = delete;
bool operator()(int exit_status) const;
private:
- // No implementation - assignment is unsupported.
- void operator=(const ExitedWithCode& other);
-
const int exit_code_;
};
diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h
index 718e6f1..5123d69 100644
--- a/googletest/include/gtest/gtest-printers.h
+++ b/googletest/include/gtest/gtest-printers.h
@@ -117,106 +117,91 @@
namespace testing {
-// Definitions in the 'internal' and 'internal2' name spaces are
-// subject to change without notice. DO NOT USE THEM IN USER CODE!
-namespace internal2 {
-
-// Prints the given number of bytes in the given object to the given
-// ostream.
-GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
- size_t count,
- ::std::ostream* os);
-
-// For selecting which printer to use when a given type has neither <<
-// nor PrintTo().
-enum TypeKind {
- kProtobuf, // a protobuf type
- kConvertibleToInteger, // a type implicitly convertible to BiggestInt
- // (e.g. a named or unnamed enum type)
-#if GTEST_INTERNAL_HAS_STRING_VIEW
- kConvertibleToStringView, // a type implicitly convertible to
- // absl::string_view or std::string_view
-#endif
- kOtherType // anything else
-};
-
-// TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
-// by the universal printer to print a value of type T when neither
-// operator<< nor PrintTo() is defined for T, where kTypeKind is the
-// "kind" of T as defined by enum TypeKind.
-template <typename T, TypeKind kTypeKind>
-class TypeWithoutFormatter {
- public:
- // This default version is called when kTypeKind is kOtherType.
- static void PrintValue(const T& value, ::std::ostream* os) {
- PrintBytesInObjectTo(
- static_cast<const unsigned char*>(
- reinterpret_cast<const void*>(std::addressof(value))),
- sizeof(value), os);
- }
-};
-
-// We print a protobuf using its ShortDebugString() when the string
-// doesn't exceed this many characters; otherwise we print it using
-// DebugString() for better readability.
-const size_t kProtobufOneLinerMaxLength = 50;
+// Definitions in the internal* namespaces are subject to change without notice.
+// DO NOT USE THEM IN USER CODE!
+namespace internal {
template <typename T>
-class TypeWithoutFormatter<T, kProtobuf> {
- public:
- static void PrintValue(const T& value, ::std::ostream* os) {
- std::string pretty_str = value.ShortDebugString();
- if (pretty_str.length() > kProtobufOneLinerMaxLength) {
- pretty_str = "\n" + value.DebugString();
+void UniversalPrint(const T& value, ::std::ostream* os);
+
+// Used to print an STL-style container when the user doesn't define
+// a PrintTo() for it.
+struct ContainerPrinter {
+ template <typename T,
+ typename = typename std::enable_if<
+ (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
+ !IsRecursiveContainer<T>::value>::type>
+ static void PrintValue(const T& container, std::ostream* os) {
+ const size_t kMaxCount = 32; // The maximum number of elements to print.
+ *os << '{';
+ size_t count = 0;
+ for (auto&& elem : container) {
+ if (count > 0) {
+ *os << ',';
+ if (count == kMaxCount) { // Enough has been printed.
+ *os << " ...";
+ break;
+ }
+ }
+ *os << ' ';
+ // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
+ // handle `elem` being a native array.
+ internal::UniversalPrint(elem, os);
+ ++count;
}
- *os << ("<" + pretty_str + ">");
+
+ if (count > 0) {
+ *os << ' ';
+ }
+ *os << '}';
}
};
-template <typename T>
-class TypeWithoutFormatter<T, kConvertibleToInteger> {
- public:
- // Since T has no << operator or PrintTo() but can be implicitly
- // converted to BiggestInt, we print it as a BiggestInt.
- //
- // Most likely T is an enum type (either named or unnamed), in which
- // case printing it as an integer is the desired behavior. In case
- // T is not an enum, printing it as an integer is the best we can do
- // given that it has no user-defined printer.
- static void PrintValue(const T& value, ::std::ostream* os) {
- const internal::BiggestInt kBigInt = value;
- *os << kBigInt;
+// Used to print a pointer that is neither a char pointer nor a member
+// pointer, when the user doesn't define PrintTo() for it. (A member
+// variable pointer or member function pointer doesn't really point to
+// a location in the address space. Their representation is
+// implementation-defined. Therefore they will be printed as raw
+// bytes.)
+struct FunctionPointerPrinter {
+ template <typename T, typename = typename std::enable_if<
+ std::is_function<T>::value>::type>
+ static void PrintValue(T* p, ::std::ostream* os) {
+ if (p == nullptr) {
+ *os << "NULL";
+ } else {
+ // T is a function type, so '*os << p' doesn't do what we want
+ // (it just prints p as bool). We want to print p as a const
+ // void*.
+ *os << reinterpret_cast<const void*>(p);
+ }
}
};
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-template <typename T>
-class TypeWithoutFormatter<T, kConvertibleToStringView> {
- public:
- // Since T has neither operator<< nor PrintTo() but can be implicitly
- // converted to absl::string_view, we print it as a absl::string_view
- // (or std::string_view).
- //
- // Note: the implementation is further below, as it depends on
- // internal::PrintTo symbol which is defined later in the file.
- static void PrintValue(const T& value, ::std::ostream* os);
+struct PointerPrinter {
+ template <typename T>
+ static void PrintValue(T* p, ::std::ostream* os) {
+ if (p == nullptr) {
+ *os << "NULL";
+ } else {
+ // T is not a function type. We just call << to print p,
+ // relying on ADL to pick up user-defined << for their pointer
+ // types, if any.
+ *os << p;
+ }
+ }
};
-#endif
-// Prints the given value to the given ostream. If the value is a
-// protocol message, its debug string is printed; if it's an enum or
-// of a type implicitly convertible to BiggestInt, it's printed as an
-// integer; otherwise the bytes in the value are printed. This is
-// what UniversalPrinter<T>::Print() does when it knows nothing about
-// type T and T has neither << operator nor PrintTo().
+namespace internal_stream {
+
+struct Sentinel;
+template <typename Char, typename CharTraits, typename T>
+Sentinel* operator<<(::std::basic_ostream<Char, CharTraits>& os, const T& x);
+
+// Check if the user has a user-defined operator<< for their type.
//
-// A user can override this behavior for a class type Foo by defining
-// a << operator in the namespace where Foo is defined.
-//
-// We put this operator in namespace 'internal2' instead of 'internal'
-// to simplify the implementation, as much code in 'internal' needs to
-// use << in STL, which would conflict with our own << were it defined
-// in 'internal'.
+// We put this in its own namespace to inject a custom operator<< that allows us
+// to probe the type's operator.
//
// Note that this operator<< takes a generic std::basic_ostream<Char,
// CharTraits> type instead of the more restricted std::ostream. If
@@ -227,67 +212,105 @@
// operator<<(std::ostream&, const T&) or
// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
// specific.
-template <typename Char, typename CharTraits, typename T>
-::std::basic_ostream<Char, CharTraits>& operator<<(
- ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
- TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
- ? kProtobuf
- : std::is_convertible<
- const T&, internal::BiggestInt>::value
- ? kConvertibleToInteger
- :
-#if GTEST_INTERNAL_HAS_STRING_VIEW
- std::is_convertible<
- const T&, internal::StringView>::value
- ? kConvertibleToStringView
- :
-#endif
- kOtherType)>::PrintValue(x, &os);
- return os;
-}
-
-} // namespace internal2
-} // namespace testing
-
-// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
-// magic needed for implementing UniversalPrinter won't work.
-namespace testing_internal {
-
-// Used to print a value that is not an STL-style container when the
-// user doesn't define PrintTo() for it.
template <typename T>
-void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
- // With the following statement, during unqualified name lookup,
- // testing::internal2::operator<< appears as if it was declared in
- // the nearest enclosing namespace that contains both
- // ::testing_internal and ::testing::internal2, i.e. the global
- // namespace. For more details, refer to the C++ Standard section
- // 7.3.4-1 [namespace.udir]. This allows us to fall back onto
- // testing::internal2::operator<< in case T doesn't come with a <<
- // operator.
-
- using ::testing::internal2::operator<<;
-
- // Assuming T is defined in namespace foo, in the next statement,
- // the compiler will consider all of:
- //
- // 1. foo::operator<< (thanks to Koenig look-up),
- // 2. ::operator<< (as the current namespace is enclosed in ::),
- // 3. testing::internal2::operator<< (thanks to the using statement above).
- //
- // The operator<< whose type matches T best will be picked.
- //
- // We deliberately allow #2 to be a candidate, as sometimes it's
- // impossible to define #1 (e.g. when foo is ::std, defining
- // anything in it is undefined behavior unless you are a compiler
- // vendor.).
- *os << value;
+constexpr bool UseStreamOperator() {
+ return !std::is_same<decltype(std::declval<std::ostream&>()
+ << std::declval<const T&>()),
+ Sentinel*>::value;
}
-} // namespace testing_internal
+} // namespace internal_stream
-namespace testing {
-namespace internal {
+struct StreamPrinter {
+ template <typename T, typename = typename std::enable_if<
+ internal_stream::UseStreamOperator<T>()>::type>
+ static void PrintValue(const T& value, ::std::ostream* os) {
+ *os << value;
+ }
+};
+
+struct ProtobufPrinter {
+ // We print a protobuf using its ShortDebugString() when the string
+ // doesn't exceed this many characters; otherwise we print it using
+ // DebugString() for better readability.
+ static const size_t kProtobufOneLinerMaxLength = 50;
+
+ template <typename T, typename = typename std::enable_if<
+ internal::IsAProtocolMessage<T>::value>::type>
+ static void PrintValue(const T& value, ::std::ostream* os) {
+ std::string pretty_str = value.ShortDebugString();
+ if (pretty_str.length() > kProtobufOneLinerMaxLength) {
+ pretty_str = "\n" + value.DebugString();
+ }
+ *os << ("<" + pretty_str + ">");
+ }
+};
+
+struct ConvertibleToIntegerPrinter {
+ // Since T has no << operator or PrintTo() but can be implicitly
+ // converted to BiggestInt, we print it as a BiggestInt.
+ //
+ // Most likely T is an enum type (either named or unnamed), in which
+ // case printing it as an integer is the desired behavior. In case
+ // T is not an enum, printing it as an integer is the best we can do
+ // given that it has no user-defined printer.
+ static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
+ *os << value;
+ }
+};
+
+struct ConvertibleToStringViewPrinter {
+#if GTEST_INTERNAL_HAS_STRING_VIEW
+ static void PrintValue(internal::StringView value, ::std::ostream* os) {
+ internal::UniversalPrint(value, os);
+ }
+#endif
+};
+
+
+// Prints the given number of bytes in the given object to the given
+// ostream.
+GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
+ size_t count,
+ ::std::ostream* os);
+struct FallbackPrinter {
+ template <typename T>
+ static void PrintValue(const T& value, ::std::ostream* os) {
+ PrintBytesInObjectTo(
+ static_cast<const unsigned char*>(
+ reinterpret_cast<const void*>(std::addressof(value))),
+ sizeof(value), os);
+ }
+};
+
+// Try every printer in order and return the first one that works.
+template <typename T, typename E, typename Printer, typename... Printers>
+struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
+
+template <typename T, typename Printer, typename... Printers>
+struct FindFirstPrinter<
+ T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
+ Printer, Printers...> {
+ using type = Printer;
+};
+
+// Select the best printer in the following order:
+// - Print containers (they have begin/end/etc).
+// - Print function pointers.
+// - Print object pointers.
+// - Use the stream operator, if available.
+// - Print protocol buffers.
+// - Print types convertible to BiggestInt.
+// - Print types convertible to StringView, if available.
+// - Fallback to printing the raw bytes of the object.
+template <typename T>
+void PrintWithFallback(const T& value, ::std::ostream* os) {
+ using Printer = typename FindFirstPrinter<
+ T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
+ StreamPrinter, ProtobufPrinter, ConvertibleToIntegerPrinter,
+ ConvertibleToStringViewPrinter, FallbackPrinter>::type;
+ Printer::PrintValue(value, os);
+}
// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
// value of type ToPrint that is an operand of a comparison assertion
@@ -386,85 +409,6 @@
template <typename T>
class UniversalPrinter;
-template <typename T>
-void UniversalPrint(const T& value, ::std::ostream* os);
-
-enum DefaultPrinterType {
- kPrintContainer,
- kPrintPointer,
- kPrintFunctionPointer,
- kPrintOther,
-};
-template <DefaultPrinterType type> struct WrapPrinterType {};
-
-// Used to print an STL-style container when the user doesn't define
-// a PrintTo() for it.
-template <typename C>
-void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
- const C& container, ::std::ostream* os) {
- const size_t kMaxCount = 32; // The maximum number of elements to print.
- *os << '{';
- size_t count = 0;
- for (typename C::const_iterator it = container.begin();
- it != container.end(); ++it, ++count) {
- if (count > 0) {
- *os << ',';
- if (count == kMaxCount) { // Enough has been printed.
- *os << " ...";
- break;
- }
- }
- *os << ' ';
- // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
- // handle *it being a native array.
- internal::UniversalPrint(*it, os);
- }
-
- if (count > 0) {
- *os << ' ';
- }
- *os << '}';
-}
-
-// Used to print a pointer that is neither a char pointer nor a member
-// pointer, when the user doesn't define PrintTo() for it. (A member
-// variable pointer or member function pointer doesn't really point to
-// a location in the address space. Their representation is
-// implementation-defined. Therefore they will be printed as raw
-// bytes.)
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
- T* p, ::std::ostream* os) {
- if (p == nullptr) {
- *os << "NULL";
- } else {
- // T is not a function type. We just call << to print p,
- // relying on ADL to pick up user-defined << for their pointer
- // types, if any.
- *os << p;
- }
-}
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
- T* p, ::std::ostream* os) {
- if (p == nullptr) {
- *os << "NULL";
- } else {
- // T is a function type, so '*os << p' doesn't do what we want
- // (it just prints p as bool). We want to print p as a const
- // void*.
- *os << reinterpret_cast<const void*>(p);
- }
-}
-
-// Used to print a non-container, non-pointer value when the user
-// doesn't define PrintTo() for it.
-template <typename T>
-void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
- const T& value, ::std::ostream* os) {
- ::testing_internal::DefaultPrintNonContainerTo(value, os);
-}
-
// Prints the given value using the << operator if it has one;
// otherwise prints the bytes in it. This is what
// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
@@ -478,36 +422,7 @@
// wants).
template <typename T>
void PrintTo(const T& value, ::std::ostream* os) {
- // DefaultPrintTo() is overloaded. The type of its first argument
- // determines which version will be picked.
- //
- // Note that we check for container types here, prior to we check
- // for protocol message types in our operator<<. The rationale is:
- //
- // For protocol messages, we want to give people a chance to
- // override Google Mock's format by defining a PrintTo() or
- // operator<<. For STL containers, other formats can be
- // incompatible with Google Mock's format for the container
- // elements; therefore we check for container types here to ensure
- // that our format is used.
- //
- // Note that MSVC and clang-cl do allow an implicit conversion from
- // pointer-to-function to pointer-to-object, but clang-cl warns on it.
- // So don't use ImplicitlyConvertible if it can be helped since it will
- // cause this warning, and use a separate overload of DefaultPrintTo for
- // function pointers so that the `*os << p` in the object pointer overload
- // doesn't cause that warning either.
- DefaultPrintTo(
- WrapPrinterType <
- (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
- !IsRecursiveContainer<T>::value
- ? kPrintContainer
- : !std::is_pointer<T>::value
- ? kPrintOther
- : std::is_function<typename std::remove_pointer<T>::type>::value
- ? kPrintFunctionPointer
- : kPrintPointer > (),
- value, os);
+ internal::PrintWithFallback(value, os);
}
// The following list of PrintTo() overloads tells
@@ -687,10 +602,11 @@
class UniversalPrinter<Any> {
public:
static void Print(const Any& value, ::std::ostream* os) {
- if (value.has_value())
- *os << "'any' type with value of type " << GetTypeName(value);
- else
- *os << "'any' type with no value";
+ if (value.has_value()) {
+ *os << "value of type " << GetTypeName(value);
+ } else {
+ *os << "no value";
+ }
}
private:
@@ -698,8 +614,8 @@
#if GTEST_HAS_RTTI
return internal::GetTypeName(value.type());
#else
- static_cast<void>(value); // possibly unused
- return "the element type";
+ static_cast<void>(value); // possibly unused
+ return "<unknown_type>";
#endif // GTEST_HAS_RTTI
}
};
@@ -747,7 +663,8 @@
struct Visitor {
template <typename U>
void operator()(const U& u) const {
- *os << "'" << GetTypeName<U>() << "(" << index << ")' with value ";
+ *os << "'" << GetTypeName<U>() << "(index = " << index
+ << ")' with value ";
UniversalPrint(u, os);
}
::std::ostream* os;
@@ -934,16 +851,6 @@
} // namespace internal
-#if GTEST_INTERNAL_HAS_STRING_VIEW
-namespace internal2 {
-template <typename T>
-void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
- const T& value, ::std::ostream* os) {
- internal::PrintTo(internal::StringView(value), os);
-}
-} // namespace internal2
-#endif
-
template <typename T>
::std::string PrintToString(const T& value) {
::std::stringstream ss;
diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h
index 8871207..a0942b4 100644
--- a/googletest/include/gtest/gtest.h
+++ b/googletest/include/gtest/gtest.h
@@ -101,6 +101,10 @@
// to let Google Test decide.
GTEST_DECLARE_string_(color);
+// This flag controls whether the test runner should continue execution past
+// first failure.
+GTEST_DECLARE_bool_(fail_fast);
+
// This flag sets up the filter to select by name using a glob pattern
// the tests to run. If the filter is not given all tests are executed.
GTEST_DECLARE_string_(filter);
@@ -117,6 +121,9 @@
// in addition to its normal textual output.
GTEST_DECLARE_string_(output);
+// This flags control whether Google Test prints only test failures.
+GTEST_DECLARE_bool_(brief);
+
// This flags control whether Google Test prints the elapsed time for each
// test.
GTEST_DECLARE_bool_(print_time);
@@ -411,10 +418,10 @@
// The d'tor is virtual as we intend to inherit from Test.
virtual ~Test();
- // Sets up the stuff shared by all tests in this test case.
+ // Sets up the stuff shared by all tests in this test suite.
//
// Google Test will call Foo::SetUpTestSuite() before running the first
- // test in test case Foo. Hence a sub-class can define its own
+ // test in test suite Foo. Hence a sub-class can define its own
// SetUpTestSuite() method to shadow the one defined in the super
// class.
static void SetUpTestSuite() {}
@@ -422,7 +429,7 @@
// Tears down the stuff shared by all tests in this test suite.
//
// Google Test will call Foo::TearDownTestSuite() after running the last
- // test in test case Foo. Hence a sub-class can define its own
+ // test in test suite Foo. Hence a sub-class can define its own
// TearDownTestSuite() method to shadow the one defined in the super
// class.
static void TearDownTestSuite() {}
@@ -795,6 +802,9 @@
// deletes it.
void Run();
+ // Skip and records the test result for this object.
+ void Skip();
+
static void ClearTestResult(TestInfo* test_info) {
test_info->result_.Clear();
}
@@ -943,6 +953,9 @@
// Runs every test in this TestSuite.
void Run();
+ // Skips the execution of tests under this TestSuite
+ void Skip();
+
// Runs SetUpTestSuite() for this TestSuite. This wrapper is needed
// for catching exceptions thrown from SetUpTestSuite().
void RunSetUpTestSuite() {
@@ -1807,12 +1820,6 @@
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
};
-enum class GTestColor { kDefault, kRed, kGreen, kYellow };
-
-GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color,
- const char* fmt,
- ...);
-
} // namespace internal
// The pure interface class that all value-parameterized tests inherit from.
diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h
index 6bad878..028f21e 100644
--- a/googletest/include/gtest/internal/gtest-internal.h
+++ b/googletest/include/gtest/internal/gtest-internal.h
@@ -90,7 +90,9 @@
#define GTEST_STRINGIFY_HELPER_(name, ...) #name
#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )
-namespace proto2 { class Message; }
+namespace proto2 {
+class MessageLite;
+}
namespace testing {
@@ -879,10 +881,10 @@
typename std::remove_const<typename std::remove_reference<T>::type>::type
// IsAProtocolMessage<T>::value is a compile-time bool constant that's
-// true if and only if T is type proto2::Message or a subclass of it.
+// true if and only if T is type proto2::MessageLite or a subclass of it.
template <typename T>
struct IsAProtocolMessage
- : public std::is_convertible<const T*, const ::proto2::Message*> {};
+ : public std::is_convertible<const T*, const ::proto2::MessageLite*> {};
// When the compiler sees expression IsContainerTest<C>(0), if C is an
// STL-style container class, the first overload of IsContainerTest
@@ -1118,8 +1120,6 @@
const Element* array_;
size_t size_;
void (NativeArray::*clone_)(const Element*, size_t);
-
- GTEST_DISALLOW_ASSIGN_(NativeArray);
};
// Backport of std::index_sequence.
@@ -1283,8 +1283,13 @@
// Suppress MSVC warning 4072 (unreachable code) for the code following
// statement if it returns or throws (or doesn't return or throw in some
// situations).
+// NOTE: The "else" is important to keep this expansion to prevent a top-level
+// "else" from attaching to our "if".
#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \
- if (::testing::internal::AlwaysTrue()) { statement; }
+ if (::testing::internal::AlwaysTrue()) { \
+ statement; \
+ } else /* NOLINT */ \
+ static_assert(true, "") // User must have a semicolon after expansion.
#define GTEST_TEST_THROW_(statement, expected_exception, fail) \
GTEST_AMBIGUOUS_ELSE_BLOCKER_ \
diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h
index 75e00cc..6f9c14a 100644
--- a/googletest/include/gtest/internal/gtest-port.h
+++ b/googletest/include/gtest/internal/gtest-port.h
@@ -201,13 +201,16 @@
// is suppressed.
// GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or
// UniversalPrinter<absl::any> specializations.
-// GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional> or
-// UniversalPrinter<absl::optional> specializations.
+// GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>
+// or
+// UniversalPrinter<absl::optional>
+// specializations.
// GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or
// Matcher<absl::string_view>
// specializations.
// GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or
-// UniversalPrinter<absl::variant> specializations.
+// UniversalPrinter<absl::variant>
+// specializations.
//
// Synchronization:
// Mutex, MutexLock, ThreadLocal, GetThreadCount()
@@ -258,6 +261,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+
+#include <cerrno>
#include <cstdint>
#include <limits>
#include <type_traits>
@@ -273,6 +278,7 @@
#endif
#include <iostream> // NOLINT
+#include <locale>
#include <memory>
#include <string> // NOLINT
#include <tuple>
@@ -685,8 +691,8 @@
// A macro to disallow copy constructor and operator=
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \
- type(type const &) = delete; \
- GTEST_DISALLOW_ASSIGN_(type)
+ type(type const&) = delete; \
+ type& operator=(type const&) = delete
// A macro to disallow move operator=
// This should be used in the private: declarations for a class.
@@ -696,8 +702,8 @@
// A macro to disallow move constructor and operator=
// This should be used in the private: declarations for a class.
#define GTEST_DISALLOW_MOVE_AND_ASSIGN_(type) \
- type(type &&) noexcept = delete; \
- GTEST_DISALLOW_MOVE_ASSIGN_(type)
+ type(type&&) noexcept = delete; \
+ type& operator=(type&&) noexcept = delete
// Tell the compiler to warn about unused return values for functions declared
// with this macro. The macro should be used on function declarations
@@ -924,8 +930,6 @@
const char* full_pattern_; // For FullMatch();
# endif
-
- GTEST_DISALLOW_ASSIGN_(RE);
};
#endif // GTEST_USES_PCRE
@@ -1966,16 +1970,16 @@
typedef struct _stat StatStruct;
# ifdef __BORLANDC__
-inline int IsATTY(int fd) { return isatty(fd); }
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int StrCaseCmp(const char* s1, const char* s2) {
return stricmp(s1, s2);
}
inline char* StrDup(const char* src) { return strdup(src); }
# else // !__BORLANDC__
# if GTEST_OS_WINDOWS_MOBILE
-inline int IsATTY(int /* fd */) { return 0; }
+inline int DoIsATTY(int /* fd */) { return 0; }
# else
-inline int IsATTY(int fd) { return _isatty(fd); }
+inline int DoIsATTY(int fd) { return _isatty(fd); }
# endif // GTEST_OS_WINDOWS_MOBILE
inline int StrCaseCmp(const char* s1, const char* s2) {
return _stricmp(s1, s2);
@@ -2000,7 +2004,7 @@
typedef struct stat StatStruct;
inline int FileNo(FILE* file) { return fileno(file); }
-inline int IsATTY(int fd) { return isatty(fd); }
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int Stat(const char* path, StatStruct* buf) {
// stat function not implemented on ESP8266
return 0;
@@ -2017,7 +2021,7 @@
typedef struct stat StatStruct;
inline int FileNo(FILE* file) { return fileno(file); }
-inline int IsATTY(int fd) { return isatty(fd); }
+inline int DoIsATTY(int fd) { return isatty(fd); }
inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }
inline int StrCaseCmp(const char* s1, const char* s2) {
return strcasecmp(s1, s2);
@@ -2028,6 +2032,17 @@
#endif // GTEST_OS_WINDOWS
+inline int IsATTY(int fd) {
+ // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout
+ // to a file on Linux), which is unexpected, so save the previous value, and
+ // restore it after the call.
+ int savedErrno = errno;
+ int isAttyValue = DoIsATTY(fd);
+ errno = savedErrno;
+
+ return isAttyValue;
+}
+
// Functions deprecated by MSVC 8.0.
GTEST_DISABLE_MSC_DEPRECATED_PUSH_()
@@ -2040,7 +2055,15 @@
inline int ChDir(const char* dir) { return chdir(dir); }
#endif
inline FILE* FOpen(const char* path, const char* mode) {
+#if GTEST_OS_WINDOWS
+ struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};
+ std::wstring_convert<wchar_codecvt> converter;
+ std::wstring wide_path = converter.from_bytes(path);
+ std::wstring wide_mode = converter.from_bytes(mode);
+ return _wfopen(wide_path.c_str(), wide_mode.c_str());
+#else
return fopen(path, mode);
+#endif // GTEST_OS_WINDOWS
}
#if !GTEST_OS_WINDOWS_MOBILE
inline FILE *FReopen(const char* path, const char* mode, FILE* stream) {
@@ -2232,7 +2255,7 @@
#if GTEST_HAS_ABSL
// Always use absl::any for UniversalPrinter<> specializations if googletest
// is built with absl support.
-# define GTEST_INTERNAL_HAS_ANY 1
+#define GTEST_INTERNAL_HAS_ANY 1
#include "absl/types/any.h"
namespace testing {
namespace internal {
@@ -2240,11 +2263,11 @@
} // namespace internal
} // namespace testing
#else
-# ifdef __has_include
-# if __has_include(<any>) && __cplusplus >= 201703L
+#ifdef __has_include
+#if __has_include(<any>) && __cplusplus >= 201703L
// Otherwise for C++17 and higher use std::any for UniversalPrinter<>
// specializations.
-# define GTEST_INTERNAL_HAS_ANY 1
+#define GTEST_INTERNAL_HAS_ANY 1
#include <any>
namespace testing {
namespace internal {
@@ -2253,14 +2276,14 @@
} // namespace testing
// The case where absl is configured NOT to alias std::any is not
// supported.
-# endif // __has_include(<any>) && __cplusplus >= 201703L
-# endif // __has_include
+#endif // __has_include(<any>) && __cplusplus >= 201703L
+#endif // __has_include
#endif // GTEST_HAS_ABSL
#if GTEST_HAS_ABSL
-// Always use absl::optional for UniversalPrinter<> specializations if googletest
-// is built with absl support.
-# define GTEST_INTERNAL_HAS_OPTIONAL 1
+// Always use absl::optional for UniversalPrinter<> specializations if
+// googletest is built with absl support.
+#define GTEST_INTERNAL_HAS_OPTIONAL 1
#include "absl/types/optional.h"
namespace testing {
namespace internal {
@@ -2269,11 +2292,11 @@
} // namespace internal
} // namespace testing
#else
-# ifdef __has_include
-# if __has_include(<optional>) && __cplusplus >= 201703L
+#ifdef __has_include
+#if __has_include(<optional>) && __cplusplus >= 201703L
// Otherwise for C++17 and higher use std::optional for UniversalPrinter<>
// specializations.
-# define GTEST_INTERNAL_HAS_OPTIONAL 1
+#define GTEST_INTERNAL_HAS_OPTIONAL 1
#include <optional>
namespace testing {
namespace internal {
@@ -2283,8 +2306,8 @@
} // namespace testing
// The case where absl is configured NOT to alias std::optional is not
// supported.
-# endif // __has_include(<optional>) && __cplusplus >= 201703L
-# endif // __has_include
+#endif // __has_include(<optional>) && __cplusplus >= 201703L
+#endif // __has_include
#endif // GTEST_HAS_ABSL
#if GTEST_HAS_ABSL
@@ -2318,7 +2341,7 @@
#if GTEST_HAS_ABSL
// Always use absl::variant for UniversalPrinter<> specializations if googletest
// is built with absl support.
-# define GTEST_INTERNAL_HAS_VARIANT 1
+#define GTEST_INTERNAL_HAS_VARIANT 1
#include "absl/types/variant.h"
namespace testing {
namespace internal {
@@ -2327,11 +2350,11 @@
} // namespace internal
} // namespace testing
#else
-# ifdef __has_include
-# if __has_include(<variant>) && __cplusplus >= 201703L
+#ifdef __has_include
+#if __has_include(<variant>) && __cplusplus >= 201703L
// Otherwise for C++17 and higher use std::variant for UniversalPrinter<>
// specializations.
-# define GTEST_INTERNAL_HAS_VARIANT 1
+#define GTEST_INTERNAL_HAS_VARIANT 1
#include <variant>
namespace testing {
namespace internal {
@@ -2339,10 +2362,9 @@
using Variant = ::std::variant<T...>;
} // namespace internal
} // namespace testing
-// The case where absl is configured NOT to alias std::variant is not
-// supported.
-# endif // __has_include(<variant>) && __cplusplus >= 201703L
-# endif // __has_include
+// The case where absl is configured NOT to alias std::variant is not supported.
+#endif // __has_include(<variant>) && __cplusplus >= 201703L
+#endif // __has_include
#endif // GTEST_HAS_ABSL
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
diff --git a/googletest/src/gtest-filepath.cc b/googletest/src/gtest-filepath.cc
index 9aad12f..062b95b 100644
--- a/googletest/src/gtest-filepath.cc
+++ b/googletest/src/gtest-filepath.cc
@@ -349,33 +349,21 @@
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
void FilePath::Normalize() {
- if (pathname_.c_str() == nullptr) {
- pathname_ = "";
- return;
- }
- const char* src = pathname_.c_str();
- char* const dest = new char[pathname_.length() + 1];
- char* dest_ptr = dest;
- memset(dest_ptr, 0, pathname_.length() + 1);
+ std::string normalized_pathname;
+ normalized_pathname.reserve(pathname_.length());
- while (*src != '\0') {
- *dest_ptr = *src;
- if (!IsPathSeparator(*src)) {
- src++;
+ for (const char character : pathname_) {
+ if (!IsPathSeparator(character)) {
+ normalized_pathname.push_back(character);
+ } else if (normalized_pathname.empty() ||
+ normalized_pathname.back() != kPathSeparator) {
+ normalized_pathname.push_back(kPathSeparator);
} else {
-#if GTEST_HAS_ALT_PATH_SEP_
- if (*dest_ptr == kAlternatePathSeparator) {
- *dest_ptr = kPathSeparator;
- }
-#endif
- while (IsPathSeparator(*src))
- src++;
+ continue;
}
- dest_ptr++;
}
- *dest_ptr = '\0';
- pathname_ = dest;
- delete[] dest;
+
+ pathname_ = normalized_pathname;
}
} // namespace internal
diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h
index e42ff47..aef5571 100644
--- a/googletest/src/gtest-internal-inl.h
+++ b/googletest/src/gtest-internal-inl.h
@@ -84,9 +84,11 @@
const char kBreakOnFailureFlag[] = "break_on_failure";
const char kCatchExceptionsFlag[] = "catch_exceptions";
const char kColorFlag[] = "color";
+const char kFailFast[] = "fail_fast";
const char kFilterFlag[] = "filter";
const char kListTestsFlag[] = "list_tests";
const char kOutputFlag[] = "output";
+const char kBriefFlag[] = "brief";
const char kPrintTimeFlag[] = "print_time";
const char kPrintUTF8Flag[] = "print_utf8";
const char kRandomSeedFlag[] = "random_seed";
@@ -164,10 +166,12 @@
color_ = GTEST_FLAG(color);
death_test_style_ = GTEST_FLAG(death_test_style);
death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
+ fail_fast_ = GTEST_FLAG(fail_fast);
filter_ = GTEST_FLAG(filter);
internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
list_tests_ = GTEST_FLAG(list_tests);
output_ = GTEST_FLAG(output);
+ brief_ = GTEST_FLAG(brief);
print_time_ = GTEST_FLAG(print_time);
print_utf8_ = GTEST_FLAG(print_utf8);
random_seed_ = GTEST_FLAG(random_seed);
@@ -187,9 +191,11 @@
GTEST_FLAG(death_test_style) = death_test_style_;
GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
GTEST_FLAG(filter) = filter_;
+ GTEST_FLAG(fail_fast) = fail_fast_;
GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
GTEST_FLAG(list_tests) = list_tests_;
GTEST_FLAG(output) = output_;
+ GTEST_FLAG(brief) = brief_;
GTEST_FLAG(print_time) = print_time_;
GTEST_FLAG(print_utf8) = print_utf8_;
GTEST_FLAG(random_seed) = random_seed_;
@@ -208,10 +214,12 @@
std::string color_;
std::string death_test_style_;
bool death_test_use_fork_;
+ bool fail_fast_;
std::string filter_;
std::string internal_run_death_test_;
bool list_tests_;
std::string output_;
+ bool brief_;
bool print_time_;
bool print_utf8_;
int32_t random_seed_;
diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc
index a05c50a..c180233 100644
--- a/googletest/src/gtest-port.cc
+++ b/googletest/src/gtest-port.cc
@@ -208,7 +208,7 @@
// exclude empty members
int nthreads = 0;
- for (int i = 0; i < size / mib[4]; i++) {
+ for (size_t i = 0; i < size / mib[4]; i++) {
if (info[i].p_tid != -1)
nthreads++;
}
diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc
index 3337be3..4e1ccad 100644
--- a/googletest/src/gtest-printers.cc
+++ b/googletest/src/gtest-printers.cc
@@ -104,7 +104,7 @@
} // namespace
-namespace internal2 {
+namespace internal {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
@@ -116,10 +116,6 @@
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
-} // namespace internal2
-
-namespace internal {
-
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
diff --git a/googletest/src/gtest-typed-test.cc b/googletest/src/gtest-typed-test.cc
index 1b1cfb0..722c7b1 100644
--- a/googletest/src/gtest-typed-test.cc
+++ b/googletest/src/gtest-typed-test.cc
@@ -78,17 +78,7 @@
continue;
}
- bool found = false;
- for (RegisteredTestIter it = registered_tests_.begin();
- it != registered_tests_.end();
- ++it) {
- if (name == it->first) {
- found = true;
- break;
- }
- }
-
- if (found) {
+ if (registered_tests_.count(name) != 0) {
tests.insert(name);
} else {
errors << "No test named " << name
diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc
index 2259260..5a8999f 100644
--- a/googletest/src/gtest.cc
+++ b/googletest/src/gtest.cc
@@ -86,7 +86,6 @@
#ifdef _MSC_VER
# include <crtdbg.h> // NOLINT
-# include <debugapi.h> // NOLINT
#endif
# include <io.h> // NOLINT
@@ -213,6 +212,21 @@
return kUniversalFilter;
}
+// Bazel passes in the argument to '--test_runner_fail_fast' via the
+// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.
+static bool GetDefaultFailFast() {
+ const char* const testbridge_test_runner_fail_fast =
+ internal::posix::GetEnv("TESTBRIDGE_TEST_RUNNER_FAIL_FAST");
+ if (testbridge_test_runner_fail_fast != nullptr) {
+ return strcmp(testbridge_test_runner_fail_fast, "1") == 0;
+ }
+ return false;
+}
+
+GTEST_DEFINE_bool_(
+ fail_fast, internal::BoolFromGTestEnv("fail_fast", GetDefaultFailFast()),
+ "True if and only if a test failure should stop further test execution.");
+
GTEST_DEFINE_bool_(
also_run_disabled_tests,
internal::BoolFromGTestEnv("also_run_disabled_tests", false),
@@ -273,6 +287,10 @@
"executable's name and, if necessary, made unique by adding "
"digits.");
+GTEST_DEFINE_bool_(
+ brief, internal::BoolFromGTestEnv("brief", false),
+ "True if only test failures should be displayed in text output.");
+
GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true),
"True if and only if " GTEST_NAME_
" should display elapsed time in text output.");
@@ -2176,7 +2194,9 @@
if (user_msg_string.empty()) {
return gtest_msg;
}
-
+ if (gtest_msg.empty()) {
+ return user_msg_string;
+ }
return gtest_msg + "\n" + user_msg_string;
}
@@ -2255,7 +2275,8 @@
// The list of reserved attributes used in the <testsuite> element of XML
// output.
static const char* const kReservedTestSuiteAttributes[] = {
- "disabled", "errors", "failures", "name", "tests", "time", "timestamp"};
+ "disabled", "errors", "failures", "name",
+ "tests", "time", "timestamp", "skipped"};
// The list of reserved attributes used in the <testcase> element of XML output.
static const char* const kReservedTestCaseAttributes[] = {
@@ -2268,7 +2289,7 @@
"classname", "name", "status", "time", "type_param",
"value_param", "file", "line", "result", "timestamp"};
-template <int kSize>
+template <size_t kSize>
std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
return std::vector<std::string>(array, array + kSize);
}
@@ -2863,6 +2884,28 @@
impl->set_current_test_info(nullptr);
}
+// Skip and records a skipped test result for this object.
+void TestInfo::Skip() {
+ if (!should_run_) return;
+
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
+ impl->set_current_test_info(this);
+
+ TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+
+ // Notifies the unit test event listeners that a test is about to start.
+ repeater->OnTestStart(*this);
+
+ const TestPartResult test_part_result =
+ TestPartResult(TestPartResult::kSkip, this->file(), this->line(), "");
+ impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(
+ test_part_result);
+
+ // Notifies the unit test event listener that a test has just finished.
+ repeater->OnTestEnd(*this);
+ impl->set_current_test_info(nullptr);
+}
+
// class TestSuite
// Gets the number of successful tests in this test suite.
@@ -2975,6 +3018,12 @@
start_timestamp_ = internal::GetTimeInMillis();
for (int i = 0; i < total_test_count(); i++) {
GetMutableTestInfo(i)->Run();
+ if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {
+ for (int j = i + 1; j < total_test_count(); j++) {
+ GetMutableTestInfo(j)->Skip();
+ }
+ break;
+ }
}
elapsed_time_ = internal::GetTimeInMillis() - start_timestamp_;
@@ -2992,6 +3041,36 @@
impl->set_current_test_suite(nullptr);
}
+// Skips all tests under this TestSuite.
+void TestSuite::Skip() {
+ if (!should_run_) return;
+
+ internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
+ impl->set_current_test_suite(this);
+
+ TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
+
+ // Call both legacy and the new API
+ repeater->OnTestSuiteStart(*this);
+// Legacy API is deprecated but still available
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+ repeater->OnTestCaseStart(*this);
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+
+ for (int i = 0; i < total_test_count(); i++) {
+ GetMutableTestInfo(i)->Skip();
+ }
+
+ // Call both legacy and the new API
+ repeater->OnTestSuiteEnd(*this);
+ // Legacy API is deprecated but still available
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI
+ repeater->OnTestCaseEnd(*this);
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI
+
+ impl->set_current_test_suite(nullptr);
+}
+
// Clears the results of all tests in this test suite.
void TestSuite::ClearResult() {
ad_hoc_test_result_.Clear();
@@ -3039,7 +3118,7 @@
static const char * TestPartResultTypeToString(TestPartResult::Type type) {
switch (type) {
case TestPartResult::kSkip:
- return "Skipped";
+ return "Skipped\n";
case TestPartResult::kSuccess:
return "Success";
@@ -3056,6 +3135,9 @@
}
namespace internal {
+namespace {
+enum class GTestColor { kDefault, kRed, kGreen, kYellow };
+} // namespace
// Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString(
@@ -3194,6 +3276,7 @@
// cannot simply emit special characters and have the terminal change colors.
// This routine must actually emit the characters rather than return a string
// that would be colored when printed, as can be done on Linux.
+
void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
@@ -3562,6 +3645,110 @@
// End PrettyUnitTestResultPrinter
+// This class implements the TestEventListener interface.
+//
+// Class BriefUnitTestResultPrinter is copyable.
+class BriefUnitTestResultPrinter : public TestEventListener {
+ public:
+ BriefUnitTestResultPrinter() {}
+ static void PrintTestName(const char* test_suite, const char* test) {
+ printf("%s.%s", test_suite, test);
+ }
+
+ // The following methods override what's in the TestEventListener class.
+ void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}
+ void OnTestIterationStart(const UnitTest& /*unit_test*/,
+ int /*iteration*/) override {}
+ void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}
+ void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ void OnTestCaseStart(const TestCase& /*test_case*/) override {}
+#else
+ void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}
+#endif // OnTestCaseStart
+
+ void OnTestStart(const TestInfo& /*test_info*/) override {}
+
+ void OnTestPartResult(const TestPartResult& result) override;
+ void OnTestEnd(const TestInfo& test_info) override;
+#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+ void OnTestCaseEnd(const TestCase& /*test_case*/) override {}
+#else
+ void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}
+#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_
+
+ void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}
+ void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}
+ void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;
+ void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}
+};
+
+// Called after an assertion failure.
+void BriefUnitTestResultPrinter::OnTestPartResult(
+ const TestPartResult& result) {
+ switch (result.type()) {
+ // If the test part succeeded, we don't need to do anything.
+ case TestPartResult::kSuccess:
+ return;
+ default:
+ // Print failure message from the assertion
+ // (e.g. expected this and got that).
+ PrintTestPartResult(result);
+ fflush(stdout);
+ }
+}
+
+void BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
+ if (test_info.result()->Failed()) {
+ ColoredPrintf(GTestColor::kRed, "[ FAILED ] ");
+ PrintTestName(test_info.test_suite_name(), test_info.name());
+ PrintFullTestCommentIfPresent(test_info);
+
+ if (GTEST_FLAG(print_time)) {
+ printf(" (%s ms)\n",
+ internal::StreamableToString(test_info.result()->elapsed_time())
+ .c_str());
+ } else {
+ printf("\n");
+ }
+ fflush(stdout);
+ }
+}
+
+void BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
+ int /*iteration*/) {
+ ColoredPrintf(GTestColor::kGreen, "[==========] ");
+ printf("%s from %s ran.",
+ FormatTestCount(unit_test.test_to_run_count()).c_str(),
+ FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());
+ if (GTEST_FLAG(print_time)) {
+ printf(" (%s ms total)",
+ internal::StreamableToString(unit_test.elapsed_time()).c_str());
+ }
+ printf("\n");
+ ColoredPrintf(GTestColor::kGreen, "[ PASSED ] ");
+ printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
+
+ const int skipped_test_count = unit_test.skipped_test_count();
+ if (skipped_test_count > 0) {
+ ColoredPrintf(GTestColor::kGreen, "[ SKIPPED ] ");
+ printf("%s.\n", FormatTestCount(skipped_test_count).c_str());
+ }
+
+ int num_disabled = unit_test.reportable_disabled_test_count();
+ if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
+ if (unit_test.Passed()) {
+ printf("\n"); // Add a spacer if no FAILURE banner is displayed.
+ }
+ ColoredPrintf(GTestColor::kYellow, " YOU HAVE %d DISABLED %s\n\n",
+ num_disabled, num_disabled == 1 ? "TEST" : "TESTS");
+ }
+ // Ensure that Google Test output is printed before, e.g., heapchecker output.
+ fflush(stdout);
+}
+
+// End BriefUnitTestResultPrinter
+
// class TestEventRepeater
//
// This class forwards events to other event listeners.
@@ -4003,10 +4190,11 @@
OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name);
int failures = 0;
+ int skips = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
if (part.failed()) {
- if (++failures == 1) {
+ if (++failures == 1 && skips == 0) {
*stream << ">\n";
}
const std::string location =
@@ -4014,18 +4202,31 @@
part.line_number());
const std::string summary = location + "\n" + part.summary();
*stream << " <failure message=\""
- << EscapeXmlAttribute(summary.c_str())
+ << EscapeXmlAttribute(summary)
<< "\" type=\"\">";
const std::string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
*stream << "</failure>\n";
+ } else if (part.skipped()) {
+ if (++skips == 1 && failures == 0) {
+ *stream << ">\n";
+ }
+ const std::string location =
+ internal::FormatCompilerIndependentFileLocation(part.file_name(),
+ part.line_number());
+ const std::string summary = location + "\n" + part.summary();
+ *stream << " <skipped message=\""
+ << EscapeXmlAttribute(summary.c_str()) << "\">";
+ const std::string detail = location + "\n" + part.message();
+ OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
+ *stream << "</skipped>\n";
}
}
- if (failures == 0 && result.test_property_count() == 0) {
+ if (failures == 0 && skips == 0 && result.test_property_count() == 0) {
*stream << " />\n";
} else {
- if (failures == 0) {
+ if (failures == 0 && skips == 0) {
*stream << ">\n";
}
OutputXmlTestProperties(stream, result);
@@ -4047,7 +4248,11 @@
OutputXmlAttribute(
stream, kTestsuite, "disabled",
StreamableToString(test_suite.reportable_disabled_test_count()));
+ OutputXmlAttribute(stream, kTestsuite, "skipped",
+ StreamableToString(test_suite.skipped_test_count()));
+
OutputXmlAttribute(stream, kTestsuite, "errors", "0");
+
OutputXmlAttribute(stream, kTestsuite, "time",
FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));
OutputXmlAttribute(
@@ -5312,6 +5517,10 @@
// to shut down the default XML output before invoking RUN_ALL_TESTS.
ConfigureXmlOutput();
+ if (GTEST_FLAG(brief)) {
+ listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);
+ }
+
#if GTEST_CAN_STREAM_RESULTS_
// Configures listeners for streaming test results to the specified server.
ConfigureStreamingOutput();
@@ -5519,6 +5728,13 @@
for (int test_index = 0; test_index < total_test_suite_count();
test_index++) {
GetMutableSuiteCase(test_index)->Run();
+ if (GTEST_FLAG(fail_fast) &&
+ GetMutableSuiteCase(test_index)->Failed()) {
+ for (int j = test_index + 1; j < total_test_suite_count(); j++) {
+ GetMutableSuiteCase(j)->Skip();
+ }
+ break;
+ }
}
}
@@ -6056,98 +6272,126 @@
}
static const char kColorEncodedHelpMessage[] =
-"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
-"following command line flags to control its behavior:\n"
-"\n"
-"Test Selection:\n"
-" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
-" List the names of all tests instead of running them. The name of\n"
-" TEST(Foo, Bar) is \"Foo.Bar\".\n"
-" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
+ "This program contains tests written using " GTEST_NAME_
+ ". You can use the\n"
+ "following command line flags to control its behavior:\n"
+ "\n"
+ "Test Selection:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D\n"
+ " List the names of all tests instead of running them. The name of\n"
+ " TEST(Foo, Bar) is \"Foo.Bar\".\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "filter=@YPOSTIVE_PATTERNS"
"[@G-@YNEGATIVE_PATTERNS]@D\n"
-" Run only the tests whose name matches one of the positive patterns but\n"
-" none of the negative patterns. '?' matches any single character; '*'\n"
-" matches any substring; ':' separates two patterns.\n"
-" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
-" Run all disabled tests too.\n"
-"\n"
-"Test Execution:\n"
-" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
-" Run the tests repeatedly; use a negative count to repeat forever.\n"
-" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
-" Randomize tests' orders on every iteration.\n"
-" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
-" Random number seed to use for shuffling test orders (between 1 and\n"
-" 99999, or 0 to use a seed based on the current time).\n"
-"\n"
-"Test Output:\n"
-" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
-" Enable/disable colored output. The default is @Gauto@D.\n"
-" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
-" Don't print the elapsed time of each test.\n"
-" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G"
- GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
-" Generate a JSON or XML report in the given directory or with the given\n"
-" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
+ " Run only the tests whose name matches one of the positive patterns "
+ "but\n"
+ " none of the negative patterns. '?' matches any single character; "
+ "'*'\n"
+ " matches any substring; ':' separates two patterns.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "also_run_disabled_tests@D\n"
+ " Run all disabled tests too.\n"
+ "\n"
+ "Test Execution:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "repeat=@Y[COUNT]@D\n"
+ " Run the tests repeatedly; use a negative count to repeat forever.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "shuffle@D\n"
+ " Randomize tests' orders on every iteration.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "random_seed=@Y[NUMBER]@D\n"
+ " Random number seed to use for shuffling test orders (between 1 and\n"
+ " 99999, or 0 to use a seed based on the current time).\n"
+ "\n"
+ "Test Output:\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
+ " Enable/disable colored output. The default is @Gauto@D.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "brief=1@D\n"
+ " Only print test failures.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "print_time=0@D\n"
+ " Don't print the elapsed time of each test.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_
+ "@Y|@G:@YFILE_PATH]@D\n"
+ " Generate a JSON or XML report in the given directory or with the "
+ "given\n"
+ " file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n"
# if GTEST_CAN_STREAM_RESULTS_
-" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
-" Stream test results to the given server.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "stream_result_to=@YHOST@G:@YPORT@D\n"
+ " Stream test results to the given server.\n"
# endif // GTEST_CAN_STREAM_RESULTS_
-"\n"
-"Assertion Behavior:\n"
+ "\n"
+ "Assertion Behavior:\n"
# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
-" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
-" Set the default death test style.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
+ " Set the default death test style.\n"
# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
-" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
-" Turn assertion failures into debugger break-points.\n"
-" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
-" Turn assertion failures into C++ exceptions for use by an external\n"
-" test framework.\n"
-" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
-" Do not report exceptions as test failures. Instead, allow them\n"
-" to crash the program or throw a pop-up (on Windows).\n"
-"\n"
-"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
+ " @G--" GTEST_FLAG_PREFIX_
+ "break_on_failure@D\n"
+ " Turn assertion failures into debugger break-points.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "throw_on_failure@D\n"
+ " Turn assertion failures into C++ exceptions for use by an external\n"
+ " test framework.\n"
+ " @G--" GTEST_FLAG_PREFIX_
+ "catch_exceptions=0@D\n"
+ " Do not report exceptions as test failures. Instead, allow them\n"
+ " to crash the program or throw a pop-up (on Windows).\n"
+ "\n"
+ "Except for @G--" GTEST_FLAG_PREFIX_
+ "list_tests@D, you can alternatively set "
"the corresponding\n"
-"environment variable of a flag (all letters in upper-case). For example, to\n"
-"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
+ "environment variable of a flag (all letters in upper-case). For example, "
+ "to\n"
+ "disable colored text output, you can either specify "
+ "@G--" GTEST_FLAG_PREFIX_
"color=no@D or set\n"
-"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
-"\n"
-"For more information, please read the " GTEST_NAME_ " documentation at\n"
-"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
-"(not one in your own code or tests), please report it to\n"
-"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
+ "the @G" GTEST_FLAG_PREFIX_UPPER_
+ "COLOR@D environment variable to @Gno@D.\n"
+ "\n"
+ "For more information, please read the " GTEST_NAME_
+ " documentation at\n"
+ "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_
+ "\n"
+ "(not one in your own code or tests), please report it to\n"
+ "@G<" GTEST_DEV_EMAIL_ ">@D.\n";
static bool ParseGoogleTestFlag(const char* const arg) {
return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
>EST_FLAG(also_run_disabled_tests)) ||
- ParseBoolFlag(arg, kBreakOnFailureFlag,
- >EST_FLAG(break_on_failure)) ||
- ParseBoolFlag(arg, kCatchExceptionsFlag,
- >EST_FLAG(catch_exceptions)) ||
- ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
- ParseStringFlag(arg, kDeathTestStyleFlag,
- >EST_FLAG(death_test_style)) ||
- ParseBoolFlag(arg, kDeathTestUseFork,
- >EST_FLAG(death_test_use_fork)) ||
- ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
- ParseStringFlag(arg, kInternalRunDeathTestFlag,
- >EST_FLAG(internal_run_death_test)) ||
- ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
- ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
- ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
- ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) ||
- ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
- ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
- ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
- ParseInt32Flag(arg, kStackTraceDepthFlag,
- >EST_FLAG(stack_trace_depth)) ||
- ParseStringFlag(arg, kStreamResultToFlag,
- >EST_FLAG(stream_result_to)) ||
- ParseBoolFlag(arg, kThrowOnFailureFlag,
- >EST_FLAG(throw_on_failure));
+ ParseBoolFlag(arg, kBreakOnFailureFlag,
+ >EST_FLAG(break_on_failure)) ||
+ ParseBoolFlag(arg, kCatchExceptionsFlag,
+ >EST_FLAG(catch_exceptions)) ||
+ ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
+ ParseStringFlag(arg, kDeathTestStyleFlag,
+ >EST_FLAG(death_test_style)) ||
+ ParseBoolFlag(arg, kDeathTestUseFork,
+ >EST_FLAG(death_test_use_fork)) ||
+ ParseBoolFlag(arg, kFailFast, >EST_FLAG(fail_fast)) ||
+ ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
+ ParseStringFlag(arg, kInternalRunDeathTestFlag,
+ >EST_FLAG(internal_run_death_test)) ||
+ ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
+ ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
+ ParseBoolFlag(arg, kBriefFlag, >EST_FLAG(brief)) ||
+ ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
+ ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) ||
+ ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
+ ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
+ ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
+ ParseInt32Flag(arg, kStackTraceDepthFlag,
+ >EST_FLAG(stack_trace_depth)) ||
+ ParseStringFlag(arg, kStreamResultToFlag,
+ >EST_FLAG(stream_result_to)) ||
+ ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure));
}
#if GTEST_USE_OWN_FLAGFILE_FLAG_
diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel
index 456cc6f..e24f5f2 100644
--- a/googletest/test/BUILD.bazel
+++ b/googletest/test/BUILD.bazel
@@ -28,8 +28,6 @@
# (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 The Google C++ Testing Framework (Google Test)
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_test")
@@ -60,6 +58,7 @@
"googletest-catch-exceptions-test_.cc",
"googletest-color-test_.cc",
"googletest-env-var-test_.cc",
+ "googletest-failfast-unittest_.cc",
"googletest-filter-unittest_.cc",
"googletest-break-on-failure-unittest_.cc",
"googletest-listener-test.cc",
@@ -225,6 +224,21 @@
)
cc_binary(
+ name = "googletest-failfast-unittest_",
+ testonly = 1,
+ srcs = ["googletest-failfast-unittest_.cc"],
+ deps = ["//:gtest"],
+)
+
+py_test(
+ name = "googletest-failfast-unittest",
+ size = "medium",
+ srcs = ["googletest-failfast-unittest.py"],
+ data = [":googletest-failfast-unittest_"],
+ deps = [":gtest_test_utils"],
+)
+
+cc_binary(
name = "googletest-filter-unittest_",
testonly = 1,
srcs = ["googletest-filter-unittest_.cc"],
diff --git a/googletest/test/googletest-death-test-test.cc b/googletest/test/googletest-death-test-test.cc
index cba906c..b0dda27 100644
--- a/googletest/test/googletest-death-test-test.cc
+++ b/googletest/test/googletest-death-test-test.cc
@@ -391,17 +391,19 @@
// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).
void SetSigprofActionAndTimer() {
- struct itimerval timer;
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = 1;
- timer.it_value = timer.it_interval;
- ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
struct sigaction signal_action;
memset(&signal_action, 0, sizeof(signal_action));
sigemptyset(&signal_action.sa_mask);
signal_action.sa_sigaction = SigprofAction;
signal_action.sa_flags = SA_RESTART | SA_SIGINFO;
ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr));
+ // timer comes second, to avoid SIGPROF premature delivery, as suggested at
+ // https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html
+ struct itimerval timer;
+ timer.it_interval.tv_sec = 0;
+ timer.it_interval.tv_usec = 1;
+ timer.it_value = timer.it_interval;
+ ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));
}
// Disables ITIMER_PROF timer and ignores SIGPROF signal.
diff --git a/googletest/test/googletest-death-test_ex_test.cc b/googletest/test/googletest-death-test_ex_test.cc
index 7ea5b94..7219680 100644
--- a/googletest/test/googletest-death-test_ex_test.cc
+++ b/googletest/test/googletest-death-test_ex_test.cc
@@ -59,7 +59,7 @@
class TestException : public std::exception {
public:
- const char* what() const throw() override { return "exceptional message"; }
+ const char* what() const noexcept override { return "exceptional message"; }
};
TEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {
diff --git a/googletest/test/googletest-env-var-test.py b/googletest/test/googletest-env-var-test.py
index 2f0e406..02c3655 100755
--- a/googletest/test/googletest-env-var-test.py
+++ b/googletest/test/googletest-env-var-test.py
@@ -85,9 +85,12 @@
TestFlag('break_on_failure', '1', '0')
TestFlag('color', 'yes', 'auto')
+ SetEnvVar('TESTBRIDGE_TEST_RUNNER_FAIL_FAST', None) # For 'fail_fast' test
+ TestFlag('fail_fast', '1', '0')
TestFlag('filter', 'FooTest.Bar', '*')
SetEnvVar('XML_OUTPUT_FILE', None) # For 'output' test
TestFlag('output', 'xml:tmp/foo.xml', '')
+ TestFlag('brief', '1', '0')
TestFlag('print_time', '0', '1')
TestFlag('repeat', '999', '1')
TestFlag('throw_on_failure', '1', '0')
diff --git a/googletest/test/googletest-env-var-test_.cc b/googletest/test/googletest-env-var-test_.cc
index fd2aa82..52f9586 100644
--- a/googletest/test/googletest-env-var-test_.cc
+++ b/googletest/test/googletest-env-var-test_.cc
@@ -72,6 +72,11 @@
return;
}
+ if (strcmp(flag, "fail_fast") == 0) {
+ cout << GTEST_FLAG(fail_fast);
+ return;
+ }
+
if (strcmp(flag, "filter") == 0) {
cout << GTEST_FLAG(filter);
return;
@@ -82,6 +87,11 @@
return;
}
+ if (strcmp(flag, "brief") == 0) {
+ cout << GTEST_FLAG(brief);
+ return;
+ }
+
if (strcmp(flag, "print_time") == 0) {
cout << GTEST_FLAG(print_time);
return;
diff --git a/googletest/test/googletest-failfast-unittest.py b/googletest/test/googletest-failfast-unittest.py
new file mode 100755
index 0000000..3aeb2df
--- /dev/null
+++ b/googletest/test/googletest-failfast-unittest.py
@@ -0,0 +1,410 @@
+#!/usr/bin/env python
+#
+# Copyright 2020 Google Inc. All Rights Reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Unit test for Google Test fail_fast.
+
+A user can specify if a Google Test program should continue test execution
+after a test failure via the GTEST_FAIL_FAST environment variable or the
+--gtest_fail_fast flag. The default value of the flag can also be changed
+by Bazel fail fast environment variable TESTBRIDGE_TEST_RUNNER_FAIL_FAST.
+
+This script tests such functionality by invoking googletest-failfast-unittest_
+(a program written with Google Test) with different environments and command
+line flags.
+"""
+
+import os
+import gtest_test_utils
+
+# Constants.
+
+# Bazel testbridge environment variable for fail fast
+BAZEL_FAIL_FAST_ENV_VAR = 'TESTBRIDGE_TEST_RUNNER_FAIL_FAST'
+
+# The environment variable for specifying fail fast.
+FAIL_FAST_ENV_VAR = 'GTEST_FAIL_FAST'
+
+# The command line flag for specifying fail fast.
+FAIL_FAST_FLAG = 'gtest_fail_fast'
+
+# The command line flag to run disabled tests.
+RUN_DISABLED_FLAG = 'gtest_also_run_disabled_tests'
+
+# The command line flag for specifying a filter.
+FILTER_FLAG = 'gtest_filter'
+
+# Command to run the googletest-failfast-unittest_ program.
+COMMAND = gtest_test_utils.GetTestExecutablePath(
+ 'googletest-failfast-unittest_')
+
+# The command line flag to tell Google Test to output the list of tests it
+# will run.
+LIST_TESTS_FLAG = '--gtest_list_tests'
+
+# Indicates whether Google Test supports death tests.
+SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess(
+ [COMMAND, LIST_TESTS_FLAG]).output
+
+# Utilities.
+
+environ = os.environ.copy()
+
+
+def SetEnvVar(env_var, value):
+ """Sets the env variable to 'value'; unsets it when 'value' is None."""
+
+ if value is not None:
+ environ[env_var] = value
+ elif env_var in environ:
+ del environ[env_var]
+
+
+def RunAndReturnOutput(test_suite=None, fail_fast=None, run_disabled=False):
+ """Runs the test program and returns its output."""
+
+ args = []
+ xml_path = os.path.join(gtest_test_utils.GetTempDir(),
+ '.GTestFailFastUnitTest.xml')
+ args += ['--gtest_output=xml:' + xml_path]
+ if fail_fast is not None:
+ if isinstance(fail_fast, str):
+ args += ['--%s=%s' % (FAIL_FAST_FLAG, fail_fast)]
+ elif fail_fast:
+ args += ['--%s' % FAIL_FAST_FLAG]
+ else:
+ args += ['--no%s' % FAIL_FAST_FLAG]
+ if test_suite:
+ args += ['--%s=%s.*' % (FILTER_FLAG, test_suite)]
+ if run_disabled:
+ args += ['--%s' % RUN_DISABLED_FLAG]
+ txt_out = gtest_test_utils.Subprocess([COMMAND] + args, env=environ).output
+ with open(xml_path) as xml_file:
+ return txt_out, xml_file.read()
+
+
+# The unit test.
+class GTestFailFastUnitTest(gtest_test_utils.TestCase):
+ """Tests the env variable or the command line flag for fail_fast."""
+
+ def testDefaultBehavior(self):
+ """Tests the behavior of not specifying the fail_fast."""
+
+ txt, _ = RunAndReturnOutput()
+ self.assertIn('22 FAILED TEST', txt)
+
+ def testGoogletestFlag(self):
+ txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=False)
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+
+ def testGoogletestEnvVar(self):
+ """Tests the behavior of specifying fail_fast via Googletest env var."""
+
+ try:
+ SetEnvVar(FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ SetEnvVar(FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+
+ def testBazelEnvVar(self):
+ """Tests the behavior of specifying fail_fast via Bazel testbridge."""
+
+ try:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('4 FAILED TEST', txt)
+ self.assertNotIn('[ SKIPPED ]', txt)
+ finally:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)
+
+ def testFlagOverridesEnvVar(self):
+ """Tests precedence of flag over env var."""
+
+ try:
+ SetEnvVar(FAIL_FAST_ENV_VAR, '0')
+ txt, _ = RunAndReturnOutput('HasSimpleTest', True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+
+ def testGoogletestEnvVarOverridesBazelEnvVar(self):
+ """Tests that the Googletest native env var over Bazel testbridge."""
+
+ try:
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')
+ SetEnvVar(FAIL_FAST_ENV_VAR, '1')
+ txt, _ = RunAndReturnOutput('HasSimpleTest')
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ finally:
+ SetEnvVar(FAIL_FAST_ENV_VAR, None)
+ SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)
+
+ def testEventListener(self):
+ txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=True)
+ self.assertIn('1 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 3 tests', txt)
+ for expected_count, callback in [(1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd')]:
+ self.assertEqual(
+ expected_count, txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s ' %
+ (expected_count, callback, txt))
+
+ txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=False)
+ self.assertIn('3 FAILED TEST', txt)
+ self.assertIn('[ SKIPPED ] 1 test', txt)
+ for expected_count, callback in [(1, 'OnTestSuiteStart'),
+ (5, 'OnTestStart'),
+ (5, 'OnTestEnd'),
+ (5, 'OnTestPartResult'),
+ (1, 'OnTestSuiteEnd')]:
+ self.assertEqual(
+ expected_count, txt.count(callback),
+ 'Expected %d calls to callback %s match count on output: %s ' %
+ (expected_count, callback, txt))
+
+ def assertXmlResultCount(self, result, count, xml):
+ self.assertEqual(
+ count, xml.count('result="%s"' % result),
+ 'Expected \'result="%s"\' match count of %s: %s ' %
+ (result, count, xml))
+
+ def assertXmlStatusCount(self, status, count, xml):
+ self.assertEqual(
+ count, xml.count('status="%s"' % status),
+ 'Expected \'status="%s"\' match count of %s: %s ' %
+ (status, count, xml))
+
+ def assertFailFastXmlAndTxtOutput(self,
+ fail_fast,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False):
+ """Assert XML and text output of a test execution."""
+
+ txt, xml = RunAndReturnOutput(test_suite, fail_fast, run_disabled)
+ if failure_count > 0:
+ self.assertIn('%s FAILED TEST' % failure_count, txt)
+ if suppressed_count > 0:
+ self.assertIn('%s DISABLED TEST' % suppressed_count, txt)
+ if skipped_count > 0:
+ self.assertIn('[ SKIPPED ] %s tests' % skipped_count, txt)
+ self.assertXmlStatusCount('run',
+ passed_count + failure_count + skipped_count, xml)
+ self.assertXmlStatusCount('notrun', suppressed_count, xml)
+ self.assertXmlResultCount('completed', passed_count + failure_count, xml)
+ self.assertXmlResultCount('skipped', skipped_count, xml)
+ self.assertXmlResultCount('suppressed', suppressed_count, xml)
+
+ def assertFailFastBehavior(self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False):
+ """Assert --fail_fast via flag."""
+
+ for fail_fast in ('true', '1', 't', True):
+ self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,
+ failure_count, skipped_count,
+ suppressed_count, run_disabled)
+
+ def assertNotFailFastBehavior(self,
+ test_suite,
+ passed_count,
+ failure_count,
+ skipped_count,
+ suppressed_count,
+ run_disabled=False):
+ """Assert --nofail_fast via flag."""
+
+ for fail_fast in ('false', '0', 'f', False):
+ self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,
+ failure_count, skipped_count,
+ suppressed_count, run_disabled)
+
+ def testFlag_HasFixtureTest(self):
+ """Tests the behavior of fail_fast and TEST_F."""
+ self.assertFailFastBehavior(
+ test_suite='HasFixtureTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasFixtureTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+ def testFlag_HasSimpleTest(self):
+ """Tests the behavior of fail_fast and TEST."""
+ self.assertFailFastBehavior(
+ test_suite='HasSimpleTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasSimpleTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+ def testFlag_HasParametersTest(self):
+ """Tests the behavior of fail_fast and TEST_P."""
+ self.assertFailFastBehavior(
+ test_suite='HasParametersSuite/HasParametersTest',
+ passed_count=0,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasParametersSuite/HasParametersTest',
+ passed_count=0,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+ def testFlag_HasDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test cases."""
+ self.assertFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=2,
+ suppressed_count=1,
+ run_disabled=False)
+ self.assertNotFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=3,
+ skipped_count=0,
+ suppressed_count=1,
+ run_disabled=False)
+
+ def testFlag_HasDisabledRunDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test cases enabled."""
+ self.assertFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ run_disabled=True)
+ self.assertNotFailFastBehavior(
+ test_suite='HasDisabledTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ run_disabled=True)
+
+ def testFlag_HasDisabledSuiteTest(self):
+ """Tests the behavior of fail_fast and Disabled test suites."""
+ self.assertFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=0,
+ failure_count=0,
+ skipped_count=0,
+ suppressed_count=5,
+ run_disabled=False)
+ self.assertNotFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=0,
+ failure_count=0,
+ skipped_count=0,
+ suppressed_count=5,
+ run_disabled=False)
+
+ def testFlag_HasDisabledSuiteRunDisabledTest(self):
+ """Tests the behavior of fail_fast and Disabled test suites enabled."""
+ self.assertFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0,
+ run_disabled=True)
+ self.assertNotFailFastBehavior(
+ test_suite='DISABLED_HasDisabledSuite',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0,
+ run_disabled=True)
+
+ if SUPPORTS_DEATH_TESTS:
+
+ def testFlag_HasDeathTest(self):
+ """Tests the behavior of fail_fast and death tests."""
+ self.assertFailFastBehavior(
+ test_suite='HasDeathTest',
+ passed_count=1,
+ failure_count=1,
+ skipped_count=3,
+ suppressed_count=0)
+ self.assertNotFailFastBehavior(
+ test_suite='HasDeathTest',
+ passed_count=1,
+ failure_count=4,
+ skipped_count=0,
+ suppressed_count=0)
+
+
+if __name__ == '__main__':
+ gtest_test_utils.Main()
diff --git a/googletest/test/googletest-failfast-unittest_.cc b/googletest/test/googletest-failfast-unittest_.cc
new file mode 100644
index 0000000..0b2c951
--- /dev/null
+++ b/googletest/test/googletest-failfast-unittest_.cc
@@ -0,0 +1,167 @@
+// Copyright 2005, Google Inc.
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+// Unit test for Google Test test filters.
+//
+// A user can specify which test(s) in a Google Test program to run via
+// either the GTEST_FILTER environment variable or the --gtest_filter
+// flag. This is used for testing such functionality.
+//
+// The program will be invoked from a Python unit test. Don't run it
+// directly.
+
+#include "gtest/gtest.h"
+
+namespace {
+
+// Test HasFixtureTest.
+
+class HasFixtureTest : public testing::Test {};
+
+TEST_F(HasFixtureTest, Test0) {}
+
+TEST_F(HasFixtureTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST_F(HasFixtureTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasSimpleTest.
+
+TEST(HasSimpleTest, Test0) {}
+
+TEST(HasSimpleTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasSimpleTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasDisabledTest.
+
+TEST(HasDisabledTest, Test0) {}
+
+TEST(HasDisabledTest, DISABLED_Test1) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasDisabledTest, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasDeathTest
+
+TEST(HasDeathTest, Test0) { EXPECT_DEATH_IF_SUPPORTED(exit(1), ".*"); }
+
+TEST(HasDeathTest, Test1) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test2) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test3) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+TEST(HasDeathTest, Test4) {
+ EXPECT_DEATH_IF_SUPPORTED(FAIL() << "Expected failure.", ".*");
+}
+
+// Test DISABLED_HasDisabledSuite
+
+TEST(DISABLED_HasDisabledSuite, Test0) {}
+
+TEST(DISABLED_HasDisabledSuite, Test1) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test2) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test3) { FAIL() << "Expected failure."; }
+
+TEST(DISABLED_HasDisabledSuite, Test4) { FAIL() << "Expected failure."; }
+
+// Test HasParametersTest
+
+class HasParametersTest : public testing::TestWithParam<int> {};
+
+TEST_P(HasParametersTest, Test1) { FAIL() << "Expected failure."; }
+
+TEST_P(HasParametersTest, Test2) { FAIL() << "Expected failure."; }
+
+INSTANTIATE_TEST_SUITE_P(HasParametersSuite, HasParametersTest,
+ testing::Values(1, 2));
+
+class MyTestListener : public ::testing::EmptyTestEventListener {
+ void OnTestSuiteStart(const ::testing::TestSuite& test_suite) override {
+ printf("We are in OnTestSuiteStart of %s.\n", test_suite.name());
+ }
+
+ void OnTestStart(const ::testing::TestInfo& test_info) override {
+ printf("We are in OnTestStart of %s.%s.\n", test_info.test_suite_name(),
+ test_info.name());
+ }
+
+ void OnTestPartResult(
+ const ::testing::TestPartResult& test_part_result) override {
+ printf("We are in OnTestPartResult %s:%d.\n", test_part_result.file_name(),
+ test_part_result.line_number());
+ }
+
+ void OnTestEnd(const ::testing::TestInfo& test_info) override {
+ printf("We are in OnTestEnd of %s.%s.\n", test_info.test_suite_name(),
+ test_info.name());
+ }
+
+ void OnTestSuiteEnd(const ::testing::TestSuite& test_suite) override {
+ printf("We are in OnTestSuiteEnd of %s.\n", test_suite.name());
+ }
+};
+
+TEST(HasSkipTest, Test0) { SUCCEED() << "Expected success."; }
+
+TEST(HasSkipTest, Test1) { GTEST_SKIP() << "Expected skip."; }
+
+TEST(HasSkipTest, Test2) { FAIL() << "Expected failure."; }
+
+TEST(HasSkipTest, Test3) { FAIL() << "Expected failure."; }
+
+TEST(HasSkipTest, Test4) { FAIL() << "Expected failure."; }
+
+} // namespace
+
+int main(int argc, char **argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+ ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());
+ return RUN_ALL_TESTS();
+}
diff --git a/googletest/test/googletest-json-output-unittest.py b/googletest/test/googletest-json-output-unittest.py
index 15861f7..e799d47 100644
--- a/googletest/test/googletest-json-output-unittest.py
+++ b/googletest/test/googletest-json-output-unittest.py
@@ -58,9 +58,9 @@
EXPECTED_NON_EMPTY = {
u'tests':
- 24,
+ 26,
u'failures':
- 4,
+ 5,
u'disabled':
2,
u'errors':
@@ -158,9 +158,9 @@
u'name':
u'SkippedTest',
u'tests':
- 1,
+ 3,
u'failures':
- 0,
+ 1,
u'disabled':
0,
u'errors':
@@ -176,6 +176,32 @@
u'time': u'*',
u'timestamp': u'*',
u'classname': u'SkippedTest'
+ }, {
+ u'name': u'SkippedWithMessage',
+ u'status': u'RUN',
+ u'result': u'SKIPPED',
+ u'time': u'*',
+ u'timestamp': u'*',
+ u'classname': u'SkippedTest'
+ }, {
+ u'name':
+ u'SkippedAfterFailure',
+ u'status':
+ u'RUN',
+ u'result':
+ u'COMPLETED',
+ u'time':
+ u'*',
+ u'timestamp':
+ u'*',
+ u'classname':
+ u'SkippedTest',
+ u'failures': [{
+ u'failure': u'gtest_xml_output_unittest_.cc:*\n'
+ u'Expected equality of these values:\n'
+ u' 1\n 2' + STACK_TRACE_TEMPLATE,
+ u'type': u''
+ }]
}]
}, {
u'name':
diff --git a/googletest/test/googletest-output-test_.cc b/googletest/test/googletest-output-test_.cc
index 76af5bc..b32b8f3 100644
--- a/googletest/test/googletest-output-test_.cc
+++ b/googletest/test/googletest-output-test_.cc
@@ -476,63 +476,6 @@
GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc";
}
-#if GTEST_IS_THREADSAFE
-
-// A unary function that may die.
-void DieIf(bool should_die) {
- GTEST_CHECK_(!should_die) << " - death inside DieIf().";
-}
-
-// Tests running death tests in a multi-threaded context.
-
-// Used for coordination between the main and the spawn thread.
-struct SpawnThreadNotifications {
- SpawnThreadNotifications() {}
-
- Notification spawn_thread_started;
- Notification spawn_thread_ok_to_terminate;
-
- private:
- GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
-};
-
-// The function to be executed in the thread spawn by the
-// MultipleThreads test (below).
-static void ThreadRoutine(SpawnThreadNotifications* notifications) {
- // Signals the main thread that this thread has started.
- notifications->spawn_thread_started.Notify();
-
- // Waits for permission to finish from the main thread.
- notifications->spawn_thread_ok_to_terminate.WaitForNotification();
-}
-
-// This is a death-test test, but it's not named with a DeathTest
-// suffix. It starts threads which might interfere with later
-// death tests, so it must run after all other death tests.
-class DeathTestAndMultiThreadsTest : public testing::Test {
- protected:
- // Starts a thread and waits for it to begin.
- void SetUp() override {
- thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
- &ThreadRoutine, ¬ifications_, nullptr));
- notifications_.spawn_thread_started.WaitForNotification();
- }
- // Tells the thread to finish, and reaps it.
- // Depending on the version of the thread library in use,
- // a manager thread might still be left running that will interfere
- // with later death tests. This is unfortunate, but this class
- // cleans up after itself as best it can.
- void TearDown() override {
- notifications_.spawn_thread_ok_to_terminate.Notify();
- }
-
- private:
- SpawnThreadNotifications notifications_;
- std::unique_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
-};
-
-#endif // GTEST_IS_THREADSAFE
-
// The MixedUpTestSuiteTest test case verifies that Google Test will fail a
// test if it uses a different fixture class than what other tests in
// the same test case use. It deliberately contains two fixture
diff --git a/googletest/test/googletest-param-test-test.cc b/googletest/test/googletest-param-test-test.cc
index 6ba8965..c852220 100644
--- a/googletest/test/googletest-param-test-test.cc
+++ b/googletest/test/googletest-param-test-test.cc
@@ -490,16 +490,17 @@
class NonDefaultConstructAssignString {
public:
NonDefaultConstructAssignString(const std::string& s) : str_(s) {}
+ NonDefaultConstructAssignString() = delete;
+ NonDefaultConstructAssignString(const NonDefaultConstructAssignString&) =
+ default;
+ NonDefaultConstructAssignString& operator=(
+ const NonDefaultConstructAssignString&) = delete;
+ ~NonDefaultConstructAssignString() = default;
const std::string& str() const { return str_; }
private:
std::string str_;
-
- // Not default constructible
- NonDefaultConstructAssignString();
- // Not assignable
- void operator=(const NonDefaultConstructAssignString&);
};
TEST(CombineTest, NonDefaultConstructAssign) {
diff --git a/googletest/test/googletest-port-test.cc b/googletest/test/googletest-port-test.cc
index 60d637c..44b99ce 100644
--- a/googletest/test/googletest-port-test.cc
+++ b/googletest/test/googletest-port-test.cc
@@ -90,10 +90,10 @@
class Base {
public:
- // Copy constructor and assignment operator do exactly what we need, so we
- // use them.
Base() : member_(0) {}
explicit Base(int n) : member_(n) {}
+ Base(const Base&) = default;
+ Base& operator=(const Base&) = default;
virtual ~Base() {}
int member() { return member_; }
@@ -1180,8 +1180,6 @@
return DestructorCall::List().size() - 1;
}
const size_t index_;
-
- GTEST_DISALLOW_ASSIGN_(DestructorTracker);
};
typedef ThreadLocal<DestructorTracker>* ThreadParam;
diff --git a/googletest/test/googletest-printers-test.cc b/googletest/test/googletest-printers-test.cc
index 1324dd6..05c4183 100644
--- a/googletest/test/googletest-printers-test.cc
+++ b/googletest/test/googletest-printers-test.cc
@@ -1539,14 +1539,14 @@
#if GTEST_HAS_RTTI
return internal::GetTypeName<T>();
#else
- return "the element type";
+ return "<unknown_type>";
#endif // GTEST_HAS_RTTI
}
};
TEST_F(PrintAnyTest, Empty) {
internal::Any any;
- EXPECT_EQ("'any' type with no value", PrintToString(any));
+ EXPECT_EQ("no value", PrintToString(any));
}
TEST_F(PrintAnyTest, NonEmpty) {
@@ -1555,11 +1555,10 @@
const std::string val2 = "content";
any = val1;
- EXPECT_EQ("'any' type with value of type " + ExpectedTypeName<int>(),
- PrintToString(any));
+ EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
any = val2;
- EXPECT_EQ("'any' type with value of type " + ExpectedTypeName<std::string>(),
+ EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
PrintToString(any));
}
#endif // GTEST_INTERNAL_HAS_ANY
@@ -1582,12 +1581,12 @@
TEST(PrintOneofTest, Basic) {
using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
- EXPECT_EQ("('int(0)' with value 7)", PrintToString(Type(7)));
- EXPECT_EQ("('StreamableInGlobal(1)' with value StreamableInGlobal)",
+ EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
+ EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
PrintToString(Type(StreamableInGlobal{})));
EXPECT_EQ(
- "('testing::gtest_printers_test::NonPrintable(2)' with value 1-byte object "
- "<11>)",
+ "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
+ "1-byte object <11>)",
PrintToString(Type(NonPrintable{})));
}
#endif // GTEST_INTERNAL_HAS_VARIANT
diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc
index 7d2d8cc..25a8afb 100644
--- a/googletest/test/gtest-unittest-api_test.cc
+++ b/googletest/test/gtest-unittest-api_test.cc
@@ -55,8 +55,8 @@
// name. The caller is responsible for deleting the array.
static TestSuite const** GetSortedTestSuites() {
UnitTest& unit_test = *UnitTest::GetInstance();
- auto const** const test_suites =
- new const TestSuite*[unit_test.total_test_suite_count()];
+ auto const** const test_suites = new const TestSuite*[static_cast<size_t>(
+ unit_test.total_test_suite_count())];
for (int i = 0; i < unit_test.total_test_suite_count(); ++i)
test_suites[i] = unit_test.GetTestSuite(i);
@@ -83,8 +83,8 @@
// sorted by the test name. The caller is responsible for deleting the
// array.
static TestInfo const** GetSortedTests(const TestSuite* test_suite) {
- TestInfo const** const tests =
- new const TestInfo*[test_suite->total_test_count()];
+ TestInfo const** const tests = new const TestInfo*[static_cast<size_t>(
+ test_suite->total_test_count())];
for (int i = 0; i < test_suite->total_test_count(); ++i)
tests[i] = test_suite->GetTestInfo(i);
diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py
index 582d24c..609615e 100755
--- a/googletest/test/gtest_help_test.py
+++ b/googletest/test/gtest_help_test.py
@@ -68,6 +68,7 @@
FLAG_PREFIX + r'shuffle.*' +
FLAG_PREFIX + r'random_seed=.*' +
FLAG_PREFIX + r'color=.*' +
+ FLAG_PREFIX + r'brief.*' +
FLAG_PREFIX + r'print_time.*' +
FLAG_PREFIX + r'output=.*' +
FLAG_PREFIX + r'break_on_failure.*' +
diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc
index 06c5e67..a6d44ab 100644
--- a/googletest/test/gtest_unittest.cc
+++ b/googletest/test/gtest_unittest.cc
@@ -37,21 +37,22 @@
// code once "gtest.h" has been #included.
// Do not move it after other gtest #includes.
TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {
- bool dummy = testing::GTEST_FLAG(also_run_disabled_tests)
- || testing::GTEST_FLAG(break_on_failure)
- || testing::GTEST_FLAG(catch_exceptions)
- || testing::GTEST_FLAG(color) != "unknown"
- || testing::GTEST_FLAG(filter) != "unknown"
- || testing::GTEST_FLAG(list_tests)
- || testing::GTEST_FLAG(output) != "unknown"
- || testing::GTEST_FLAG(print_time)
- || testing::GTEST_FLAG(random_seed)
- || testing::GTEST_FLAG(repeat) > 0
- || testing::GTEST_FLAG(show_internal_stack_frames)
- || testing::GTEST_FLAG(shuffle)
- || testing::GTEST_FLAG(stack_trace_depth) > 0
- || testing::GTEST_FLAG(stream_result_to) != "unknown"
- || testing::GTEST_FLAG(throw_on_failure);
+ bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) ||
+ testing::GTEST_FLAG(break_on_failure) ||
+ testing::GTEST_FLAG(catch_exceptions) ||
+ testing::GTEST_FLAG(color) != "unknown" ||
+ testing::GTEST_FLAG(fail_fast) ||
+ testing::GTEST_FLAG(filter) != "unknown" ||
+ testing::GTEST_FLAG(list_tests) ||
+ testing::GTEST_FLAG(output) != "unknown" ||
+ testing::GTEST_FLAG(brief) || testing::GTEST_FLAG(print_time) ||
+ testing::GTEST_FLAG(random_seed) ||
+ testing::GTEST_FLAG(repeat) > 0 ||
+ testing::GTEST_FLAG(show_internal_stack_frames) ||
+ testing::GTEST_FLAG(shuffle) ||
+ testing::GTEST_FLAG(stack_trace_depth) > 0 ||
+ testing::GTEST_FLAG(stream_result_to) != "unknown" ||
+ testing::GTEST_FLAG(throw_on_failure);
EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused.
}
@@ -202,9 +203,11 @@
using testing::GTEST_FLAG(catch_exceptions);
using testing::GTEST_FLAG(color);
using testing::GTEST_FLAG(death_test_use_fork);
+using testing::GTEST_FLAG(fail_fast);
using testing::GTEST_FLAG(filter);
using testing::GTEST_FLAG(list_tests);
using testing::GTEST_FLAG(output);
+using testing::GTEST_FLAG(brief);
using testing::GTEST_FLAG(print_time);
using testing::GTEST_FLAG(random_seed);
using testing::GTEST_FLAG(repeat);
@@ -1598,9 +1601,11 @@
GTEST_FLAG(catch_exceptions) = false;
GTEST_FLAG(death_test_use_fork) = false;
GTEST_FLAG(color) = "auto";
+ GTEST_FLAG(fail_fast) = false;
GTEST_FLAG(filter) = "";
GTEST_FLAG(list_tests) = false;
GTEST_FLAG(output) = "";
+ GTEST_FLAG(brief) = false;
GTEST_FLAG(print_time) = true;
GTEST_FLAG(random_seed) = 0;
GTEST_FLAG(repeat) = 1;
@@ -1625,9 +1630,11 @@
EXPECT_FALSE(GTEST_FLAG(catch_exceptions));
EXPECT_STREQ("auto", GTEST_FLAG(color).c_str());
EXPECT_FALSE(GTEST_FLAG(death_test_use_fork));
+ EXPECT_FALSE(GTEST_FLAG(fail_fast));
EXPECT_STREQ("", GTEST_FLAG(filter).c_str());
EXPECT_FALSE(GTEST_FLAG(list_tests));
EXPECT_STREQ("", GTEST_FLAG(output).c_str());
+ EXPECT_FALSE(GTEST_FLAG(brief));
EXPECT_TRUE(GTEST_FLAG(print_time));
EXPECT_EQ(0, GTEST_FLAG(random_seed));
EXPECT_EQ(1, GTEST_FLAG(repeat));
@@ -1641,9 +1648,11 @@
GTEST_FLAG(catch_exceptions) = true;
GTEST_FLAG(color) = "no";
GTEST_FLAG(death_test_use_fork) = true;
+ GTEST_FLAG(fail_fast) = true;
GTEST_FLAG(filter) = "abc";
GTEST_FLAG(list_tests) = true;
GTEST_FLAG(output) = "xml:foo.xml";
+ GTEST_FLAG(brief) = true;
GTEST_FLAG(print_time) = false;
GTEST_FLAG(random_seed) = 1;
GTEST_FLAG(repeat) = 100;
@@ -5495,20 +5504,23 @@
// The Flags struct stores a copy of all Google Test flags.
struct Flags {
// Constructs a Flags struct where each flag has its default value.
- Flags() : also_run_disabled_tests(false),
- break_on_failure(false),
- catch_exceptions(false),
- death_test_use_fork(false),
- filter(""),
- list_tests(false),
- output(""),
- print_time(true),
- random_seed(0),
- repeat(1),
- shuffle(false),
- stack_trace_depth(kMaxStackTraceDepth),
- stream_result_to(""),
- throw_on_failure(false) {}
+ Flags()
+ : also_run_disabled_tests(false),
+ break_on_failure(false),
+ catch_exceptions(false),
+ death_test_use_fork(false),
+ fail_fast(false),
+ filter(""),
+ list_tests(false),
+ output(""),
+ brief(false),
+ print_time(true),
+ random_seed(0),
+ repeat(1),
+ shuffle(false),
+ stack_trace_depth(kMaxStackTraceDepth),
+ stream_result_to(""),
+ throw_on_failure(false) {}
// Factory methods.
@@ -5544,6 +5556,14 @@
return flags;
}
+ // Creates a Flags struct where the gtest_fail_fast flag has
+ // the given value.
+ static Flags FailFast(bool fail_fast) {
+ Flags flags;
+ flags.fail_fast = fail_fast;
+ return flags;
+ }
+
// Creates a Flags struct where the gtest_filter flag has the given
// value.
static Flags Filter(const char* filter) {
@@ -5568,6 +5588,14 @@
return flags;
}
+ // Creates a Flags struct where the gtest_brief flag has the given
+ // value.
+ static Flags Brief(bool brief) {
+ Flags flags;
+ flags.brief = brief;
+ return flags;
+ }
+
// Creates a Flags struct where the gtest_print_time flag has the given
// value.
static Flags PrintTime(bool print_time) {
@@ -5629,9 +5657,11 @@
bool break_on_failure;
bool catch_exceptions;
bool death_test_use_fork;
+ bool fail_fast;
const char* filter;
bool list_tests;
const char* output;
+ bool brief;
bool print_time;
int32_t random_seed;
int32_t repeat;
@@ -5650,9 +5680,11 @@
GTEST_FLAG(break_on_failure) = false;
GTEST_FLAG(catch_exceptions) = false;
GTEST_FLAG(death_test_use_fork) = false;
+ GTEST_FLAG(fail_fast) = false;
GTEST_FLAG(filter) = "";
GTEST_FLAG(list_tests) = false;
GTEST_FLAG(output) = "";
+ GTEST_FLAG(brief) = false;
GTEST_FLAG(print_time) = true;
GTEST_FLAG(random_seed) = 0;
GTEST_FLAG(repeat) = 1;
@@ -5680,9 +5712,11 @@
EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure));
EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions));
EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork));
+ EXPECT_EQ(expected.fail_fast, GTEST_FLAG(fail_fast));
EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str());
EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests));
EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str());
+ EXPECT_EQ(expected.brief, GTEST_FLAG(brief));
EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time));
EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed));
EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat));
@@ -5766,6 +5800,15 @@
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
}
+// Tests parsing --gtest_fail_fast.
+TEST_F(ParseFlagsTest, FailFast) {
+ const char* argv[] = {"foo.exe", "--gtest_fail_fast", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);
+}
+
// Tests parsing a bad --gtest_filter flag.
TEST_F(ParseFlagsTest, FilterBad) {
const char* argv[] = {"foo.exe", "--gtest_filter", nullptr};
@@ -5965,6 +6008,33 @@
Flags::Output("xml:directory/path/"), false);
}
+// Tests having a --gtest_brief flag
+TEST_F(ParseFlagsTest, BriefFlag) {
+ const char* argv[] = {"foo.exe", "--gtest_brief", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
+}
+
+// Tests having a --gtest_brief flag with a "true" value
+TEST_F(ParseFlagsTest, BriefFlagTrue) {
+ const char* argv[] = {"foo.exe", "--gtest_brief=1", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);
+}
+
+// Tests having a --gtest_brief flag with a "false" value
+TEST_F(ParseFlagsTest, BriefFlagFalse) {
+ const char* argv[] = {"foo.exe", "--gtest_brief=0", nullptr};
+
+ const char* argv2[] = {"foo.exe", nullptr};
+
+ GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);
+}
+
// Tests having a --gtest_print_time flag
TEST_F(ParseFlagsTest, PrintTimeFlag) {
const char* argv[] = {"foo.exe", "--gtest_print_time", nullptr};
@@ -7077,7 +7147,7 @@
// Tests that IsAProtocolMessage<T>::value is a compile-time constant.
TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) {
- GTEST_COMPILE_ASSERT_(IsAProtocolMessage<::proto2::Message>::value,
+ GTEST_COMPILE_ASSERT_(IsAProtocolMessage<::proto2::MessageLite>::value,
const_true);
GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false);
}
@@ -7085,7 +7155,7 @@
// Tests that IsAProtocolMessage<T>::value is true when T is
// proto2::Message or a sub-class of it.
TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) {
- EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value);
+ EXPECT_TRUE(IsAProtocolMessage<::proto2::MessageLite>::value);
}
// Tests that IsAProtocolMessage<T>::value is false when T is neither
diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py
index e093f6f..ac66feb 100755
--- a/googletest/test/gtest_xml_outfiles_test.py
+++ b/googletest/test/gtest_xml_outfiles_test.py
@@ -42,7 +42,7 @@
EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
- <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="PropertyOne" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
<testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyOne">
<properties>
<property name="SetUpProp" value="1"/>
@@ -56,7 +56,7 @@
EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests">
- <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="PropertyTwo" tests="1" failures="0" skipped="0" disabled="0" errors="0" time="*" timestamp="*">
<testcase name="TestSomeProperties" status="run" result="completed" time="*" timestamp="*" classname="PropertyTwo">
<properties>
<property name="SetUpProp" value="2"/>
diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py
index 63b1af0..de8b8c7 100755
--- a/googletest/test/gtest_xml_output_unittest.py
+++ b/googletest/test/gtest_xml_output_unittest.py
@@ -65,11 +65,11 @@
sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)
EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?>
-<testsuites tests="24" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+<testsuites tests="26" failures="5" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
+ <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
- <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="FailedTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="FailedTest">
<failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Expected equality of these values:
@@ -77,7 +77,7 @@
2%(stack)s]]></failure>
</testcase>
</testsuite>
- <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*" timestamp="*">
+ <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest"/>
<testcase name="Fails" status="run" result="completed" time="*" timestamp="*" classname="MixedResultTest">
<failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
@@ -91,27 +91,43 @@
</testcase>
<testcase name="DISABLED_test" status="notrun" result="suppressed" time="*" timestamp="*" classname="MixedResultTest"/>
</testsuite>
- <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="OutputsCData" status="run" result="completed" time="*" timestamp="*" classname="XmlQuotingTest">
<failure message="gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure>
</testcase>
</testsuite>
- <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="InvalidCharactersInMessage" status="run" result="completed" time="*" timestamp="*" classname="InvalidCharactersTest">
<failure message="gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []%(stack)s]]></failure>
</testcase>
</testsuite>
- <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*" timestamp="*">
+ <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="DISABLED_test_not_run" status="notrun" result="suppressed" time="*" timestamp="*" classname="DisabledTest"/>
</testsuite>
- <testsuite name="SkippedTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest"/>
+ <testsuite name="SkippedTest" tests="3" failures="1" disabled="0" skipped="2" errors="0" time="*" timestamp="*">
+ <testcase name="Skipped" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
+ <skipped message="gtest_xml_output_unittest_.cc:*
"><![CDATA[gtest_xml_output_unittest_.cc:*
+%(stack)s]]></skipped>
+ </testcase>
+ <testcase name="SkippedWithMessage" status="run" result="skipped" time="*" timestamp="*" classname="SkippedTest">
+ <skipped message="gtest_xml_output_unittest_.cc:*
It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:*
+It is good practice to tell why you skip a test.%(stack)s]]></skipped>
+ </testcase>
+ <testcase name="SkippedAfterFailure" status="run" result="completed" time="*" timestamp="*" classname="SkippedTest">
+ <failure message="gtest_xml_output_unittest_.cc:*
Expected equality of these values:
 1
 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:*
+Expected equality of these values:
+ 1
+ 2%(stack)s]]></failure>
+ <skipped message="gtest_xml_output_unittest_.cc:*
It is good practice to tell why you skip a test."><![CDATA[gtest_xml_output_unittest_.cc:*
+It is good practice to tell why you skip a test.%(stack)s]]></skipped>
+ </testcase>
+
</testsuite>
- <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
+ <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
<testcase name="OneProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
<property name="key_1" value="1"/>
@@ -135,7 +151,7 @@
</properties>
</testcase>
</testsuite>
- <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="RecordProperty" status="run" result="completed" time="*" timestamp="*" classname="NoFixtureTest">
<properties>
<property name="key" value="1"/>
@@ -152,22 +168,22 @@
</properties>
</testcase>
</testsuite>
- <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="HasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
<testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
- <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/0" />
</testsuite>
- <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="TypedTest/1" />
</testsuite>
- <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="Single/TypeParameterizedTestSuite/0" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/0" />
</testsuite>
- <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="Single/TypeParameterizedTestSuite/1" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="HasTypeParamAttribute" type_param="*" status="run" result="completed" time="*" timestamp="*" classname="Single/TypeParameterizedTestSuite/1" />
</testsuite>
</testsuites>""" % {
@@ -177,7 +193,7 @@
EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="1" failures="0" disabled="0" errors="0" time="*"
timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0"
+ <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0"
errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
@@ -185,18 +201,18 @@
EXPECTED_SHARDED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42">
- <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
+ <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
<testcase name="Succeeds" status="run" result="completed" time="*" timestamp="*" classname="SuccessfulTest"/>
</testsuite>
- <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
- <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
+ <testsuite name="PropertyRecordingTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*" SetUpTestSuite="yes" TearDownTestSuite="aye">
+ <testcase name="IntValuedProperty" status="run" result="completed" time="*" timestamp="*" classname="PropertyRecordingTest">
<properties>
- <property name="key_1" value="2"/>
+ <property name="key_int" value="1"/>
</properties>
</testcase>
</testsuite>
- <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*">
- <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
+ <testsuite name="Single/ValueParamTest" tests="1" failures="0" disabled="0" skipped="0" errors="0" time="*" timestamp="*">
+ <testcase name="HasValueParamAttribute/0" value_param="33" status="run" result="completed" time="*" timestamp="*" classname="Single/ValueParamTest" />
</testsuite>
</testsuites>"""
diff --git a/googletest/test/gtest_xml_output_unittest_.cc b/googletest/test/gtest_xml_output_unittest_.cc
index c95fd66..2b6634b 100644
--- a/googletest/test/gtest_xml_output_unittest_.cc
+++ b/googletest/test/gtest_xml_output_unittest_.cc
@@ -74,6 +74,15 @@
GTEST_SKIP();
}
+TEST_F(SkippedTest, SkippedWithMessage) {
+ GTEST_SKIP() << "It is good practice to tell why you skip a test.";
+}
+
+TEST_F(SkippedTest, SkippedAfterFailure) {
+ EXPECT_EQ(1, 2);
+ GTEST_SKIP() << "It is good practice to tell why you skip a test.";
+}
+
TEST(MixedResultTest, Succeeds) {
EXPECT_EQ(1, 1);
ASSERT_EQ(1, 1);
diff --git a/googletest/test/gtest_xml_test_utils.py b/googletest/test/gtest_xml_test_utils.py
index 9914a49..cae0bc0 100755
--- a/googletest/test/gtest_xml_test_utils.py
+++ b/googletest/test/gtest_xml_test_utils.py
@@ -105,6 +105,7 @@
'testsuite': 'name',
'testcase': 'name',
'failure': 'message',
+ 'skipped': 'message',
'property': 'name',
}
@@ -179,7 +180,7 @@
type_param = element.getAttributeNode('type_param')
if type_param and type_param.value:
type_param.value = '*'
- elif element.tagName == 'failure':
+ elif element.tagName == 'failure' or element.tagName == 'skipped':
source_line_pat = r'^.*[/\\](.*:)\d+\n'
# Replaces the source line information with a normalized form.
message = element.getAttributeNode('message')