From a9653c401e799933be77ee9dfa4aa0c378031b1d Mon Sep 17 00:00:00 2001 From: Scott Graham Date: Wed, 2 May 2018 11:14:39 -0700 Subject: Fix gmock not building when -fno-rtti Fixes issue #1554. This is internal cl/195020996. --- googlemock/include/gmock/gmock-matchers.h | 8 ++++---- googlemock/test/gmock-matchers_test.cc | 6 ++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index e0a7864..c94f582 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -2371,6 +2371,7 @@ class PointeeMatcher { GTEST_DISALLOW_ASSIGN_(PointeeMatcher); }; +#if GTEST_HAS_RTTI // Implements the WhenDynamicCastTo(m) matcher that matches a pointer or // reference that matches inner_matcher when dynamic_cast is applied. // The result of dynamic_cast is forwarded to the inner matcher. @@ -2397,11 +2398,7 @@ class WhenDynamicCastToMatcherBase { const Matcher matcher_; static std::string GetToName() { -#if GTEST_HAS_RTTI return GetTypeName(); -#else // GTEST_HAS_RTTI - return "the target type"; -#endif // GTEST_HAS_RTTI } private: @@ -2447,6 +2444,7 @@ class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase { return MatchPrintAndExplain(*to, this->matcher_, listener); } }; +#endif // GTEST_HAS_RTTI // Implements the Field() matcher for matching a field (i.e. member // variable) of an object. @@ -4441,6 +4439,7 @@ inline internal::PointeeMatcher Pointee( return internal::PointeeMatcher(inner_matcher); } +#if GTEST_HAS_RTTI // Creates a matcher that matches a pointer or reference that matches // inner_matcher when dynamic_cast is applied. // The result of dynamic_cast is forwarded to the inner matcher. @@ -4453,6 +4452,7 @@ WhenDynamicCastTo(const Matcher& inner_matcher) { return MakePolymorphicMatcher( internal::WhenDynamicCastToMatcher(inner_matcher)); } +#endif // GTEST_HAS_RTTI // Creates a matcher that matches an object whose given field matches // 'matcher'. For example, diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index b422465..87b2ad5 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -3704,6 +3704,7 @@ MATCHER_P(FieldIIs, inner_matcher, "") { return ExplainMatchResult(inner_matcher, arg.i, result_listener); } +#if GTEST_HAS_RTTI TEST(WhenDynamicCastToTest, SameType) { Derived derived; derived.i = 4; @@ -3761,12 +3762,8 @@ TEST(WhenDynamicCastToTest, AmbiguousCast) { TEST(WhenDynamicCastToTest, Describe) { Matcher matcher = WhenDynamicCastTo(Pointee(_)); -#if GTEST_HAS_RTTI const std::string prefix = "when dynamic_cast to " + internal::GetTypeName() + ", "; -#else // GTEST_HAS_RTTI - const std::string prefix = "when dynamic_cast, "; -#endif // GTEST_HAS_RTTI EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher)); EXPECT_EQ(prefix + "does not point to a value that is anything", DescribeNegation(matcher)); @@ -3799,6 +3796,7 @@ TEST(WhenDynamicCastToTest, BadReference) { Base& as_base_ref = derived; EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo(_))); } +#endif // GTEST_HAS_RTTI // Minimal const-propagating pointer. template -- cgit v0.12 From b8fa4d275441acae8d4e84f373940869436b1de1 Mon Sep 17 00:00:00 2001 From: James Dennett Date: Thu, 10 May 2018 22:33:29 -0700 Subject: Add unit test for CanonicalizeForStdLibVersioning. --- googletest/test/gtest_unittest.cc | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 58995a4..2b5a7e1 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -380,6 +380,31 @@ TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); } +// Tests CanonicalizeForStdLibVersioning. + +using ::testing::internal::CanonicalizeForStdLibVersioning; + +TEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) { + EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::_")); + EXPECT_EQ("std::__foo", CanonicalizeForStdLibVersioning("std::__foo")); + EXPECT_EQ("gtl::__1::x", CanonicalizeForStdLibVersioning("gtl::__1::x")); + EXPECT_EQ("__1::x", CanonicalizeForStdLibVersioning("__1::x")); + EXPECT_EQ("::__1::x", CanonicalizeForStdLibVersioning("::__1::x")); +} + +TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) { + EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__1::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__1::_")); + + EXPECT_EQ("std::bind", CanonicalizeForStdLibVersioning("std::__g::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__g::_")); + + EXPECT_EQ("std::bind", + CanonicalizeForStdLibVersioning("std::__google::bind")); + EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_")); +} + // Tests FormatTimeInMillisAsSeconds(). TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { -- cgit v0.12 From fc66ae45fc7f935eef23af27347761ba4050ad6e Mon Sep 17 00:00:00 2001 From: James Dennett Date: Thu, 10 May 2018 22:36:50 -0700 Subject: Update generated code. --- googletest/include/gtest/internal/gtest-type-util.h | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index e46f7cf..d0d83f5 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -56,6 +56,22 @@ namespace testing { namespace internal { + +// Canonicalizes a given name with respect to the Standard C++ Library. +// This handles removing the inline namespace within `std` that is +// used by various standard libraries (e.g., `std::__1`). Names outside +// of namespace std are returned unmodified. +inline std::string CanonicalizeForStdLibVersioning(std::string s) { + static constexpr char prefix[] = "std::__"; + if (s.compare(0, strlen(prefix), prefix) == 0) { + auto end = s.find("::", strlen(prefix)); + if (end != s.npos) { + // Erase the `::__` plus whatever was between that and the next `::`. + s.erase(strlen("std"), strlen("::__") + end - strlen(prefix)); + } + } + return s; +} // GetTypeName() returns a human-readable name of type T. // NB: This function is also used in Google Mock, so don't move it inside of @@ -73,9 +89,9 @@ std::string GetTypeName() { using abi::__cxa_demangle; # endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, 0, 0, &status); - const std::string name_str(status == 0 ? readable_name : name); + std::string name_str(status == 0 ? readable_name : name); free(readable_name); - return name_str; + return CanonicalizeForStdLibVersioning(std::move(name_str)); # else return name; # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC -- cgit v0.12 From 54e331b88bca8e9ab9de55153a3e6d295299aad0 Mon Sep 17 00:00:00 2001 From: James Dennett Date: Thu, 10 May 2018 22:39:19 -0700 Subject: Add support for versioned standard libraries. This canonicalizes demangled names by omitting a nested inline namespace within namespace std if the name of the nested namespace begins with a double underscore. This improves compatibility with libc++. --- .../include/gtest/internal/gtest-type-util.h.pump | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index 251fdf0..6122862 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -54,6 +54,22 @@ $var n = 50 $$ Maximum length of type lists we want to support. namespace testing { namespace internal { + +// Canonicalizes a given name with respect to the Standard C++ Library. +// This handles removing the inline namespace within `std` that is +// used by various standard libraries (e.g., `std::__1`). Names outside +// of namespace std are returned unmodified. +inline std::string CanonicalizeForStdLibVersioning(std::string s) { + static constexpr char prefix[] = "std::__"; + if (s.compare(0, strlen(prefix), prefix) == 0) { + auto end = s.find("::", strlen(prefix)); + if (end != s.npos) { + // Erase the `::__` plus whatever was between that and the next `::`. + s.erase(strlen("std"), strlen("::__") + end - strlen(prefix)); + } + } + return s; +} // GetTypeName() returns a human-readable name of type T. // NB: This function is also used in Google Mock, so don't move it inside of @@ -71,9 +87,9 @@ std::string GetTypeName() { using abi::__cxa_demangle; # endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, 0, 0, &status); - const std::string name_str(status == 0 ? readable_name : name); + std::string name_str(status == 0 ? readable_name : name); free(readable_name); - return name_str; + return CanonicalizeForStdLibVersioning(std::move(name_str)); # else return name; # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC -- cgit v0.12 From f91bf75cf97f70cfc3814bd12cc7d505c62269e2 Mon Sep 17 00:00:00 2001 From: Fabrice de Gans-Riberi Date: Fri, 11 May 2018 10:38:48 -0700 Subject: Remove unused variable in Fuchsia. --- googletest/src/gtest-death-test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 792fe46..4b721a4 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -123,7 +123,7 @@ namespace internal { // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. -# if !GTEST_OS_WINDOWS +# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA static bool g_in_fast_death_test_child = false; # endif -- cgit v0.12 From ec2c911b3370f6536b90bf8de7be742ac191c25f Mon Sep 17 00:00:00 2001 From: James Dennett Date: Mon, 21 May 2018 10:59:24 -0700 Subject: Downgrade to C++98 code. Some users are not ready for C++11 yet. --- googletest/include/gtest/internal/gtest-type-util.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index d0d83f5..d778131 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -62,12 +62,12 @@ namespace internal { // used by various standard libraries (e.g., `std::__1`). Names outside // of namespace std are returned unmodified. inline std::string CanonicalizeForStdLibVersioning(std::string s) { - static constexpr char prefix[] = "std::__"; + static const char prefix[] = "std::__"; if (s.compare(0, strlen(prefix), prefix) == 0) { - auto end = s.find("::", strlen(prefix)); + std::string::size_type end = s.find("::", strlen(prefix)); if (end != s.npos) { - // Erase the `::__` plus whatever was between that and the next `::`. - s.erase(strlen("std"), strlen("::__") + end - strlen(prefix)); + // Erase everything between the initial `std` and the second `::`. + s.erase(strlen("std"), end - strlen("std")); } } return s; @@ -89,9 +89,9 @@ std::string GetTypeName() { using abi::__cxa_demangle; # endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, 0, 0, &status); - std::string name_str(status == 0 ? readable_name : name); + const std::string name_str(status == 0 ? readable_name : name); free(readable_name); - return CanonicalizeForStdLibVersioning(std::move(name_str)); + return CanonicalizeForStdLibVersioning(name_str); # else return name; # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC -- cgit v0.12 From 49ecebd1f25cdfb97462e81ada8662990e3d211d Mon Sep 17 00:00:00 2001 From: James Dennett Date: Mon, 21 May 2018 12:27:52 -0700 Subject: Downgrade to C++98. Some projects cannot handle C++11 yet. --- googletest/include/gtest/internal/gtest-type-util.h.pump | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index 6122862..eb4df2c 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -60,12 +60,12 @@ namespace internal { // used by various standard libraries (e.g., `std::__1`). Names outside // of namespace std are returned unmodified. inline std::string CanonicalizeForStdLibVersioning(std::string s) { - static constexpr char prefix[] = "std::__"; + static const char prefix[] = "std::__"; if (s.compare(0, strlen(prefix), prefix) == 0) { - auto end = s.find("::", strlen(prefix)); + std::string::size_type end = s.find("::", strlen(prefix)); if (end != s.npos) { - // Erase the `::__` plus whatever was between that and the next `::`. - s.erase(strlen("std"), strlen("::__") + end - strlen(prefix)); + // Erase everything between the initial `std` and the second `::`. + s.erase(strlen("std"), end - strlen("std")); } } return s; @@ -87,9 +87,9 @@ std::string GetTypeName() { using abi::__cxa_demangle; # endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, 0, 0, &status); - std::string name_str(status == 0 ? readable_name : name); + const std::string name_str(status == 0 ? readable_name : name); free(readable_name); - return CanonicalizeForStdLibVersioning(std::move(name_str)); + return CanonicalizeForStdLibVersioning(name_str); # else return name; # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC -- cgit v0.12 From 28c91e2cea88ee6ddc0e0dc6ca18b8e86f85d80c Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 23 May 2018 11:03:31 -0400 Subject: Formatting changes --- googlemock/test/gmock_link2_test.cc | 2 +- googlemock/test/gmock_link_test.cc | 2 +- googletest/include/gtest/gtest-death-test.h | 2 +- googletest/include/gtest/gtest-message.h | 2 +- googletest/include/gtest/gtest-param-test.h | 2 +- googletest/include/gtest/gtest-param-test.h.pump | 2 +- googletest/include/gtest/gtest-printers.h | 2 +- googletest/include/gtest/gtest.h | 2 +- googletest/include/gtest/gtest_prod.h | 2 +- googletest/include/gtest/internal/gtest-death-test-internal.h | 2 +- googletest/include/gtest/internal/gtest-internal.h | 2 +- googletest/include/gtest/internal/gtest-port-arch.h | 2 +- googletest/include/gtest/internal/gtest-port.h | 2 +- googletest/include/gtest/internal/gtest-string.h | 2 +- googletest/include/gtest/internal/gtest-type-util.h | 2 +- googletest/include/gtest/internal/gtest-type-util.h.pump | 2 +- googletest/src/gtest-all.cc | 2 +- googletest/src/gtest-death-test.cc | 2 +- googletest/src/gtest-printers.cc | 2 +- googletest/src/gtest-test-part.cc | 2 +- googletest/src/gtest.cc | 2 +- googletest/test/gtest-listener_test.cc | 2 +- googletest/test/gtest-param-test_test.h | 2 +- googletest/test/gtest-printers_test.cc | 2 +- googletest/test/gtest-unittest-api_test.cc | 2 +- googletest/test/gtest_all_test.cc | 2 +- googletest/test/gtest_help_test.py | 2 +- googletest/test/gtest_output_test.py | 2 +- googletest/test/gtest_test_utils.py | 2 +- googletest/test/gtest_unittest.cc | 2 +- 30 files changed, 30 insertions(+), 30 deletions(-) diff --git a/googlemock/test/gmock_link2_test.cc b/googlemock/test/gmock_link2_test.cc index 4c310c3..2b48395 100644 --- a/googlemock/test/gmock_link2_test.cc +++ b/googlemock/test/gmock_link2_test.cc @@ -37,4 +37,4 @@ #define LinkTest LinkTest2 -#include "test/gmock_link_test.h" +#include "test/gmock_link_test.h" diff --git a/googlemock/test/gmock_link_test.cc b/googlemock/test/gmock_link_test.cc index 61e97d1..ef041be 100644 --- a/googlemock/test/gmock_link_test.cc +++ b/googlemock/test/gmock_link_test.cc @@ -37,4 +37,4 @@ #define LinkTest LinkTest1 -#include "test/gmock_link_test.h" +#include "test/gmock_link_test.h" diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 3834292..53f11d4 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the public API for death tests. It is // #included by gtest.h so a user doesn't need to include this diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index 8bc28d2..d7266ba 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the Message class. // diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index e155763..8993c1c 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -34,7 +34,7 @@ // Authors: vladl@google.com (Vlad Losev) // // Macros and functions for implementing parameterized tests -// in Google C++ Testing Framework (Google Test) +// in Google C++ Testing and Mocking Framework (Google Test) // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // diff --git a/googletest/include/gtest/gtest-param-test.h.pump b/googletest/include/gtest/gtest-param-test.h.pump index 8726fb3..7b7243f 100644 --- a/googletest/include/gtest/gtest-param-test.h.pump +++ b/googletest/include/gtest/gtest-param-test.h.pump @@ -33,7 +33,7 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // Authors: vladl@google.com (Vlad Losev) // // Macros and functions for implementing parameterized tests -// in Google C++ Testing Framework (Google Test) +// in Google C++ Testing and Mocking Framework (Google Test) // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 36f4042..e53963b 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) -// Google Test - The Google C++ Testing Framework +// Google Test - The Google C++ Testing and Mocking Framework // // This file implements a universal value printer that can print a // value of any type T: diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index e1e9c1b..686750e 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the public API for Google Test. It should be // included by any test program that uses Google Test. diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index d9ea685..89314f4 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// Google C++ Testing Framework definitions useful in production code. +// Google C++ Testing and Mocking Framework definitions useful in production code. #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 88e7799..949c429 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -28,7 +28,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines internal utilities needed for implementing // death tests. They are subject to change without notice. diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index a0f2771..fc65b1f 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -28,7 +28,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file declares functions and macros used internally by // Google Test. They are subject to change without notice. diff --git a/googletest/include/gtest/internal/gtest-port-arch.h b/googletest/include/gtest/internal/gtest-port-arch.h index 02ff07b..f83700e 100644 --- a/googletest/include/gtest/internal/gtest-port-arch.h +++ b/googletest/include/gtest/internal/gtest-port-arch.h @@ -27,7 +27,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file defines the GTEST_OS_* macro. // It is separate from gtest-port.h so that custom/gtest-port.h can include it. diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index fafb134..437a4ed 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -813,7 +813,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; (GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ - GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD || \ + GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD || \ GTEST_OS_NETBSD || GTEST_OS_FUCHSIA) # define GTEST_HAS_DEATH_TEST 1 #endif diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 04b9e7b..71eb840 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -28,7 +28,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file declares the String class and functions used internally by // Google Test. They are subject to change without notice. They should not used diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index d778131..282b81f 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -56,7 +56,7 @@ namespace testing { namespace internal { - + // Canonicalizes a given name with respect to the Standard C++ Library. // This handles removing the inline namespace within `std` that is // used by various standard libraries (e.g., `std::__1`). Names outside diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index eb4df2c..eaa8880 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -54,7 +54,7 @@ $var n = 50 $$ Maximum length of type lists we want to support. namespace testing { namespace internal { - + // Canonicalizes a given name with respect to the Standard C++ Library. // This handles removing the inline namespace within `std` that is // used by various standard libraries (e.g., `std::__1`). Names outside diff --git a/googletest/src/gtest-all.cc b/googletest/src/gtest-all.cc index 0a9cee5..5872a2e 100644 --- a/googletest/src/gtest-all.cc +++ b/googletest/src/gtest-all.cc @@ -29,7 +29,7 @@ // // Author: mheule@google.com (Markus Heule) // -// Google C++ Testing Framework (Google Test) +// Google C++ Testing and Mocking Framework (Google Test) // // Sometimes it's desirable to build Google Test by compiling a single file. // This file serves this purpose. diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 4b721a4..b397992 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -184,7 +184,7 @@ bool KilledBySignal::operator()(int exit_status) const { # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } -# endif // !GTEST_OS_WINDOWS +# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA namespace internal { diff --git a/googletest/src/gtest-printers.cc b/googletest/src/gtest-printers.cc index d55a5e9..eeba17f 100644 --- a/googletest/src/gtest-printers.cc +++ b/googletest/src/gtest-printers.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) -// Google Test - The Google C++ Testing Framework +// Google Test - The Google C++ Testing and Mocking Framework // // This file implements a universal value printer that can print a // value of any type T: diff --git a/googletest/src/gtest-test-part.cc b/googletest/src/gtest-test-part.cc index c3926c8..4c5f2e3 100644 --- a/googletest/src/gtest-test-part.cc +++ b/googletest/src/gtest-test-part.cc @@ -29,7 +29,7 @@ // // Author: mheule@google.com (Markus Heule) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) #include "gtest/gtest-test-part.h" #include "src/gtest-internal-inl.h" diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 1b2aad2..5406392 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) #include "gtest/gtest.h" #include "gtest/internal/custom/gtest.h" diff --git a/googletest/test/gtest-listener_test.cc b/googletest/test/gtest-listener_test.cc index 9074768..639529c 100644 --- a/googletest/test/gtest-listener_test.cc +++ b/googletest/test/gtest-listener_test.cc @@ -28,7 +28,7 @@ // // Author: vladl@google.com (Vlad Losev) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This file verifies Google Test event listeners receive events at the // right times. diff --git a/googletest/test/gtest-param-test_test.h b/googletest/test/gtest-param-test_test.h index 249c089..ea1e884 100644 --- a/googletest/test/gtest-param-test_test.h +++ b/googletest/test/gtest-param-test_test.h @@ -29,7 +29,7 @@ // // Authors: vladl@google.com (Vlad Losev) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This header file provides classes and functions used internally // for testing Google Test itself. diff --git a/googletest/test/gtest-printers_test.cc b/googletest/test/gtest-printers_test.cc index 4487978..a373851 100644 --- a/googletest/test/gtest-printers_test.cc +++ b/googletest/test/gtest-printers_test.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) -// Google Test - The Google C++ Testing Framework +// Google Test - The Google C++ Testing and Mocking Framework // // This file tests the universal value printer. diff --git a/googletest/test/gtest-unittest-api_test.cc b/googletest/test/gtest-unittest-api_test.cc index b1f5168..1ebd431 100644 --- a/googletest/test/gtest-unittest-api_test.cc +++ b/googletest/test/gtest-unittest-api_test.cc @@ -28,7 +28,7 @@ // // Author: vladl@google.com (Vlad Losev) // -// The Google C++ Testing Framework (Google Test) +// The Google C++ Testing and Mocking Framework (Google Test) // // This file contains tests verifying correctness of data provided via // UnitTest's public methods. diff --git a/googletest/test/gtest_all_test.cc b/googletest/test/gtest_all_test.cc index e16ef53..e6c1b01 100644 --- a/googletest/test/gtest_all_test.cc +++ b/googletest/test/gtest_all_test.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// Tests for Google C++ Testing Framework (Google Test) +// Tests for Google C++ Testing and Mocking Framework (Google Test) // // Sometimes it's desirable to build most of Google Test's own tests // by compiling a single file. This file serves this purpose. diff --git a/googletest/test/gtest_help_test.py b/googletest/test/gtest_help_test.py index 093c838..79ffbe4 100755 --- a/googletest/test/gtest_help_test.py +++ b/googletest/test/gtest_help_test.py @@ -29,7 +29,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Tests the --help flag of Google C++ Testing Framework. +"""Tests the --help flag of Google C++ Testing and Mocking Framework. SYNOPSIS gtest_help_test.py --build_dir=BUILD/DIR diff --git a/googletest/test/gtest_output_test.py b/googletest/test/gtest_output_test.py index e431653..f83d3be 100755 --- a/googletest/test/gtest_output_test.py +++ b/googletest/test/gtest_output_test.py @@ -29,7 +29,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Tests the text output of Google C++ Testing Framework. +"""Tests the text output of Google C++ Testing and Mocking Framework. SYNOPSIS diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py index 7c48933..d7fc099 100755 --- a/googletest/test/gtest_test_utils.py +++ b/googletest/test/gtest_test_utils.py @@ -27,7 +27,7 @@ # (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 utilities for Google C++ Testing Framework.""" +"""Unit test utilities for Google C++ Testing and Mocking Framework.""" # Suppresses the 'Import not at the top of the file' lint complaint. # pylint: disable-msg=C6204 diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 662a8ab..39b6841 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -404,7 +404,7 @@ TEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) { CanonicalizeForStdLibVersioning("std::__google::bind")); EXPECT_EQ("std::_", CanonicalizeForStdLibVersioning("std::__google::_")); } - + // Tests FormatTimeInMillisAsSeconds(). TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { -- cgit v0.12 From 8977af0ecfdd49baedfd4ea020afe68d5c5e1fbb Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 23 May 2018 11:49:11 -0400 Subject: formatting changes --- googlemock/scripts/generator/README | 9 ++++----- googlemock/test/gmock_test_utils.py | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/googlemock/scripts/generator/README b/googlemock/scripts/generator/README index d6f9597..01fd463 100644 --- a/googlemock/scripts/generator/README +++ b/googlemock/scripts/generator/README @@ -1,11 +1,10 @@ The Google Mock class generator is an application that is part of cppclean. -For more information about cppclean, see the README.cppclean file or -visit http://code.google.com/p/cppclean/ +For more information about cppclean, visit http://code.google.com/p/cppclean/ -cppclean requires Python 2.3.5 or later. If you don't have Python installed -on your system, you will also need to install it. You can download Python -from: http://www.python.org/download/releases/ +The mock generator requires Python 2.3.5 or later. If you don't have Python +installed on your system, you will also need to install it. You can download +Python from: http://www.python.org/download/releases/ To use the Google Mock class generator, you need to call it on the command line passing the header file and class for which you want diff --git a/googlemock/test/gmock_test_utils.py b/googlemock/test/gmock_test_utils.py index b513000..92b1ac1 100755 --- a/googlemock/test/gmock_test_utils.py +++ b/googlemock/test/gmock_test_utils.py @@ -38,7 +38,7 @@ import sys SCRIPT_DIR = os.path.dirname(__file__) or '.' # isdir resolves symbolic links. -gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../googletest/test') +gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../../googletest/test') if os.path.isdir(gtest_tests_util_dir): GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir else: -- cgit v0.12 From 0a6edf3ca757a742f2adeb4623f625c6118e0fd7 Mon Sep 17 00:00:00 2001 From: Fabrice de Gans-Riberi Date: Wed, 30 May 2018 18:16:44 -0700 Subject: Remvoe launchpad dependency from Fuchsia. --- googletest/src/gtest-death-test.cc | 49 ++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index b397992..03adcce 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -64,7 +64,8 @@ # if GTEST_OS_FUCHSIA # include -# include +# include +# include # include # endif // GTEST_OS_FUCHSIA @@ -926,29 +927,31 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { args.AddArgument(filter_flag.c_str()); args.AddArgument(internal_flag.c_str()); - // Build the child process launcher. - zx_status_t status; - launchpad_t* lp; - status = launchpad_create(ZX_HANDLE_INVALID, args.Argv()[0], &lp); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - // Build the pipe for communication with the child. - int read_fd; - status = launchpad_add_pipe(lp, &read_fd, kFuchsiaReadPipeFd); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - set_read_fd(read_fd); - - // Set the command line arguments. - status = launchpad_load_from_file(lp, args.Argv()[0]); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - status = launchpad_set_args(lp, args.size(), args.Argv()); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - - // Clone all the things (environment, stdio, namespace, ...). - launchpad_clone(lp, LP_CLONE_ALL); - - // Launch the child process. - status = launchpad_go(lp, &child_process_, nullptr); + zx_status_t status; + zx_handle_t child_pipe_handle; + uint32_t type; + status = fdio_pipe_half(&child_pipe_handle, &type); + GTEST_DEATH_TEST_CHECK_(status >= 0); + set_read_fd(status); + + // Set the pipe handle for the child. + fdio_spawn_action_t add_handle_action = { + .action = FDIO_SPAWN_ACTION_ADD_HANDLE, + .h = { + .id = PA_HND(type, kFuchsiaReadPipeFd), + .handle = child_pipe_handle + } + }; + + // Spawn the child process. + char err_msg[255]; + status = fdio_spawn_etc(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL, + args.Argv()[0], args.Argv(), nullptr, 1, + &add_handle_action, &child_process_, err_msg); + if (status != ZX_OK) { + GTEST_LOG_(ERROR) << err_msg; + } GTEST_DEATH_TEST_CHECK_(status == ZX_OK); set_spawned(true); -- cgit v0.12 From 93e267a999a3528b21ce0e51412e889f87288f24 Mon Sep 17 00:00:00 2001 From: Fabrice de Gans-Riberi Date: Thu, 31 May 2018 11:21:01 -0700 Subject: Clean up --- googletest/src/gtest-death-test.cc | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index 03adcce..e5b4e09 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -945,13 +945,9 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { }; // Spawn the child process. - char err_msg[255]; status = fdio_spawn_etc(ZX_HANDLE_INVALID, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, 1, - &add_handle_action, &child_process_, err_msg); - if (status != ZX_OK) { - GTEST_LOG_(ERROR) << err_msg; - } + &add_handle_action, &child_process_, nullptr); GTEST_DEATH_TEST_CHECK_(status == ZX_OK); set_spawned(true); -- cgit v0.12 From f66ab00704cd47e4e63ef6d425ca14b9192aaebb Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 4 Jun 2018 10:45:56 -0400 Subject: Upstream, cl/199129756 Add printer for std::nullptr_t, addressing https://github.com/google/googletest/issues/1616 --- googletest/include/gtest/gtest-printers.h | 4 ++++ googletest/test/gtest-printers_test.cc | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index e53963b..373946b 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -636,6 +636,10 @@ inline void PrintTo(absl::string_view sp, ::std::ostream* os) { } #endif // GTEST_HAS_ABSL +#if GTEST_LANG_CXX11 +inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; } +#endif // GTEST_LANG_CXX11 + #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ // Helper function for printing a tuple. T must be instantiated with // a tuple type. diff --git a/googletest/test/gtest-printers_test.cc b/googletest/test/gtest-printers_test.cc index a373851..49b3bd4 100644 --- a/googletest/test/gtest-printers_test.cc +++ b/googletest/test/gtest-printers_test.cc @@ -1115,6 +1115,12 @@ TEST(PrintStdTupleTest, NestedTuple) { #endif // GTEST_LANG_CXX11 +#if GTEST_LANG_CXX11 +TEST(PrintNullptrT, Basic) { + EXPECT_EQ("(nullptr)", Print(nullptr)); +} +#endif // GTEST_LANG_CXX11 + // Tests printing user-defined unprintable types. // Unprintable types in the global namespace. -- cgit v0.12 From d437209cd0056fccec89b7a4736dd6a5c3dbfc7f Mon Sep 17 00:00:00 2001 From: Fabrice de Gans-Riberi Date: Thu, 7 Jun 2018 15:46:29 -0700 Subject: Fuchsia: Change fdio include path. --- googletest/src/gtest-death-test.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index e5b4e09..2f772f6 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -63,8 +63,8 @@ # endif // GTEST_OS_QNX # if GTEST_OS_FUCHSIA -# include -# include +# include +# include # include # include # endif // GTEST_OS_FUCHSIA -- cgit v0.12 From de47b0d30c1d2a2072eb1c2a2e852d6aaa028931 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 11 Jun 2018 11:26:16 -0400 Subject: Rename "Primer.md" to "primer.md" and adjust links. Part of the documentaion rationalzation --- README.md | 4 +- googlemock/README.md | 16 +- googlemock/docs/CheatSheet.md | 2 +- googletest/docs/AdvancedGuide.md | 2 +- googletest/docs/Documentation.md | 2 +- googletest/docs/FAQ.md | 4 +- googletest/docs/Primer.md | 536 --------------------------------------- googletest/docs/primer.md | 536 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 551 insertions(+), 551 deletions(-) delete mode 100644 googletest/docs/Primer.md create mode 100644 googletest/docs/primer.md diff --git a/README.md b/README.md index 157316c..d87abce 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,8 @@ mailing list for questions, discussions, and development. There is also an IRC channel on [OFTC](https://webchat.oftc.net/) (irc.oftc.net) #gtest available. Please join us! -Getting started information for **Google Test** is available in the -[Google Test Primer](googletest/docs/Primer.md) documentation. +Getting started information for **Google Test** is available in the +[Google Test Primer](googletest/docs/primer.md) documentation. **Google Mock** is an extension to Google Test for writing and using C++ mock classes. See the separate [Google Mock documentation](googlemock/README.md). diff --git a/googlemock/README.md b/googlemock/README.md index 1170cfa..ad374de 100644 --- a/googlemock/README.md +++ b/googlemock/README.md @@ -53,7 +53,7 @@ the Apache License, which is different from Google Mock's license. If you are new to the project, we suggest that you read the user documentation in the following order: - * Learn the [basics](../../master/googletest/docs/Primer.md) of + * Learn the [basics](../../master/googletest/docs/primer.md) of Google Test, if you choose to use Google Mock with it (recommended). * Read [Google Mock for Dummies](../../master/googlemock/docs/ForDummies.md). * Read the instructions below on how to build Google Mock. @@ -129,20 +129,20 @@ build Google Mock and its tests, which has further requirements: If you have CMake available, it is recommended that you follow the [build instructions][gtest_cmakebuild] -as described for Google Test. +as described for Google Test. If are using Google Mock with an existing CMake project, the section [Incorporating Into An Existing CMake Project][gtest_incorpcmake] -may be of particular interest. -To make it work for Google Mock you will need to change +may be of particular interest. +To make it work for Google Mock you will need to change target_link_libraries(example gtest_main) -to +to target_link_libraries(example gmock_main) - + This works because `gmock_main` library is compiled with Google Test. However, it does not automatically add Google Test includes. Therefore you will also have to change @@ -161,8 +161,8 @@ to "${gtest_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}/include") endif() -This will addtionally mark Google Mock includes as system, which will -silence compiler warnings when compiling your tests using clang with +This will addtionally mark Google Mock includes as system, which will +silence compiler warnings when compiling your tests using clang with `-Wpedantic -Wall -Wextra -Wconversion`. diff --git a/googlemock/docs/CheatSheet.md b/googlemock/docs/CheatSheet.md index f8bbbfe..d078b42 100644 --- a/googlemock/docs/CheatSheet.md +++ b/googlemock/docs/CheatSheet.md @@ -349,7 +349,7 @@ You can make a matcher from one or more other matchers: ## Matchers as Test Assertions ## -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/Primer.md#assertions) if the value of `expression` doesn't match matcher `m`.| +|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/primer.md#assertions) if the value of `expression` doesn't match matcher `m`.| |:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------| |`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | diff --git a/googletest/docs/AdvancedGuide.md b/googletest/docs/AdvancedGuide.md index c1a1a4a..857967a 100644 --- a/googletest/docs/AdvancedGuide.md +++ b/googletest/docs/AdvancedGuide.md @@ -1,6 +1,6 @@ -Now that you have read [Primer](Primer.md) and learned how to write tests +Now that you have read [Primer](primer.md) and learned how to write tests using Google Test, it's time to learn some new tricks. This document will show you more assertions as well as how to construct complex failure messages, propagate fatal failures, reuse and speed up your diff --git a/googletest/docs/Documentation.md b/googletest/docs/Documentation.md index 20f2503..de6aaae 100644 --- a/googletest/docs/Documentation.md +++ b/googletest/docs/Documentation.md @@ -4,7 +4,7 @@ current git version)** documentation for that specific version instead (e.g. by checking out the respective git branch/tag).** - * [Primer](Primer.md) -- start here if you are new to Google Test. + * [Primer](primer.md) -- start here if you are new to Google Test. * [Samples](Samples.md) -- learn from examples. * [AdvancedGuide](AdvancedGuide.md) -- learn more about Google Test. * [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac. diff --git a/googletest/docs/FAQ.md b/googletest/docs/FAQ.md index bd9526d..362f81b 100644 --- a/googletest/docs/FAQ.md +++ b/googletest/docs/FAQ.md @@ -1,7 +1,7 @@ If you cannot find the answer to your question here, and you have read -[Primer](Primer.md) and [AdvancedGuide](AdvancedGuide.md), send it to +[Primer](primer.md) and [AdvancedGuide](AdvancedGuide.md), send it to googletestframework@googlegroups.com. ## Why should I use Google Test instead of my favorite C++ testing framework? ## @@ -956,7 +956,7 @@ using gtest-md.vcproj instead of gtest.vcproj. ## I put my tests in a library and Google Test doesn't run them. What's happening? ## Have you read a -[warning](Primer.md#important-note-for-visual-c-users) on +[warning](primer.md#important-note-for-visual-c-users) on the Google Test Primer page? ## I want to use Google Test with Visual Studio but don't know where to start. ## diff --git a/googletest/docs/Primer.md b/googletest/docs/Primer.md deleted file mode 100644 index 5e8ee0c..0000000 --- a/googletest/docs/Primer.md +++ /dev/null @@ -1,536 +0,0 @@ - - -# Introduction: Why Google C++ Testing Framework? # - -_Google C++ Testing Framework_ helps you write better C++ tests. - -No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, -Google Test can help you. - -So what makes a good test, and how does Google C++ Testing Framework fit in? We believe: - 1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging. - 1. Tests should be well _organized_ and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base. - 1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.) - 1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle. - 1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them. - 1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other. - -Since Google C++ Testing Framework is based on the popular xUnit -architecture, you'll feel right at home if you've used JUnit or PyUnit before. -If not, it will take you about 10 minutes to learn the basics and get started. -So let's go! - -_Note:_ We sometimes refer to Google C++ Testing Framework informally -as _Google Test_. - -# Beware of the nomenclature # - -_Note:_ There might be some confusion of idea due to different -definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware -of misunderstanding these. - -Historically, the Google C++ Testing Framework started to use the term -_Test Case_ for grouping related tests, whereas current publications -including the International Software Testing Qualifications Board -([ISTQB](http://www.istqb.org/)) and various textbooks on Software -Quality use the term _[Test -Suite](http://glossary.istqb.org/search/test%20suite)_ for this. - -The related term _Test_, as it is used in the Google C++ Testing -Framework, is corresponding to the term _[Test -Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB and -others. - -The term _Test_ is commonly of broad enough sense, including ISTQB's -definition of _Test Case_, so it's not much of a problem here. But the -term _Test Case_ as used in Google Test is of contradictory sense and thus confusing. - -Unfortunately replacing the term _Test Case_ by _Test Suite_ throughout -the Google C++ Testing Framework is not easy without breaking dependent -projects, as `TestCase` is part of the public API at various places. - -So for the time being, please be aware of the different definitions of -the terms: - -Meaning | Google Test Term | [ISTQB](http://www.istqb.org/) Term -------- | ---------------- | ----------------------------------- -Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) -A set of several tests related to one component | [Test Case](#basic-concepts) | [Test Suite](http://glossary.istqb.org/search/test%20suite) - -# Setting up a New Test Project # - -To write a test program using Google Test, you need to compile Google -Test into a library and link your test with it. We provide build -files for some popular build systems: `msvc/` for Visual Studio, -`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland -C++ Builder, and the autotools script (deprecated) and -`CMakeLists.txt` for CMake (recommended) in the Google Test root -directory. If your build system is not on this list, you can take a -look at `make/Makefile` to learn how Google Test should be compiled -(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT` -and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT` -is the Google Test root directory). - -Once you are able to compile the Google Test library, you should -create a project or build target for your test program. Make sure you -have `GTEST_ROOT/include` in the header search path so that the -compiler can find `"gtest/gtest.h"` when compiling your test. Set up -your test project to link with the Google Test library (for example, -in Visual Studio, this is done by adding a dependency on -`gtest.vcproj`). - -If you still have questions, take a look at how Google Test's own -tests are built and use them as examples. - -# Basic Concepts # - -When using Google Test, you start by writing _assertions_, which are statements -that check whether a condition is true. An assertion's result can be _success_, -_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts -the current function; otherwise the program continues normally. - -_Tests_ use assertions to verify the tested code's behavior. If a test crashes -or has a failed assertion, then it _fails_; otherwise it _succeeds_. - -A _test case_ contains one or many tests. You should group your tests into test -cases that reflect the structure of the tested code. When multiple tests in a -test case need to share common objects and subroutines, you can put them into a -_test fixture_ class. - -A _test program_ can contain multiple test cases. - -We'll now explain how to write a test program, starting at the individual -assertion level and building up to tests and test cases. - -# Assertions # - -Google Test assertions are macros that resemble function calls. You test a -class or function by making assertions about its behavior. When an assertion -fails, Google Test prints the assertion's source file and line number location, -along with a failure message. You may also supply a custom failure message -which will be appended to Google Test's message. - -The assertions come in pairs that test the same thing but have different -effects on the current function. `ASSERT_*` versions generate fatal failures -when they fail, and **abort the current function**. `EXPECT_*` versions generate -nonfatal failures, which don't abort the current function. Usually `EXPECT_*` -are preferred, as they allow more than one failures to be reported in a test. -However, you should use `ASSERT_*` if it doesn't make sense to continue when -the assertion in question fails. - -Since a failed `ASSERT_*` returns from the current function immediately, -possibly skipping clean-up code that comes after it, it may cause a space leak. -Depending on the nature of the leak, it may or may not be worth fixing - so -keep this in mind if you get a heap checker error in addition to assertion -errors. - -To provide a custom failure message, simply stream it into the macro using the -`<<` operator, or a sequence of such operators. An example: -``` -ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; - -for (int i = 0; i < x.size(); ++i) { - EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; -} -``` - -Anything that can be streamed to an `ostream` can be streamed to an assertion -macro--in particular, C strings and `string` objects. If a wide string -(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is -streamed to an assertion, it will be translated to UTF-8 when printed. - -## Basic Assertions ## - -These assertions do basic true/false condition testing. - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_TRUE(`_condition_`)`; | `EXPECT_TRUE(`_condition_`)`; | _condition_ is true | -| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`; | _condition_ is false | - -Remember, when they fail, `ASSERT_*` yields a fatal failure and -returns from the current function, while `EXPECT_*` yields a nonfatal -failure, allowing the function to continue running. In either case, an -assertion failure means its containing test fails. - -_Availability_: Linux, Windows, Mac. - -## Binary Comparison ## - -This section describes assertions that compare two values. - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -|`ASSERT_EQ(`_val1_`, `_val2_`);`|`EXPECT_EQ(`_val1_`, `_val2_`);`| _val1_ `==` _val2_ | -|`ASSERT_NE(`_val1_`, `_val2_`);`|`EXPECT_NE(`_val1_`, `_val2_`);`| _val1_ `!=` _val2_ | -|`ASSERT_LT(`_val1_`, `_val2_`);`|`EXPECT_LT(`_val1_`, `_val2_`);`| _val1_ `<` _val2_ | -|`ASSERT_LE(`_val1_`, `_val2_`);`|`EXPECT_LE(`_val1_`, `_val2_`);`| _val1_ `<=` _val2_ | -|`ASSERT_GT(`_val1_`, `_val2_`);`|`EXPECT_GT(`_val1_`, `_val2_`);`| _val1_ `>` _val2_ | -|`ASSERT_GE(`_val1_`, `_val2_`);`|`EXPECT_GE(`_val1_`, `_val2_`);`| _val1_ `>=` _val2_ | - -In the event of a failure, Google Test prints both _val1_ and _val2_. - -Value arguments must be comparable by the assertion's comparison -operator or you'll get a compiler error. We used to require the -arguments to support the `<<` operator for streaming to an `ostream`, -but it's no longer necessary since v1.6.0 (if `<<` is supported, it -will be called to print the arguments when the assertion fails; -otherwise Google Test will attempt to print them in the best way it -can. For more details and how to customize the printing of the -arguments, see this Google Mock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-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. `==`, `<`, etc). If the corresponding -operator is defined, prefer using the `ASSERT_*()` macros because they will -print out not only the result of the comparison, but the two operands as well. - -Arguments are always evaluated exactly once. Therefore, it's OK for the -arguments to have side effects. However, as with any ordinary C/C++ function, -the arguments' evaluation order is undefined (i.e. the compiler is free to -choose any order) and your code should not depend on any particular argument -evaluation order. - -`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it -tests if they are in the same memory location, not if they have the same value. -Therefore, if you want to compare C strings (e.g. `const char*`) by value, use -`ASSERT_STREQ()` , which will be described later on. In particular, to assert -that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to -compare two `string` objects, you should use `ASSERT_EQ`. - -Macros in this section work with both narrow and wide string objects (`string` -and `wstring`). - -_Availability_: Linux, Windows, Mac. - -_Historical note_: Before February 2016 `*_EQ` had a convention of calling it as -`ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. -Now `*_EQ` treats both parameters in the same way. - -## String Comparison ## - -The assertions in this group compare two **C strings**. If you want to compare -two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_STREQ(`_str1_`, `_str2_`);` | `EXPECT_STREQ(`_str1_`, `_str2_`);` | the two C strings have the same content | -| `ASSERT_STRNE(`_str1_`, `_str2_`);` | `EXPECT_STRNE(`_str1_`, `_str2_`);` | the two C strings have different content | -| `ASSERT_STRCASEEQ(`_str1_`, `_str2_`);`| `EXPECT_STRCASEEQ(`_str1_`, `_str2_`);` | the two C strings have the same content, ignoring case | -| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case | - -Note that "CASE" in an assertion name means that case is ignored. - -`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a -comparison of two wide strings fails, their values will be printed as UTF-8 -narrow strings. - -A `NULL` pointer and an empty string are considered _different_. - -_Availability_: Linux, Windows, Mac. - -See also: For more string comparison tricks (substring, prefix, suffix, and -regular expression matching, for example), see the [Advanced Google Test Guide](AdvancedGuide.md). - -# Simple Tests # - -To create a test: - 1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value. - 1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values. - 1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds. - -``` -TEST(testCaseName, testName) { - ... test body ... -} -``` - - -`TEST()` arguments go from general to specific. The _first_ argument is the -name of the test case, and the _second_ argument is the test's name within the -test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its -individual name. Tests from different test cases can have the same individual -name. - -For example, let's take a simple integer function: -``` -int Factorial(int n); // Returns the factorial of n -``` - -A test case for this function might look like: -``` -// Tests factorial of 0. -TEST(FactorialTest, HandlesZeroInput) { - EXPECT_EQ(1, Factorial(0)); -} - -// Tests factorial of positive numbers. -TEST(FactorialTest, HandlesPositiveInput) { - EXPECT_EQ(1, Factorial(1)); - EXPECT_EQ(2, Factorial(2)); - EXPECT_EQ(6, Factorial(3)); - EXPECT_EQ(40320, Factorial(8)); -} -``` - -Google Test groups the test results by test cases, so logically-related tests -should be in the same test case; in other words, the first argument to their -`TEST()` should be the same. In the above example, we have two tests, -`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test -case `FactorialTest`. - -_Availability_: Linux, Windows, Mac. - -# Test Fixtures: Using the Same Data Configuration for Multiple Tests # - -If you find yourself writing two or more tests that operate on similar data, -you can use a _test fixture_. It allows you to reuse the same configuration of -objects for several different tests. - -To create a fixture, just: - 1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes. - 1. Inside the class, declare any objects you plan to use. - 1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you. - 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](FAQ.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function). - 1. If needed, define subroutines for your tests to share. - -When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to -access objects and subroutines in the test fixture: -``` -TEST_F(test_case_name, test_name) { - ... test body ... -} -``` - -Like `TEST()`, the first argument is the test case name, but for `TEST_F()` -this must be the name of the test fixture class. You've probably guessed: `_F` -is for fixture. - -Unfortunately, the C++ macro system does not allow us to create a single macro -that can handle both types of tests. Using the wrong macro causes a compiler -error. - -Also, you must first define a test fixture class before using it in a -`TEST_F()`, or you'll get the compiler error "`virtual outside class -declaration`". - -For each test defined with `TEST_F()`, Google Test will: - 1. Create a _fresh_ test fixture at runtime - 1. Immediately initialize it via `SetUp()` - 1. Run the test - 1. Clean up by calling `TearDown()` - 1. Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests. - -As an example, let's write tests for a FIFO queue class named `Queue`, which -has the following interface: -``` -template // E is the element type. -class Queue { - public: - Queue(); - void Enqueue(const E& element); - E* Dequeue(); // Returns NULL if the queue is empty. - size_t size() const; - ... -}; -``` - -First, define a fixture class. By convention, you should give it the name -`FooTest` where `Foo` is the class being tested. -``` -class QueueTest : public ::testing::Test { - protected: - virtual void SetUp() { - q1_.Enqueue(1); - q2_.Enqueue(2); - q2_.Enqueue(3); - } - - // virtual void TearDown() {} - - Queue q0_; - Queue q1_; - Queue q2_; -}; -``` - -In this case, `TearDown()` is not needed since we don't have to clean up after -each test, other than what's already done by the destructor. - -Now we'll write tests using `TEST_F()` and this fixture. -``` -TEST_F(QueueTest, IsEmptyInitially) { - EXPECT_EQ(0, q0_.size()); -} - -TEST_F(QueueTest, DequeueWorks) { - int* n = q0_.Dequeue(); - EXPECT_EQ(NULL, n); - - n = q1_.Dequeue(); - ASSERT_TRUE(n != NULL); - EXPECT_EQ(1, *n); - EXPECT_EQ(0, q1_.size()); - delete n; - - n = q2_.Dequeue(); - ASSERT_TRUE(n != NULL); - EXPECT_EQ(2, *n); - EXPECT_EQ(1, q2_.size()); - delete n; -} -``` - -The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is -to use `EXPECT_*` when you want the test to continue to reveal more errors -after the assertion failure, and use `ASSERT_*` when continuing after failure -doesn't make sense. For example, the second assertion in the `Dequeue` test is -`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later, -which would lead to a segfault when `n` is `NULL`. - -When these tests run, the following happens: - 1. Google Test constructs a `QueueTest` object (let's call it `t1` ). - 1. `t1.SetUp()` initializes `t1` . - 1. The first test ( `IsEmptyInitially` ) runs on `t1` . - 1. `t1.TearDown()` cleans up after the test finishes. - 1. `t1` is destructed. - 1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test. - -_Availability_: Linux, Windows, Mac. - -_Note_: Google Test automatically saves all _Google Test_ flags when a test -object is constructed, and restores them when it is destructed. - -# Invoking the Tests # - -`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them. - -After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files. - -When invoked, the `RUN_ALL_TESTS()` macro: - 1. Saves the state of all Google Test flags. - 1. Creates a test fixture object for the first test. - 1. Initializes it via `SetUp()`. - 1. Runs the test on the fixture object. - 1. Cleans up the fixture via `TearDown()`. - 1. Deletes the fixture. - 1. Restores the state of all Google Test flags. - 1. Repeats the above steps for the next test, until all tests have run. - -In addition, if the test fixture's constructor generates a fatal failure in -step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly, -if step 3 generates a fatal failure, step 4 will be skipped. - -_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc` -will give you a compiler error. The rationale for this design is that the -automated testing service determines whether a test has passed based on its -exit code, not on its stdout/stderr output; thus your `main()` function must -return the value of `RUN_ALL_TESTS()`. - -Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once -conflicts with some advanced Google Test features (e.g. thread-safe death -tests) and thus is not supported. - -_Availability_: Linux, Windows, Mac. - -# Writing the main() Function # - -You can start from this boilerplate: -``` -#include "this/package/foo.h" -#include "gtest/gtest.h" - -namespace { - -// The fixture for testing class Foo. -class FooTest : public ::testing::Test { - protected: - // You can remove any or all of the following functions if its body - // is empty. - - FooTest() { - // You can do set-up work for each test here. - } - - virtual ~FooTest() { - // You can do clean-up work that doesn't throw exceptions here. - } - - // If the constructor and destructor are not enough for setting up - // and cleaning up each test, you can define the following methods: - - virtual void SetUp() { - // Code here will be called immediately after the constructor (right - // before each test). - } - - virtual void TearDown() { - // Code here will be called immediately after each test (right - // before the destructor). - } - - // Objects declared here can be used by all tests in the test case for Foo. -}; - -// Tests that the Foo::Bar() method does Abc. -TEST_F(FooTest, MethodBarDoesAbc) { - const string input_filepath = "this/package/testdata/myinputfile.dat"; - const string output_filepath = "this/package/testdata/myoutputfile.dat"; - Foo f; - EXPECT_EQ(0, f.Bar(input_filepath, output_filepath)); -} - -// Tests that Foo does Xyz. -TEST_F(FooTest, DoesXyz) { - // Exercises the Xyz feature of Foo. -} - -} // namespace - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -The `::testing::InitGoogleTest()` function parses the command line for Google -Test flags, and removes all recognized flags. This allows the user to control a -test program's behavior via various flags, which we'll cover in [AdvancedGuide](AdvancedGuide.md). -You must call this function before calling `RUN_ALL_TESTS()`, or the flags -won't be properly initialized. - -On Windows, `InitGoogleTest()` also works with wide strings, so it can be used -in programs compiled in `UNICODE` mode as well. - -But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go. - -## Important note for Visual C++ users ## -If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function: -``` -__declspec(dllexport) int PullInMyLibrary() { return 0; } -``` -If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function: -``` -int PullInMyLibrary(); -static int dummy = PullInMyLibrary(); -``` -This will keep your tests referenced and will make them register themselves at startup. - -In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable. - -There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries! - -# Where to Go from Here # - -Congratulations! You've learned the Google Test basics. You can start writing -and running Google Test tests, read some [samples](Samples.md), or continue with -[AdvancedGuide](AdvancedGuide.md), which describes many more useful Google Test features. - -# Known Limitations # - -Google Test is designed to be thread-safe. The implementation is -thread-safe on systems where the `pthreads` library is available. It -is currently _unsafe_ to use Google Test assertions from two threads -concurrently on other systems (e.g. Windows). In most tests this is -not an issue as usually the assertions are done in the main thread. If -you want to help, you can volunteer to implement the necessary -synchronization primitives in `gtest-port.h` for your platform. diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md new file mode 100644 index 0000000..5e8ee0c --- /dev/null +++ b/googletest/docs/primer.md @@ -0,0 +1,536 @@ + + +# Introduction: Why Google C++ Testing Framework? # + +_Google C++ Testing Framework_ helps you write better C++ tests. + +No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, +Google Test can help you. + +So what makes a good test, and how does Google C++ Testing Framework fit in? We believe: + 1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging. + 1. Tests should be well _organized_ and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base. + 1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.) + 1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle. + 1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them. + 1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other. + +Since Google C++ Testing Framework is based on the popular xUnit +architecture, you'll feel right at home if you've used JUnit or PyUnit before. +If not, it will take you about 10 minutes to learn the basics and get started. +So let's go! + +_Note:_ We sometimes refer to Google C++ Testing Framework informally +as _Google Test_. + +# Beware of the nomenclature # + +_Note:_ There might be some confusion of idea due to different +definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware +of misunderstanding these. + +Historically, the Google C++ Testing Framework started to use the term +_Test Case_ for grouping related tests, whereas current publications +including the International Software Testing Qualifications Board +([ISTQB](http://www.istqb.org/)) and various textbooks on Software +Quality use the term _[Test +Suite](http://glossary.istqb.org/search/test%20suite)_ for this. + +The related term _Test_, as it is used in the Google C++ Testing +Framework, is corresponding to the term _[Test +Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB and +others. + +The term _Test_ is commonly of broad enough sense, including ISTQB's +definition of _Test Case_, so it's not much of a problem here. But the +term _Test Case_ as used in Google Test is of contradictory sense and thus confusing. + +Unfortunately replacing the term _Test Case_ by _Test Suite_ throughout +the Google C++ Testing Framework is not easy without breaking dependent +projects, as `TestCase` is part of the public API at various places. + +So for the time being, please be aware of the different definitions of +the terms: + +Meaning | Google Test Term | [ISTQB](http://www.istqb.org/) Term +------- | ---------------- | ----------------------------------- +Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) +A set of several tests related to one component | [Test Case](#basic-concepts) | [Test Suite](http://glossary.istqb.org/search/test%20suite) + +# Setting up a New Test Project # + +To write a test program using Google Test, you need to compile Google +Test into a library and link your test with it. We provide build +files for some popular build systems: `msvc/` for Visual Studio, +`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland +C++ Builder, and the autotools script (deprecated) and +`CMakeLists.txt` for CMake (recommended) in the Google Test root +directory. If your build system is not on this list, you can take a +look at `make/Makefile` to learn how Google Test should be compiled +(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT` +and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT` +is the Google Test root directory). + +Once you are able to compile the Google Test library, you should +create a project or build target for your test program. Make sure you +have `GTEST_ROOT/include` in the header search path so that the +compiler can find `"gtest/gtest.h"` when compiling your test. Set up +your test project to link with the Google Test library (for example, +in Visual Studio, this is done by adding a dependency on +`gtest.vcproj`). + +If you still have questions, take a look at how Google Test's own +tests are built and use them as examples. + +# Basic Concepts # + +When using Google Test, you start by writing _assertions_, which are statements +that check whether a condition is true. An assertion's result can be _success_, +_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts +the current function; otherwise the program continues normally. + +_Tests_ use assertions to verify the tested code's behavior. If a test crashes +or has a failed assertion, then it _fails_; otherwise it _succeeds_. + +A _test case_ contains one or many tests. You should group your tests into test +cases that reflect the structure of the tested code. When multiple tests in a +test case need to share common objects and subroutines, you can put them into a +_test fixture_ class. + +A _test program_ can contain multiple test cases. + +We'll now explain how to write a test program, starting at the individual +assertion level and building up to tests and test cases. + +# Assertions # + +Google Test assertions are macros that resemble function calls. You test a +class or function by making assertions about its behavior. When an assertion +fails, Google Test prints the assertion's source file and line number location, +along with a failure message. You may also supply a custom failure message +which will be appended to Google Test's message. + +The assertions come in pairs that test the same thing but have different +effects on the current function. `ASSERT_*` versions generate fatal failures +when they fail, and **abort the current function**. `EXPECT_*` versions generate +nonfatal failures, which don't abort the current function. Usually `EXPECT_*` +are preferred, as they allow more than one failures to be reported in a test. +However, you should use `ASSERT_*` if it doesn't make sense to continue when +the assertion in question fails. + +Since a failed `ASSERT_*` returns from the current function immediately, +possibly skipping clean-up code that comes after it, it may cause a space leak. +Depending on the nature of the leak, it may or may not be worth fixing - so +keep this in mind if you get a heap checker error in addition to assertion +errors. + +To provide a custom failure message, simply stream it into the macro using the +`<<` operator, or a sequence of such operators. An example: +``` +ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; + +for (int i = 0; i < x.size(); ++i) { + EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; +} +``` + +Anything that can be streamed to an `ostream` can be streamed to an assertion +macro--in particular, C strings and `string` objects. If a wide string +(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is +streamed to an assertion, it will be translated to UTF-8 when printed. + +## Basic Assertions ## + +These assertions do basic true/false condition testing. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_TRUE(`_condition_`)`; | `EXPECT_TRUE(`_condition_`)`; | _condition_ is true | +| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`; | _condition_ is false | + +Remember, when they fail, `ASSERT_*` yields a fatal failure and +returns from the current function, while `EXPECT_*` yields a nonfatal +failure, allowing the function to continue running. In either case, an +assertion failure means its containing test fails. + +_Availability_: Linux, Windows, Mac. + +## Binary Comparison ## + +This section describes assertions that compare two values. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +|`ASSERT_EQ(`_val1_`, `_val2_`);`|`EXPECT_EQ(`_val1_`, `_val2_`);`| _val1_ `==` _val2_ | +|`ASSERT_NE(`_val1_`, `_val2_`);`|`EXPECT_NE(`_val1_`, `_val2_`);`| _val1_ `!=` _val2_ | +|`ASSERT_LT(`_val1_`, `_val2_`);`|`EXPECT_LT(`_val1_`, `_val2_`);`| _val1_ `<` _val2_ | +|`ASSERT_LE(`_val1_`, `_val2_`);`|`EXPECT_LE(`_val1_`, `_val2_`);`| _val1_ `<=` _val2_ | +|`ASSERT_GT(`_val1_`, `_val2_`);`|`EXPECT_GT(`_val1_`, `_val2_`);`| _val1_ `>` _val2_ | +|`ASSERT_GE(`_val1_`, `_val2_`);`|`EXPECT_GE(`_val1_`, `_val2_`);`| _val1_ `>=` _val2_ | + +In the event of a failure, Google Test prints both _val1_ and _val2_. + +Value arguments must be comparable by the assertion's comparison +operator or you'll get a compiler error. We used to require the +arguments to support the `<<` operator for streaming to an `ostream`, +but it's no longer necessary since v1.6.0 (if `<<` is supported, it +will be called to print the arguments when the assertion fails; +otherwise Google Test will attempt to print them in the best way it +can. For more details and how to customize the printing of the +arguments, see this Google Mock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-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. `==`, `<`, etc). If the corresponding +operator is defined, prefer using the `ASSERT_*()` macros because they will +print out not only the result of the comparison, but the two operands as well. + +Arguments are always evaluated exactly once. Therefore, it's OK for the +arguments to have side effects. However, as with any ordinary C/C++ function, +the arguments' evaluation order is undefined (i.e. the compiler is free to +choose any order) and your code should not depend on any particular argument +evaluation order. + +`ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it +tests if they are in the same memory location, not if they have the same value. +Therefore, if you want to compare C strings (e.g. `const char*`) by value, use +`ASSERT_STREQ()` , which will be described later on. In particular, to assert +that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to +compare two `string` objects, you should use `ASSERT_EQ`. + +Macros in this section work with both narrow and wide string objects (`string` +and `wstring`). + +_Availability_: Linux, Windows, Mac. + +_Historical note_: Before February 2016 `*_EQ` had a convention of calling it as +`ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. +Now `*_EQ` treats both parameters in the same way. + +## String Comparison ## + +The assertions in this group compare two **C strings**. If you want to compare +two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_STREQ(`_str1_`, `_str2_`);` | `EXPECT_STREQ(`_str1_`, `_str2_`);` | the two C strings have the same content | +| `ASSERT_STRNE(`_str1_`, `_str2_`);` | `EXPECT_STRNE(`_str1_`, `_str2_`);` | the two C strings have different content | +| `ASSERT_STRCASEEQ(`_str1_`, `_str2_`);`| `EXPECT_STRCASEEQ(`_str1_`, `_str2_`);` | the two C strings have the same content, ignoring case | +| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case | + +Note that "CASE" in an assertion name means that case is ignored. + +`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a +comparison of two wide strings fails, their values will be printed as UTF-8 +narrow strings. + +A `NULL` pointer and an empty string are considered _different_. + +_Availability_: Linux, Windows, Mac. + +See also: For more string comparison tricks (substring, prefix, suffix, and +regular expression matching, for example), see the [Advanced Google Test Guide](AdvancedGuide.md). + +# Simple Tests # + +To create a test: + 1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value. + 1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values. + 1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds. + +``` +TEST(testCaseName, testName) { + ... test body ... +} +``` + + +`TEST()` arguments go from general to specific. The _first_ argument is the +name of the test case, and the _second_ argument is the test's name within the +test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its +individual name. Tests from different test cases can have the same individual +name. + +For example, let's take a simple integer function: +``` +int Factorial(int n); // Returns the factorial of n +``` + +A test case for this function might look like: +``` +// Tests factorial of 0. +TEST(FactorialTest, HandlesZeroInput) { + EXPECT_EQ(1, Factorial(0)); +} + +// Tests factorial of positive numbers. +TEST(FactorialTest, HandlesPositiveInput) { + EXPECT_EQ(1, Factorial(1)); + EXPECT_EQ(2, Factorial(2)); + EXPECT_EQ(6, Factorial(3)); + EXPECT_EQ(40320, Factorial(8)); +} +``` + +Google Test groups the test results by test cases, so logically-related tests +should be in the same test case; in other words, the first argument to their +`TEST()` should be the same. In the above example, we have two tests, +`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test +case `FactorialTest`. + +_Availability_: Linux, Windows, Mac. + +# Test Fixtures: Using the Same Data Configuration for Multiple Tests # + +If you find yourself writing two or more tests that operate on similar data, +you can use a _test fixture_. It allows you to reuse the same configuration of +objects for several different tests. + +To create a fixture, just: + 1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes. + 1. Inside the class, declare any objects you plan to use. + 1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you. + 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](FAQ.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function). + 1. If needed, define subroutines for your tests to share. + +When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to +access objects and subroutines in the test fixture: +``` +TEST_F(test_case_name, test_name) { + ... test body ... +} +``` + +Like `TEST()`, the first argument is the test case name, but for `TEST_F()` +this must be the name of the test fixture class. You've probably guessed: `_F` +is for fixture. + +Unfortunately, the C++ macro system does not allow us to create a single macro +that can handle both types of tests. Using the wrong macro causes a compiler +error. + +Also, you must first define a test fixture class before using it in a +`TEST_F()`, or you'll get the compiler error "`virtual outside class +declaration`". + +For each test defined with `TEST_F()`, Google Test will: + 1. Create a _fresh_ test fixture at runtime + 1. Immediately initialize it via `SetUp()` + 1. Run the test + 1. Clean up by calling `TearDown()` + 1. Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests. + +As an example, let's write tests for a FIFO queue class named `Queue`, which +has the following interface: +``` +template // E is the element type. +class Queue { + public: + Queue(); + void Enqueue(const E& element); + E* Dequeue(); // Returns NULL if the queue is empty. + size_t size() const; + ... +}; +``` + +First, define a fixture class. By convention, you should give it the name +`FooTest` where `Foo` is the class being tested. +``` +class QueueTest : public ::testing::Test { + protected: + virtual void SetUp() { + q1_.Enqueue(1); + q2_.Enqueue(2); + q2_.Enqueue(3); + } + + // virtual void TearDown() {} + + Queue q0_; + Queue q1_; + Queue q2_; +}; +``` + +In this case, `TearDown()` is not needed since we don't have to clean up after +each test, other than what's already done by the destructor. + +Now we'll write tests using `TEST_F()` and this fixture. +``` +TEST_F(QueueTest, IsEmptyInitially) { + EXPECT_EQ(0, q0_.size()); +} + +TEST_F(QueueTest, DequeueWorks) { + int* n = q0_.Dequeue(); + EXPECT_EQ(NULL, n); + + n = q1_.Dequeue(); + ASSERT_TRUE(n != NULL); + EXPECT_EQ(1, *n); + EXPECT_EQ(0, q1_.size()); + delete n; + + n = q2_.Dequeue(); + ASSERT_TRUE(n != NULL); + EXPECT_EQ(2, *n); + EXPECT_EQ(1, q2_.size()); + delete n; +} +``` + +The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is +to use `EXPECT_*` when you want the test to continue to reveal more errors +after the assertion failure, and use `ASSERT_*` when continuing after failure +doesn't make sense. For example, the second assertion in the `Dequeue` test is +`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later, +which would lead to a segfault when `n` is `NULL`. + +When these tests run, the following happens: + 1. Google Test constructs a `QueueTest` object (let's call it `t1` ). + 1. `t1.SetUp()` initializes `t1` . + 1. The first test ( `IsEmptyInitially` ) runs on `t1` . + 1. `t1.TearDown()` cleans up after the test finishes. + 1. `t1` is destructed. + 1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test. + +_Availability_: Linux, Windows, Mac. + +_Note_: Google Test automatically saves all _Google Test_ flags when a test +object is constructed, and restores them when it is destructed. + +# Invoking the Tests # + +`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them. + +After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files. + +When invoked, the `RUN_ALL_TESTS()` macro: + 1. Saves the state of all Google Test flags. + 1. Creates a test fixture object for the first test. + 1. Initializes it via `SetUp()`. + 1. Runs the test on the fixture object. + 1. Cleans up the fixture via `TearDown()`. + 1. Deletes the fixture. + 1. Restores the state of all Google Test flags. + 1. Repeats the above steps for the next test, until all tests have run. + +In addition, if the test fixture's constructor generates a fatal failure in +step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly, +if step 3 generates a fatal failure, step 4 will be skipped. + +_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc` +will give you a compiler error. The rationale for this design is that the +automated testing service determines whether a test has passed based on its +exit code, not on its stdout/stderr output; thus your `main()` function must +return the value of `RUN_ALL_TESTS()`. + +Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once +conflicts with some advanced Google Test features (e.g. thread-safe death +tests) and thus is not supported. + +_Availability_: Linux, Windows, Mac. + +# Writing the main() Function # + +You can start from this boilerplate: +``` +#include "this/package/foo.h" +#include "gtest/gtest.h" + +namespace { + +// The fixture for testing class Foo. +class FooTest : public ::testing::Test { + protected: + // You can remove any or all of the following functions if its body + // is empty. + + FooTest() { + // You can do set-up work for each test here. + } + + virtual ~FooTest() { + // You can do clean-up work that doesn't throw exceptions here. + } + + // If the constructor and destructor are not enough for setting up + // and cleaning up each test, you can define the following methods: + + virtual void SetUp() { + // Code here will be called immediately after the constructor (right + // before each test). + } + + virtual void TearDown() { + // Code here will be called immediately after each test (right + // before the destructor). + } + + // Objects declared here can be used by all tests in the test case for Foo. +}; + +// Tests that the Foo::Bar() method does Abc. +TEST_F(FooTest, MethodBarDoesAbc) { + const string input_filepath = "this/package/testdata/myinputfile.dat"; + const string output_filepath = "this/package/testdata/myoutputfile.dat"; + Foo f; + EXPECT_EQ(0, f.Bar(input_filepath, output_filepath)); +} + +// Tests that Foo does Xyz. +TEST_F(FooTest, DoesXyz) { + // Exercises the Xyz feature of Foo. +} + +} // namespace + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +``` + +The `::testing::InitGoogleTest()` function parses the command line for Google +Test flags, and removes all recognized flags. This allows the user to control a +test program's behavior via various flags, which we'll cover in [AdvancedGuide](AdvancedGuide.md). +You must call this function before calling `RUN_ALL_TESTS()`, or the flags +won't be properly initialized. + +On Windows, `InitGoogleTest()` also works with wide strings, so it can be used +in programs compiled in `UNICODE` mode as well. + +But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go. + +## Important note for Visual C++ users ## +If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function: +``` +__declspec(dllexport) int PullInMyLibrary() { return 0; } +``` +If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function: +``` +int PullInMyLibrary(); +static int dummy = PullInMyLibrary(); +``` +This will keep your tests referenced and will make them register themselves at startup. + +In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable. + +There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries! + +# Where to Go from Here # + +Congratulations! You've learned the Google Test basics. You can start writing +and running Google Test tests, read some [samples](Samples.md), or continue with +[AdvancedGuide](AdvancedGuide.md), which describes many more useful Google Test features. + +# Known Limitations # + +Google Test is designed to be thread-safe. The implementation is +thread-safe on systems where the `pthreads` library is available. It +is currently _unsafe_ to use Google Test assertions from two threads +concurrently on other systems (e.g. Windows). In most tests this is +not an issue as usually the assertions are done in the main thread. If +you want to help, you can volunteer to implement the necessary +synchronization primitives in `gtest-port.h` for your platform. -- cgit v0.12 From 8f87d00398228925b1542b81710a9015c8f68e7b Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 11 Jun 2018 11:40:35 -0400 Subject: Rename AdvancedGuide.md to advanced.md and adjust the links. Part of documentation rationalization work --- googlemock/docs/CheatSheet.md | 2 +- googlemock/docs/CookBook.md | 2 +- googlemock/docs/ForDummies.md | 2 +- googletest/docs/AdvancedGuide.md | 2416 -------------------------------- googletest/docs/Documentation.md | 2 +- googletest/docs/FAQ.md | 16 +- googletest/docs/advanced.md | 2416 ++++++++++++++++++++++++++++++++ googletest/docs/primer.md | 6 +- googletest/scripts/fuse_gtest_files.py | 2 +- googletest/src/gtest.cc | 2 +- 10 files changed, 2433 insertions(+), 2433 deletions(-) delete mode 100644 googletest/docs/AdvancedGuide.md create mode 100644 googletest/docs/advanced.md diff --git a/googlemock/docs/CheatSheet.md b/googlemock/docs/CheatSheet.md index d078b42..d54dd16 100644 --- a/googlemock/docs/CheatSheet.md +++ b/googlemock/docs/CheatSheet.md @@ -229,7 +229,7 @@ The `argument` can be either a C string or a C++ string object: `ContainsRegex()` and `MatchesRegex()` use the regular expression syntax defined -[here](../../googletest/docs/AdvancedGuide.md#regular-expression-syntax). +[here](../../googletest/docs/advanced.md#regular-expression-syntax). `StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide strings as well. diff --git a/googlemock/docs/CookBook.md b/googlemock/docs/CookBook.md index 3737d03..bd9f026 100644 --- a/googlemock/docs/CookBook.md +++ b/googlemock/docs/CookBook.md @@ -3655,6 +3655,6 @@ This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the `<<` operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. -[Google Test's advanced guide](../../googletest/docs/AdvancedGuide.md#teaching-google-test-how-to-print-your-values) +[Google Test's advanced guide](../../googletest/docs/advanced.md#teaching-google-test-how-to-print-your-values) explains how to extend the printer to do a better job at printing your particular type than to dump the bytes. diff --git a/googlemock/docs/ForDummies.md b/googlemock/docs/ForDummies.md index 7691056..1e0fd41 100644 --- a/googlemock/docs/ForDummies.md +++ b/googlemock/docs/ForDummies.md @@ -187,7 +187,7 @@ sometimes causes the test program to crash. You'll still be able to notice that the test has failed, but it's not a graceful failure. A better solution is to use Google Test's -[event listener API](../../googletest/docs/AdvancedGuide.md#extending-google-test-by-handling-test-events) +[event listener API](../../googletest/docs/advanced.md#extending-google-test-by-handling-test-events) to report a test failure to your testing framework properly. You'll need to implement the `OnTestPartResult()` method of the event listener interface, but it should be straightforward. diff --git a/googletest/docs/AdvancedGuide.md b/googletest/docs/AdvancedGuide.md deleted file mode 100644 index 857967a..0000000 --- a/googletest/docs/AdvancedGuide.md +++ /dev/null @@ -1,2416 +0,0 @@ - - -Now that you have read [Primer](primer.md) and learned how to write tests -using Google Test, it's time to learn some new tricks. This document -will show you more assertions as well as how to construct complex -failure messages, propagate fatal failures, reuse and speed up your -test fixtures, and use various flags with your tests. - -# More Assertions # - -This section covers some less frequently used, but still significant, -assertions. - -## Explicit Success and Failure ## - -These three assertions do not actually test a value or expression. Instead, -they generate a success or failure directly. Like the macros that actually -perform a test, you may stream a custom failure message into them. - -| `SUCCEED();` | -|:-------------| - -Generates a success. This does NOT make the overall test succeed. A test is -considered successful only if none of its assertions fail during its execution. - -Note: `SUCCEED()` is purely documentary and currently doesn't generate any -user-visible output. However, we may add `SUCCEED()` messages to Google Test's -output in the future. - -| `FAIL();` | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` | -|:-----------|:-----------------|:------------------------------------------------------| - -`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal -failure. These are useful when control flow, rather than a Boolean expression, -determines the test's success or failure. For example, you might want to write -something like: - -``` -switch(expression) { - case 1: ... some checks ... - case 2: ... some other checks - ... - default: FAIL() << "We shouldn't get here."; -} -``` - -Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information. - -_Availability_: Linux, Windows, Mac. - -## Exception Assertions ## - -These are for verifying that a piece of code throws (or does not -throw) an exception of the given type: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type | -| `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type | -| `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception | - -Examples: - -``` -ASSERT_THROW(Foo(5), bar_exception); - -EXPECT_NO_THROW({ - int n = 5; - Bar(&n); -}); -``` - -_Availability_: Linux, Windows, Mac; since version 1.1.0. - -## Predicate Assertions for Better Error Messages ## - -Even though Google Test has a rich set of assertions, they can never be -complete, as it's impossible (nor a good idea) to anticipate all the scenarios -a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` -to check a complex expression, for lack of a better macro. This has the problem -of not showing you the values of the parts of the expression, making it hard to -understand what went wrong. As a workaround, some users choose to construct the -failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this -is awkward especially when the expression has side-effects or is expensive to -evaluate. - -Google Test gives you three different options to solve this problem: - -### Using an Existing Boolean Function ### - -If you already have a function or a functor that returns `bool` (or a type -that can be implicitly converted to `bool`), you can use it in a _predicate -assertion_ to get the function arguments printed for free: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true | -| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true | -| ... | ... | ... | - -In the above, _predn_ is an _n_-ary predicate function or functor, where -_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds -if the predicate returns `true` when applied to the given arguments, and fails -otherwise. When the assertion fails, it prints the value of each argument. In -either case, the arguments are evaluated exactly once. - -Here's an example. Given - -``` -// Returns true iff m and n have no common divisors except 1. -bool MutuallyPrime(int m, int n) { ... } -const int a = 3; -const int b = 4; -const int c = 10; -``` - -the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the -assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message - -
-!MutuallyPrime(b, c) is false, where
-b is 4
-c is 10
-
- -**Notes:** - - 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](FAQ.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. - 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. - -_Availability_: Linux, Windows, Mac. - -### Using a Function That Returns an AssertionResult ### - -While `EXPECT_PRED*()` and friends are handy for a quick job, the -syntax is not satisfactory: you have to use different macros for -different arities, and it feels more like Lisp than C++. The -`::testing::AssertionResult` class solves this problem. - -An `AssertionResult` object represents the result of an assertion -(whether it's a success or a failure, and an associated message). You -can create an `AssertionResult` using one of these factory -functions: - -``` -namespace testing { - -// Returns an AssertionResult object to indicate that an assertion has -// succeeded. -AssertionResult AssertionSuccess(); - -// Returns an AssertionResult object to indicate that an assertion has -// failed. -AssertionResult AssertionFailure(); - -} -``` - -You can then use the `<<` operator to stream messages to the -`AssertionResult` object. - -To provide more readable messages in Boolean assertions -(e.g. `EXPECT_TRUE()`), write a predicate function that returns -`AssertionResult` instead of `bool`. For example, if you define -`IsEven()` as: - -``` -::testing::AssertionResult IsEven(int n) { - if ((n % 2) == 0) - return ::testing::AssertionSuccess(); - else - return ::testing::AssertionFailure() << n << " is odd"; -} -``` - -instead of: - -``` -bool IsEven(int n) { - return (n % 2) == 0; -} -``` - -the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: - -
-Value of: IsEven(Fib(4))
-Actual: false (*3 is odd*)
-Expected: true
-
- -instead of a more opaque - -
-Value of: IsEven(Fib(4))
-Actual: false
-Expected: true
-
- -If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` -as well, and are fine with making the predicate slower in the success -case, you can supply a success message: - -``` -::testing::AssertionResult IsEven(int n) { - if ((n % 2) == 0) - return ::testing::AssertionSuccess() << n << " is even"; - else - return ::testing::AssertionFailure() << n << " is odd"; -} -``` - -Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print - -
-Value of: IsEven(Fib(6))
-Actual: true (8 is even)
-Expected: false
-
- -_Availability_: Linux, Windows, Mac; since version 1.4.1. - -### Using a Predicate-Formatter ### - -If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and -`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your -predicate do not support streaming to `ostream`, you can instead use the -following _predicate-formatter assertions_ to _fully_ customize how the -message is formatted: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful | -| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful | -| `...` | `...` | `...` | - -The difference between this and the previous two groups of macros is that instead of -a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_ -(_pred\_formatn_), which is a function or functor with the signature: - -`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);` - -where _val1_, _val2_, ..., and _valn_ are the values of the predicate -arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding -expressions as they appear in the source code. The types `T1`, `T2`, ..., and -`Tn` can be either value types or reference types. For example, if an -argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`, -whichever is appropriate. - -A predicate-formatter returns a `::testing::AssertionResult` object to indicate -whether the assertion has succeeded or not. The only way to create such an -object is to call one of these factory functions: - -As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`: - -``` -// Returns the smallest prime common divisor of m and n, -// or 1 when m and n are mutually prime. -int SmallestPrimeCommonDivisor(int m, int n) { ... } - -// A predicate-formatter for asserting that two integers are mutually prime. -::testing::AssertionResult AssertMutuallyPrime(const char* m_expr, - const char* n_expr, - int m, - int n) { - if (MutuallyPrime(m, n)) - return ::testing::AssertionSuccess(); - - return ::testing::AssertionFailure() - << m_expr << " and " << n_expr << " (" << m << " and " << n - << ") are not mutually prime, " << "as they have a common divisor " - << SmallestPrimeCommonDivisor(m, n); -} -``` - -With this predicate-formatter, we can use - -``` -EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); -``` - -to generate the message - -
-b and c (4 and 10) are not mutually prime, as they have a common divisor 2.
-
- -As you may have realized, many of the assertions we introduced earlier are -special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are -indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. - -_Availability_: Linux, Windows, Mac. - - -## Floating-Point Comparison ## - -Comparing floating-point numbers is tricky. Due to round-off errors, it is -very unlikely that two floating-points will match exactly. Therefore, -`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points -can have a wide value range, no single fixed error bound works. It's better to -compare by a fixed relative error bound, except for values close to 0 due to -the loss of precision there. - -In general, for floating-point comparison to make sense, the user needs to -carefully choose the error bound. If they don't want or care to, comparing in -terms of Units in the Last Place (ULPs) is a good default, and Google Test -provides assertions to do this. Full details about ULPs are quite long; if you -want to learn more, see -[this article on float comparison](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). - -### Floating-Point Macros ### - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_FLOAT_EQ(`_val1, val2_`);` | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal | -| `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal | - -By "almost equal", we mean the two values are within 4 ULP's from each -other. - -The following assertions allow you to choose the acceptable error bound: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error | - -_Availability_: Linux, Windows, Mac. - -### Floating-Point Predicate-Format Functions ### - -Some floating-point operations are useful, but not that often used. In order -to avoid an explosion of new macros, we provide them as predicate-format -functions that can be used in predicate assertion macros (e.g. -`EXPECT_PRED_FORMAT2`, etc). - -``` -EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); -EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); -``` - -Verifies that _val1_ is less than, or almost equal to, _val2_. You can -replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. - -_Availability_: Linux, Windows, Mac. - -## Windows HRESULT assertions ## - -These assertions test for `HRESULT` success or failure. - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` | -| `ASSERT_HRESULT_FAILED(`_expression_`);` | `EXPECT_HRESULT_FAILED(`_expression_`);` | _expression_ is a failure `HRESULT` | - -The generated output contains the human-readable error message -associated with the `HRESULT` code returned by _expression_. - -You might use them like this: - -``` -CComPtr shell; -ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); -CComVariant empty; -ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); -``` - -_Availability_: Windows. - -## Type Assertions ## - -You can call the function -``` -::testing::StaticAssertTypeEq(); -``` -to assert that types `T1` and `T2` are the same. The function does -nothing if the assertion is satisfied. If the types are different, -the function call will fail to compile, and the compiler error message -will likely (depending on the compiler) show you the actual values of -`T1` and `T2`. This is mainly useful inside template code. - -_Caveat:_ When used inside a member function of a class template or a -function template, `StaticAssertTypeEq()` is effective _only if_ -the function is instantiated. For example, given: -``` -template class Foo { - public: - void Bar() { ::testing::StaticAssertTypeEq(); } -}; -``` -the code: -``` -void Test1() { Foo foo; } -``` -will _not_ generate a compiler error, as `Foo::Bar()` is never -actually instantiated. Instead, you need: -``` -void Test2() { Foo foo; foo.Bar(); } -``` -to cause a compiler error. - -_Availability:_ Linux, Windows, Mac; since version 1.3.0. - -## Assertion Placement ## - -You can use assertions in any C++ function. In particular, it doesn't -have to be a method of the test fixture class. The one constraint is -that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`) -can only be used in void-returning functions. This is a consequence of -Google Test not using exceptions. By placing it in a non-void function -you'll get a confusing compile error like -`"error: void value not ignored as it ought to be"`. - -If you need to use assertions in a function that returns non-void, one option -is to make the function return the value in an out parameter instead. For -example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You -need to make sure that `*result` contains some sensible value even when the -function returns prematurely. As the function now returns `void`, you can use -any assertion inside of it. - -If changing the function's type is not an option, you should just use -assertions that generate non-fatal failures, such as `ADD_FAILURE*` and -`EXPECT_*`. - -_Note_: Constructors and destructors are not considered void-returning -functions, according to the C++ language specification, and so you may not use -fatal assertions in them. You'll get a compilation error if you try. A simple -workaround is to transfer the entire body of the constructor or destructor to a -private void-returning method. However, you should be aware that a fatal -assertion failure in a constructor does not terminate the current test, as your -intuition might suggest; it merely returns from the constructor early, possibly -leaving your object in a partially-constructed state. Likewise, a fatal -assertion failure in a destructor may leave your object in a -partially-destructed state. Use assertions carefully in these situations! - -# Teaching Google Test How to Print Your Values # - -When a test assertion such as `EXPECT_EQ` fails, Google Test prints the -argument values to help you debug. It does this using a -user-extensible value printer. - -This printer knows how to print built-in C++ types, native arrays, STL -containers, and any type that supports the `<<` operator. For other -types, it prints the raw bytes in the value and hopes that you the -user can figure it out. - -As mentioned earlier, the printer is _extensible_. That means -you can teach it to do a better job at printing your particular type -than to dump the bytes. To do that, define `<<` for your type: - -``` -#include - -namespace foo { - -class Bar { ... }; // We want Google Test to be able to print instances of this. - -// It's important that the << operator is defined in the SAME -// namespace that defines Bar. C++'s look-up rules rely on that. -::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { - return os << bar.DebugString(); // whatever needed to print bar to os -} - -} // namespace foo -``` - -Sometimes, this might not be an option: your team may consider it bad -style to have a `<<` operator for `Bar`, or `Bar` may already have a -`<<` operator that doesn't do what you want (and you cannot change -it). If so, you can instead define a `PrintTo()` function like this: - -``` -#include - -namespace foo { - -class Bar { ... }; - -// It's important that PrintTo() is defined in the SAME -// namespace that defines Bar. C++'s look-up rules rely on that. -void PrintTo(const Bar& bar, ::std::ostream* os) { - *os << bar.DebugString(); // whatever needed to print bar to os -} - -} // namespace foo -``` - -If you have defined both `<<` and `PrintTo()`, the latter will be used -when Google Test is concerned. This allows you to customize how the value -appears in Google Test's output without affecting code that relies on the -behavior of its `<<` operator. - -If you want to print a value `x` using Google Test's value printer -yourself, just call `::testing::PrintToString(`_x_`)`, which -returns an `std::string`: - -``` -vector > bar_ints = GetBarIntVector(); - -EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) - << "bar_ints = " << ::testing::PrintToString(bar_ints); -``` - -# Death Tests # - -In many applications, there are assertions that can cause application failure -if a condition is not met. These sanity checks, which ensure that the program -is in a known good state, are there to fail at the earliest possible time after -some program state is corrupted. If the assertion checks the wrong condition, -then the program may proceed in an erroneous state, which could lead to memory -corruption, security holes, or worse. Hence it is vitally important to test -that such assertion statements work as expected. - -Since these precondition checks cause the processes to die, we call such tests -_death tests_. More generally, any test that checks that a program terminates -(except by throwing an exception) in an expected fashion is also a death test. - -Note that if a piece of code throws an exception, we don't consider it "death" -for the purpose of death tests, as the caller of the code could catch the exception -and avoid the crash. If you want to verify exceptions thrown by your code, -see [Exception Assertions](#exception-assertions). - -If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures). - -## How to Write a Death Test ## - -Google Test has the following macros to support death tests: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error | -| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing | -| `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ | - -where _statement_ is a statement that is expected to cause the process to -die, _predicate_ is a function or function object that evaluates an integer -exit status, and _regex_ is a regular expression that the stderr output of -_statement_ is expected to match. Note that _statement_ can be _any valid -statement_ (including _compound statement_) and doesn't have to be an -expression. - -As usual, the `ASSERT` variants abort the current test function, while the -`EXPECT` variants do not. - -**Note:** We use the word "crash" here to mean that the process -terminates with a _non-zero_ exit status code. There are two -possibilities: either the process has called `exit()` or `_exit()` -with a non-zero value, or it may be killed by a signal. - -This means that if _statement_ terminates the process with a 0 exit -code, it is _not_ considered a crash by `EXPECT_DEATH`. Use -`EXPECT_EXIT` instead if this is the case, or if you want to restrict -the exit code more precisely. - -A predicate here must accept an `int` and return a `bool`. The death test -succeeds only if the predicate returns `true`. Google Test defines a few -predicates that handle the most common cases: - -``` -::testing::ExitedWithCode(exit_code) -``` - -This expression is `true` if the program exited normally with the given exit -code. - -``` -::testing::KilledBySignal(signal_number) // Not available on Windows. -``` - -This expression is `true` if the program was killed by the given signal. - -The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate -that verifies the process' exit code is non-zero. - -Note that a death test only cares about three things: - - 1. does _statement_ abort or exit the process? - 1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And - 1. does the stderr output match _regex_? - -In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process. - -To write a death test, simply use one of the above macros inside your test -function. For example, - -``` -TEST(MyDeathTest, Foo) { - // This death test uses a compound statement. - ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()"); -} -TEST(MyDeathTest, NormalExit) { - EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); -} -TEST(MyDeathTest, KillMyself) { - EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); -} -``` - -verifies that: - - * calling `Foo(5)` causes the process to die with the given error message, - * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and - * calling `KillMyself()` kills the process with signal `SIGKILL`. - -The test function body may contain other assertions and statements as well, if -necessary. - -_Important:_ We strongly recommend you to follow the convention of naming your -test case (not test) `*DeathTest` when it contains a death test, as -demonstrated in the above example. The `Death Tests And Threads` section below -explains why. - -If a test fixture class is shared by normal tests and death tests, you -can use typedef to introduce an alias for the fixture class and avoid -duplicating its code: -``` -class FooTest : public ::testing::Test { ... }; - -typedef FooTest FooDeathTest; - -TEST_F(FooTest, DoesThis) { - // normal test -} - -TEST_F(FooDeathTest, DoesThat) { - // death test -} -``` - -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0). `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0. - -## Regular Expression Syntax ## - -On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the -[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) -syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). - -On Windows, Google Test uses its own simple regular expression -implementation. It lacks many features you can find in POSIX extended -regular expressions. For example, we don't support union (`"x|y"`), -grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count -(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a -literal character, period (`.`), or a single `\\` escape sequence; `x` -and `y` denote regular expressions.): - -| `c` | matches any literal character `c` | -|:----|:----------------------------------| -| `\\d` | matches any decimal digit | -| `\\D` | matches any character that's not a decimal digit | -| `\\f` | matches `\f` | -| `\\n` | matches `\n` | -| `\\r` | matches `\r` | -| `\\s` | matches any ASCII whitespace, including `\n` | -| `\\S` | matches any character that's not a whitespace | -| `\\t` | matches `\t` | -| `\\v` | matches `\v` | -| `\\w` | matches any letter, `_`, or decimal digit | -| `\\W` | matches any character that `\\w` doesn't match | -| `\\c` | matches any literal character `c`, which must be a punctuation | -| `\\.` | matches the `.` character | -| `.` | matches any single character except `\n` | -| `A?` | matches 0 or 1 occurrences of `A` | -| `A*` | matches 0 or many occurrences of `A` | -| `A+` | matches 1 or many occurrences of `A` | -| `^` | matches the beginning of a string (not that of each line) | -| `$` | matches the end of a string (not that of each line) | -| `xy` | matches `x` followed by `y` | - -To help you determine which capability is available on your system, -Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX -extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses -the simple version. If you want your death tests to work in both -cases, you can either `#if` on these macros or use the more limited -syntax only. - -## How It Works ## - -Under the hood, `ASSERT_EXIT()` spawns a new process and executes the -death test statement in that process. The details of how precisely -that happens depend on the platform and the variable -`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the -command-line flag `--gtest_death_test_style`). - - * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which: - * If the variable's value is `"fast"`, the death test statement is immediately executed. - * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run. - * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX. - -Other values for the variable are illegal and will cause the death test to -fail. Currently, the flag's default value is `"fast"`. However, we reserve the -right to change it in the future. Therefore, your tests should not depend on -this. - -In either case, the parent process waits for the child process to complete, and checks that - - 1. the child's exit status satisfies the predicate, and - 1. the child's stderr matches the regular expression. - -If the death test statement runs to completion without dying, the child -process will nonetheless terminate, and the assertion fails. - -## Death Tests And Threads ## - -The reason for the two death test styles has to do with thread safety. Due to -well-known problems with forking in the presence of threads, death tests should -be run in a single-threaded context. Sometimes, however, it isn't feasible to -arrange that kind of environment. For example, statically-initialized modules -may start threads before main is ever reached. Once threads have been created, -it may be difficult or impossible to clean them up. - -Google Test has three features intended to raise awareness of threading issues. - - 1. A warning is emitted if multiple threads are running when a death test is encountered. - 1. Test cases with a name ending in "DeathTest" are run before all other tests. - 1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. - -It's perfectly fine to create threads inside a death test statement; they are -executed in a separate process and cannot affect the parent. - -## Death Test Styles ## - -The "threadsafe" death test style was introduced in order to help mitigate the -risks of testing in a possibly multithreaded environment. It trades increased -test execution time (potentially dramatically so) for improved thread safety. -We suggest using the faster, default "fast" style unless your test has specific -problems with it. - -You can choose a particular style of death tests by setting the flag -programmatically: - -``` -::testing::FLAGS_gtest_death_test_style = "threadsafe"; -``` - -You can do this in `main()` to set the style for all death tests in the -binary, or in individual tests. Recall that flags are saved before running each -test and restored afterwards, so you need not do that yourself. For example: - -``` -TEST(MyDeathTest, TestOne) { - ::testing::FLAGS_gtest_death_test_style = "threadsafe"; - // This test is run in the "threadsafe" style: - ASSERT_DEATH(ThisShouldDie(), ""); -} - -TEST(MyDeathTest, TestTwo) { - // This test is run in the "fast" style: - ASSERT_DEATH(ThisShouldDie(), ""); -} - -int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); - ::testing::FLAGS_gtest_death_test_style = "fast"; - return RUN_ALL_TESTS(); -} -``` - -## Caveats ## - -The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement. -If it leaves the current function via a `return` statement or by throwing an exception, -the death test is considered to have failed. Some Google Test macros may return -from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_. - -Since _statement_ runs in the child process, any in-memory side effect (e.g. -modifying a variable, releasing memory, etc) it causes will _not_ be observable -in the parent process. In particular, if you release memory in a death test, -your program will fail the heap check as the parent process will never see the -memory reclaimed. To solve this problem, you can - - 1. try not to free memory in a death test; - 1. free the memory again in the parent process; or - 1. do not use the heap checker in your program. - -Due to an implementation detail, you cannot place multiple death test -assertions on the same line; otherwise, compilation will fail with an unobvious -error message. - -Despite the improved thread safety afforded by the "threadsafe" style of death -test, thread problems such as deadlock are still possible in the presence of -handlers registered with `pthread_atfork(3)`. - -# Using Assertions in Sub-routines # - -## Adding Traces to Assertions ## - -If a test sub-routine is called from several places, when an assertion -inside it fails, it can be hard to tell which invocation of the -sub-routine the failure is from. You can alleviate this problem using -extra logging or custom failure messages, but that usually clutters up -your tests. A better solution is to use the `SCOPED_TRACE` macro or -the `ScopedTrace` utility: - -| `SCOPED_TRACE(`_message_`);` | `::testing::ScopedTrace trace(`_"file\_path"_`, `_line\_number_`, `_message_`);` | -|:-----------------------------|:---------------------------------------------------------------------------------| - -where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` -macro will cause the current file name, line number, and the given message to be -added in every failure message. `ScopedTrace` accepts explicit file name and -line number in arguments, which is useful for writing test helpers. The effect -will be undone when the control leaves the current lexical scope. - -For example, - -``` -10: void Sub1(int n) { -11: EXPECT_EQ(1, Bar(n)); -12: EXPECT_EQ(2, Bar(n + 1)); -13: } -14: -15: TEST(FooTest, Bar) { -16: { -17: SCOPED_TRACE("A"); // This trace point will be included in -18: // every failure in this scope. -19: Sub1(1); -20: } -21: // Now it won't. -22: Sub1(9); -23: } -``` - -could result in messages like these: - -``` -path/to/foo_test.cc:11: Failure -Value of: Bar(n) -Expected: 1 - Actual: 2 - Trace: -path/to/foo_test.cc:17: A - -path/to/foo_test.cc:12: Failure -Value of: Bar(n + 1) -Expected: 2 - Actual: 3 -``` - -Without the trace, it would've been difficult to know which invocation -of `Sub1()` the two failures come from respectively. (You could add an -extra message to each assertion in `Sub1()` to indicate the value of -`n`, but that's tedious.) - -Some tips on using `SCOPED_TRACE`: - - 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site. - 1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from. - 1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`. - 1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. - 1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! - -_Availability:_ Linux, Windows, Mac. - -## Propagating Fatal Failures ## - -A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that -when they fail they only abort the _current function_, not the entire test. For -example, the following test will segfault: -``` -void Subroutine() { - // Generates a fatal failure and aborts the current function. - ASSERT_EQ(1, 2); - // The following won't be executed. - ... -} - -TEST(FooTest, Bar) { - Subroutine(); - // The intended behavior is for the fatal failure - // in Subroutine() to abort the entire test. - // The actual behavior: the function goes on after Subroutine() returns. - int* p = NULL; - *p = 3; // Segfault! -} -``` - -To alleviate this, gUnit provides three different solutions. You could use -either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the -`HasFatalFailure()` function. They are described in the following two -subsections. - -#### Asserting on Subroutines with an exception - -The following code can turn ASSERT-failure into an exception: - -```c++ -class ThrowListener : public testing::EmptyTestEventListener { - void OnTestPartResult(const testing::TestPartResult& result) override { - if (result.type() == testing::TestPartResult::kFatalFailure) { - throw testing::AssertionException(result); - } - } -}; -int main(int argc, char** argv) { - ... - testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); - return RUN_ALL_TESTS(); -} -``` - -This listener should be added after other listeners if you have any, otherwise -they won't see failed `OnTestPartResult`. - -### Asserting on Subroutines ### - -As shown above, if your test calls a subroutine that has an `ASSERT_*` -failure in it, the test will continue after the subroutine -returns. This may not be what you want. - -Often people want fatal failures to propagate like exceptions. For -that Google Test offers the following macros: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. | - -Only failures in the thread that executes the assertion are checked to -determine the result of this type of assertions. If _statement_ -creates new threads, failures in these threads are ignored. - -Examples: - -``` -ASSERT_NO_FATAL_FAILURE(Foo()); - -int i; -EXPECT_NO_FATAL_FAILURE({ - i = Bar(); -}); -``` - -_Availability:_ Linux, Windows, Mac. Assertions from multiple threads -are currently not supported. - -### Checking for Failures in the Current Test ### - -`HasFatalFailure()` in the `::testing::Test` class returns `true` if an -assertion in the current test has suffered a fatal failure. This -allows functions to catch fatal failures in a sub-routine and return -early. - -``` -class Test { - public: - ... - static bool HasFatalFailure(); -}; -``` - -The typical usage, which basically simulates the behavior of a thrown -exception, is: - -``` -TEST(FooTest, Bar) { - Subroutine(); - // Aborts if Subroutine() had a fatal failure. - if (HasFatalFailure()) - return; - // The following won't be executed. - ... -} -``` - -If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test -fixture, you must add the `::testing::Test::` prefix, as in: - -``` -if (::testing::Test::HasFatalFailure()) - return; -``` - -Similarly, `HasNonfatalFailure()` returns `true` if the current test -has at least one non-fatal failure, and `HasFailure()` returns `true` -if the current test has at least one failure of either kind. - -_Availability:_ Linux, Windows, Mac. `HasNonfatalFailure()` and -`HasFailure()` are available since version 1.4.0. - -# Logging Additional Information # - -In your test code, you can call `RecordProperty("key", value)` to log -additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output -if you specify one. For example, the test - -``` -TEST_F(WidgetUsageTest, MinAndMaxWidgets) { - RecordProperty("MaximumWidgets", ComputeMaxUsage()); - RecordProperty("MinimumWidgets", ComputeMinUsage()); -} -``` - -will output XML like this: - -``` -... - -... -``` - -_Note_: - * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class. - * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`). - * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element. - -_Availability_: Linux, Windows, Mac. - -# Sharing Resources Between Tests in the Same Test Case # - - - -Google Test creates a new test fixture object for each test in order to make -tests independent and easier to debug. However, sometimes tests use resources -that are expensive to set up, making the one-copy-per-test model prohibitively -expensive. - -If the tests don't change the resource, there's no harm in them sharing a -single resource copy. So, in addition to per-test set-up/tear-down, Google Test -also supports per-test-case set-up/tear-down. To use it: - - 1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources. - 1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down. - -That's it! Google Test automatically calls `SetUpTestCase()` before running the -_first test_ in the `FooTest` test case (i.e. before creating the first -`FooTest` object), and calls `TearDownTestCase()` after running the _last test_ -in it (i.e. after deleting the last `FooTest` object). In between, the tests -can use the shared resources. - -Remember that the test order is undefined, so your code can't depend on a test -preceding or following another. Also, the tests must either not modify the -state of any shared resource, or, if they do modify the state, they must -restore the state to its original value before passing control to the next -test. - -Here's an example of per-test-case set-up and tear-down: -``` -class FooTest : public ::testing::Test { - protected: - // Per-test-case set-up. - // Called before the first test in this test case. - // Can be omitted if not needed. - static void SetUpTestCase() { - shared_resource_ = new ...; - } - - // Per-test-case tear-down. - // Called after the last test in this test case. - // Can be omitted if not needed. - static void TearDownTestCase() { - delete shared_resource_; - shared_resource_ = NULL; - } - - // You can define per-test set-up and tear-down logic as usual. - virtual void SetUp() { ... } - virtual void TearDown() { ... } - - // Some expensive resource shared by all tests. - static T* shared_resource_; -}; - -T* FooTest::shared_resource_ = NULL; - -TEST_F(FooTest, Test1) { - ... you can refer to shared_resource here ... -} -TEST_F(FooTest, Test2) { - ... you can refer to shared_resource here ... -} -``` - -_Availability:_ Linux, Windows, Mac. - -# Global Set-Up and Tear-Down # - -Just as you can do set-up and tear-down at the test level and the test case -level, you can also do it at the test program level. Here's how. - -First, you subclass the `::testing::Environment` class to define a test -environment, which knows how to set-up and tear-down: - -``` -class Environment { - public: - virtual ~Environment() {} - // Override this to define how to set up the environment. - virtual void SetUp() {} - // Override this to define how to tear down the environment. - virtual void TearDown() {} -}; -``` - -Then, you register an instance of your environment class with Google Test by -calling the `::testing::AddGlobalTestEnvironment()` function: - -``` -Environment* AddGlobalTestEnvironment(Environment* env); -``` - -Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of -the environment object, then runs the tests if there was no fatal failures, and -finally calls `TearDown()` of the environment object. - -It's OK to register multiple environment objects. In this case, their `SetUp()` -will be called in the order they are registered, and their `TearDown()` will be -called in the reverse order. - -Note that Google Test takes ownership of the registered environment objects. -Therefore **do not delete them** by yourself. - -You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is -called, probably in `main()`. If you use `gtest_main`, you need to call -this before `main()` starts for it to take effect. One way to do this is to -define a global variable like this: - -``` -::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); -``` - -However, we strongly recommend you to write your own `main()` and call -`AddGlobalTestEnvironment()` there, as relying on initialization of global -variables makes the code harder to read and may cause problems when you -register multiple environments from different translation units and the -environments have dependencies among them (remember that the compiler doesn't -guarantee the order in which global variables from different translation units -are initialized). - -_Availability:_ Linux, Windows, Mac. - - -# Value Parameterized Tests # - -_Value-parameterized tests_ allow you to test your code with different -parameters without writing multiple copies of the same test. - -Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag. - -``` -TEST(MyCodeTest, TestFoo) { - // A code to test foo(). -} -``` - -Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code. - -``` -void TestFooHelper(bool flag_value) { - flag = flag_value; - // A code to test foo(). -} - -TEST(MyCodeTest, TestFoo) { - TestFooHelper(false); - TestFooHelper(true); -} -``` - -But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred? - -Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values. - -Here are some other situations when value-parameterized tests come handy: - - * You want to test different implementations of an OO interface. - * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! - -## How to Write Value-Parameterized Tests ## - -To write value-parameterized tests, first you should define a fixture -class. It must be derived from both `::testing::Test` and -`::testing::WithParamInterface` (the latter is a pure interface), -where `T` is the type of your parameter values. For convenience, you -can just derive the fixture class from `::testing::TestWithParam`, -which itself is derived from both `::testing::Test` and -`::testing::WithParamInterface`. `T` can be any copyable type. If -it's a raw pointer, you are responsible for managing the lifespan of -the pointed values. - -``` -class FooTest : public ::testing::TestWithParam { - // You can implement all the usual fixture class members here. - // To access the test parameter, call GetParam() from class - // TestWithParam. -}; - -// Or, when you want to add parameters to a pre-existing fixture class: -class BaseTest : public ::testing::Test { - ... -}; -class BarTest : public BaseTest, - public ::testing::WithParamInterface { - ... -}; -``` - -Then, use the `TEST_P` macro to define as many test patterns using -this fixture as you want. The `_P` suffix is for "parameterized" or -"pattern", whichever you prefer to think. - -``` -TEST_P(FooTest, DoesBlah) { - // Inside a test, access the test parameter with the GetParam() method - // of the TestWithParam class: - EXPECT_TRUE(foo.Blah(GetParam())); - ... -} - -TEST_P(FooTest, HasBlahBlah) { - ... -} -``` - -Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test -case with any set of parameters you want. Google Test defines a number of -functions for generating test parameters. They return what we call -(surprise!) _parameter generators_. Here is a summary of them, -which are all in the `testing` namespace: - -| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | -|:----------------------------|:------------------------------------------------------------------------------------------------------------------| -| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | -| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time. | -| `Bool()` | Yields sequence `{false, true}`. | -| `Combine(g1, g2, ..., gN)` | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](../include/gtest/internal/gtest-port.h) for more information. | - -For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h). - -The following statement will instantiate tests from the `FooTest` test case -each with parameter values `"meeny"`, `"miny"`, and `"moe"`. - -``` -INSTANTIATE_TEST_CASE_P(InstantiationName, - FooTest, - ::testing::Values("meeny", "miny", "moe")); -``` - -To distinguish different instances of the pattern (yes, you can -instantiate it more than once), the first argument to -`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual -test case name. Remember to pick unique prefixes for different -instantiations. The tests from the instantiation above will have these -names: - - * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` - * `InstantiationName/FooTest.DoesBlah/1` for `"miny"` - * `InstantiationName/FooTest.DoesBlah/2` for `"moe"` - * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` - * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` - * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` - -You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests). - -This statement will instantiate all tests from `FooTest` again, each -with parameter values `"cat"` and `"dog"`: - -``` -const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, - ::testing::ValuesIn(pets)); -``` - -The tests from the instantiation above will have these names: - - * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` - * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` - * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` - * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` - -Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_ -tests in the given test case, whether their definitions come before or -_after_ the `INSTANTIATE_TEST_CASE_P` statement. - -You can see -[these](../samples/sample7_unittest.cc) -[files](../samples/sample8_unittest.cc) for more examples. - -_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0. - -## Creating Value-Parameterized Abstract Tests ## - -In the above, we define and instantiate `FooTest` in the same source -file. Sometimes you may want to define value-parameterized tests in a -library and let other people instantiate them later. This pattern is -known as abstract tests. As an example of its application, when you -are designing an interface you can write a standard suite of abstract -tests (perhaps using a factory function as the test parameter) that -all implementations of the interface are expected to pass. When -someone implements the interface, they can instantiate your suite to get -all the interface-conformance tests for free. - -To define abstract tests, you should organize your code like this: - - 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests. - 1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests. - -Once they are defined, you can instantiate them by including -`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking -with `foo_param_test.cc`. You can instantiate the same abstract test -case multiple times, possibly in different source files. - -# Typed Tests # - -Suppose you have multiple implementations of the same interface and -want to make sure that all of them satisfy some common requirements. -Or, you may have defined several types that are supposed to conform to -the same "concept" and you want to verify it. In both cases, you want -the same test logic repeated for different types. - -While you can write one `TEST` or `TEST_F` for each type you want to -test (and you may even factor the test logic into a function template -that you invoke from the `TEST`), it's tedious and doesn't scale: -if you want _m_ tests over _n_ types, you'll end up writing _m\*n_ -`TEST`s. - -_Typed tests_ allow you to repeat the same test logic over a list of -types. You only need to write the test logic once, although you must -know the type list when writing typed tests. Here's how you do it: - -First, define a fixture class template. It should be parameterized -by a type. Remember to derive it from `::testing::Test`: - -``` -template -class FooTest : public ::testing::Test { - public: - ... - typedef std::list List; - static T shared_; - T value_; -}; -``` - -Next, associate a list of types with the test case, which will be -repeated for each type in the list: - -``` -typedef ::testing::Types MyTypes; -TYPED_TEST_CASE(FooTest, MyTypes); -``` - -The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse -correctly. Otherwise the compiler will think that each comma in the -type list introduces a new macro argument. - -Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test -for this test case. You can repeat this as many times as you want: - -``` -TYPED_TEST(FooTest, DoesBlah) { - // Inside a test, refer to the special name TypeParam to get the type - // parameter. Since we are inside a derived class template, C++ requires - // us to visit the members of FooTest via 'this'. - TypeParam n = this->value_; - - // To visit static members of the fixture, add the 'TestFixture::' - // prefix. - n += TestFixture::shared_; - - // To refer to typedefs in the fixture, add the 'typename TestFixture::' - // prefix. The 'typename' is required to satisfy the compiler. - typename TestFixture::List values; - values.push_back(n); - ... -} - -TYPED_TEST(FooTest, HasPropertyA) { ... } -``` - -You can see [`samples/sample6_unittest.cc`](../samples/sample6_unittest.cc) for a complete example. - -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; -since version 1.1.0. - -# Type-Parameterized Tests # - -_Type-parameterized tests_ are like typed tests, except that they -don't require you to know the list of types ahead of time. Instead, -you can define the test logic first and instantiate it with different -type lists later. You can even instantiate it more than once in the -same program. - -If you are designing an interface or concept, you can define a suite -of type-parameterized tests to verify properties that any valid -implementation of the interface/concept should have. Then, the author -of each implementation can just instantiate the test suite with his -type to verify that it conforms to the requirements, without having to -write similar tests repeatedly. Here's an example: - -First, define a fixture class template, as we did with typed tests: - -``` -template -class FooTest : public ::testing::Test { - ... -}; -``` - -Next, declare that you will define a type-parameterized test case: - -``` -TYPED_TEST_CASE_P(FooTest); -``` - -The `_P` suffix is for "parameterized" or "pattern", whichever you -prefer to think. - -Then, use `TYPED_TEST_P()` to define a type-parameterized test. You -can repeat this as many times as you want: - -``` -TYPED_TEST_P(FooTest, DoesBlah) { - // Inside a test, refer to TypeParam to get the type parameter. - TypeParam n = 0; - ... -} - -TYPED_TEST_P(FooTest, HasPropertyA) { ... } -``` - -Now the tricky part: you need to register all test patterns using the -`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. -The first argument of the macro is the test case name; the rest are -the names of the tests in this test case: - -``` -REGISTER_TYPED_TEST_CASE_P(FooTest, - DoesBlah, HasPropertyA); -``` - -Finally, you are free to instantiate the pattern with the types you -want. If you put the above code in a header file, you can `#include` -it in multiple C++ source files and instantiate it multiple times. - -``` -typedef ::testing::Types MyTypes; -INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); -``` - -To distinguish different instances of the pattern, the first argument -to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be -added to the actual test case name. Remember to pick unique prefixes -for different instances. - -In the special case where the type list contains only one type, you -can write that type directly without `::testing::Types<...>`, like this: - -``` -INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); -``` - -You can see `samples/sample6_unittest.cc` for a complete example. - -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; -since version 1.1.0. - -# Testing Private Code # - -If you change your software's internal implementation, your tests should not -break as long as the change is not observable by users. Therefore, per the -_black-box testing principle_, most of the time you should test your code -through its public interfaces. - -If you still find yourself needing to test internal implementation code, -consider if there's a better design that wouldn't require you to do so. If you -absolutely have to test non-public interface code though, you can. There are -two cases to consider: - - * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and - * Private or protected class members. - -## Static Functions ## - -Both static functions and definitions/declarations in an unnamed namespace are -only visible within the same translation unit. To test them, you can `#include` -the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc` -files is not a good way to reuse code - you should not do this in production -code!) - -However, a better approach is to move the private code into the -`foo::internal` namespace, where `foo` is the namespace your project normally -uses, and put the private declarations in a `*-internal.h` file. Your -production `.cc` files and your tests are allowed to include this internal -header, but your clients are not. This way, you can fully test your internal -implementation without leaking it to your clients. - -## Private Class Members ## - -Private class members are only accessible from within the class or by friends. -To access a class' private members, you can declare your test fixture as a -friend to the class and define accessors in your fixture. Tests using the -fixture can then access the private members of your production class via the -accessors in the fixture. Note that even though your fixture is a friend to -your production class, your tests are not automatically friends to it, as they -are technically defined in sub-classes of the fixture. - -Another way to test private members is to refactor them into an implementation -class, which is then declared in a `*-internal.h` file. Your clients aren't -allowed to include this header but your tests can. Such is called the Pimpl -(Private Implementation) idiom. - -Or, you can declare an individual test as a friend of your class by adding this -line in the class body: - -``` -FRIEND_TEST(TestCaseName, TestName); -``` - -For example, -``` -// foo.h -#include "gtest/gtest_prod.h" - -// Defines FRIEND_TEST. -class Foo { - ... - private: - FRIEND_TEST(FooTest, BarReturnsZeroOnNull); - int Bar(void* x); -}; - -// foo_test.cc -... -TEST(FooTest, BarReturnsZeroOnNull) { - Foo foo; - EXPECT_EQ(0, foo.Bar(NULL)); - // Uses Foo's private member Bar(). -} -``` - -Pay special attention when your class is defined in a namespace, as you should -define your test fixtures and tests in the same namespace if you want them to -be friends of your class. For example, if the code to be tested looks like: - -``` -namespace my_namespace { - -class Foo { - friend class FooTest; - FRIEND_TEST(FooTest, Bar); - FRIEND_TEST(FooTest, Baz); - ... - definition of the class Foo - ... -}; - -} // namespace my_namespace -``` - -Your test code should be something like: - -``` -namespace my_namespace { -class FooTest : public ::testing::Test { - protected: - ... -}; - -TEST_F(FooTest, Bar) { ... } -TEST_F(FooTest, Baz) { ... } - -} // namespace my_namespace -``` - -# Catching Failures # - -If you are building a testing utility on top of Google Test, you'll -want to test your utility. What framework would you use to test it? -Google Test, of course. - -The challenge is to verify that your testing utility reports failures -correctly. In frameworks that report a failure by throwing an -exception, you could catch the exception and assert on it. But Google -Test doesn't use exceptions, so how do we test that a piece of code -generates an expected failure? - -`"gtest/gtest-spi.h"` contains some constructs to do this. After -`#include`ing this header, you can use - -| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` | -|:--------------------------------------------------| - -to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure -whose message contains the given _substring_, or use - -| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` | -|:-----------------------------------------------------| - -if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. - -For technical reasons, there are some caveats: - - 1. You cannot stream a failure message to either macro. - 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object. - 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value. - -_Note:_ Google Test is designed with threads in mind. Once the -synchronization primitives in `"gtest/internal/gtest-port.h"` have -been implemented, Google Test will become thread-safe, meaning that -you can then use assertions in multiple threads concurrently. Before -that, however, Google Test only supports single-threaded usage. Once -thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()` -will capture failures in the current thread only. If _statement_ -creates new threads, failures in these threads will be ignored. If -you want to capture failures from all threads instead, you should use -the following macros: - -| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | -|:-----------------------------------------------------------------| -| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | - -# Getting the Current Test's Name # - -Sometimes a function may need to know the name of the currently running test. -For example, you may be using the `SetUp()` method of your test fixture to set -the golden file name based on which test is running. The `::testing::TestInfo` -class has this information: - -``` -namespace testing { - -class TestInfo { - public: - // Returns the test case name and the test name, respectively. - // - // Do NOT delete or free the return value - it's managed by the - // TestInfo class. - const char* test_case_name() const; - const char* name() const; -}; - -} // namespace testing -``` - - -> To obtain a `TestInfo` object for the currently running test, call -`current_test_info()` on the `UnitTest` singleton object: - -``` -// Gets information about the currently running test. -// Do NOT delete the returned object - it's managed by the UnitTest class. -const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); -printf("We are in test %s of test case %s.\n", - test_info->name(), test_info->test_case_name()); -``` - -`current_test_info()` returns a null pointer if no test is running. In -particular, you cannot find the test case name in `SetUpTestCase()`, -`TearDownTestCase()` (where you know the test case name implicitly), or -functions called from them. - -_Availability:_ Linux, Windows, Mac. - -# Extending Google Test by Handling Test Events # - -Google Test provides an event listener API to let you receive -notifications about the progress of a test program and test -failures. The events you can listen to include the start and end of -the test program, a test case, or a test method, among others. You may -use this API to augment or replace the standard console output, -replace the XML output, or provide a completely different form of -output, such as a GUI or a database. You can also use test events as -checkpoints to implement a resource leak checker, for example. - -_Availability:_ Linux, Windows, Mac; since v1.4.0. - -## Defining Event Listeners ## - -To define a event listener, you subclass either -[testing::TestEventListener](../include/gtest/gtest.h#L991) -or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L1044). -The former is an (abstract) interface, where each pure virtual method
-can be overridden to handle a test event
(For example, when a test -starts, the `OnTestStart()` method will be called.). The latter provides -an empty implementation of all methods in the interface, such that a -subclass only needs to override the methods it cares about. - -When an event is fired, its context is passed to the handler function -as an argument. The following argument types are used: - * [UnitTest](../include/gtest/gtest.h#L1151) reflects the state of the entire test program, - * [TestCase](../include/gtest/gtest.h#L778) has information about a test case, which can contain one or more tests, - * [TestInfo](../include/gtest/gtest.h#L644) contains the state of a test, and - * [TestPartResult](../include/gtest/gtest-test-part.h#L47) represents the result of a test assertion. - -An event handler function can examine the argument it receives to find -out interesting information about the event and the test program's -state. Here's an example: - -``` - class MinimalistPrinter : public ::testing::EmptyTestEventListener { - // Called before a test starts. - virtual void OnTestStart(const ::testing::TestInfo& test_info) { - printf("*** Test %s.%s starting.\n", - test_info.test_case_name(), test_info.name()); - } - - // Called after a failed assertion or a SUCCEED() invocation. - virtual void OnTestPartResult( - const ::testing::TestPartResult& test_part_result) { - printf("%s in %s:%d\n%s\n", - test_part_result.failed() ? "*** Failure" : "Success", - test_part_result.file_name(), - test_part_result.line_number(), - test_part_result.summary()); - } - - // Called after a test ends. - virtual void OnTestEnd(const ::testing::TestInfo& test_info) { - printf("*** Test %s.%s ending.\n", - test_info.test_case_name(), test_info.name()); - } - }; -``` - -## Using Event Listeners ## - -To use the event listener you have defined, add an instance of it to -the Google Test event listener list (represented by class -[TestEventListeners](../include/gtest/gtest.h#L1064) -- note the "s" at the end of the name) in your -`main()` function, before calling `RUN_ALL_TESTS()`: -``` -int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); - // Gets hold of the event listener list. - ::testing::TestEventListeners& listeners = - ::testing::UnitTest::GetInstance()->listeners(); - // Adds a listener to the end. Google Test takes the ownership. - listeners.Append(new MinimalistPrinter); - return RUN_ALL_TESTS(); -} -``` - -There's only one problem: the default test result printer is still in -effect, so its output will mingle with the output from your minimalist -printer. To suppress the default printer, just release it from the -event listener list and delete it. You can do so by adding one line: -``` - ... - delete listeners.Release(listeners.default_result_printer()); - listeners.Append(new MinimalistPrinter); - return RUN_ALL_TESTS(); -``` - -Now, sit back and enjoy a completely different output from your -tests. For more details, you can read this -[sample](../samples/sample9_unittest.cc). - -You may append more than one listener to the list. When an `On*Start()` -or `OnTestPartResult()` event is fired, the listeners will receive it in -the order they appear in the list (since new listeners are added to -the end of the list, the default text printer and the default XML -generator will receive the event first). An `On*End()` event will be -received by the listeners in the _reverse_ order. This allows output by -listeners added later to be framed by output from listeners added -earlier. - -## Generating Failures in Listeners ## - -You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, -`FAIL()`, etc) when processing an event. There are some restrictions: - - 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively). - 1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure. - -When you add listeners to the listener list, you should put listeners -that handle `OnTestPartResult()` _before_ listeners that can generate -failures. This ensures that failures generated by the latter are -attributed to the right test by the former. - -We have a sample of failure-raising listener -[here](../samples/sample10_unittest.cc). - -# Running Test Programs: Advanced Options # - -Google Test test programs are ordinary executables. Once built, you can run -them directly and affect their behavior via the following environment variables -and/or command line flags. For the flags to work, your programs must call -`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. - -To see a list of supported flags and their usage, please run your test -program with the `--help` flag. You can also use `-h`, `-?`, or `/?` -for short. This feature is added in version 1.3.0. - -If an option is specified both by an environment variable and by a -flag, the latter takes precedence. Most of the options can also be -set/read in code: to access the value of command line flag -`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`. A common pattern is -to set the value of a flag before calling `::testing::InitGoogleTest()` -to change the default value of the flag: -``` -int main(int argc, char** argv) { - // Disables elapsed time by default. - ::testing::GTEST_FLAG(print_time) = false; - - // This allows the user to override the flag on the command line. - ::testing::InitGoogleTest(&argc, argv); - - return RUN_ALL_TESTS(); -} -``` - -## Selecting Tests ## - -This section shows various options for choosing which tests to run. - -### Listing Test Names ### - -Sometimes it is necessary to list the available tests in a program before -running them so that a filter may be applied if needed. Including the flag -`--gtest_list_tests` overrides all other flags and lists tests in the following -format: -``` -TestCase1. - TestName1 - TestName2 -TestCase2. - TestName -``` - -None of the tests listed are actually run if the flag is provided. There is no -corresponding environment variable for this flag. - -_Availability:_ Linux, Windows, Mac. - -### Running a Subset of the Tests ### - -By default, a Google Test program runs all tests the user has defined. -Sometimes, you want to run only a subset of the tests (e.g. for debugging or -quickly verifying a change). If you set the `GTEST_FILTER` environment variable -or the `--gtest_filter` flag to a filter string, Google Test will only run the -tests whose full names (in the form of `TestCaseName.TestName`) match the -filter. - -The format of a filter is a '`:`'-separated list of wildcard patterns (called -the positive patterns) optionally followed by a '`-`' and another -'`:`'-separated pattern list (called the negative patterns). A test matches the -filter if and only if it matches any of the positive patterns but does not -match any of the negative patterns. - -A pattern may contain `'*'` (matches any string) or `'?'` (matches any single -character). For convenience, the filter `'*-NegativePatterns'` can be also -written as `'-NegativePatterns'`. - -For example: - - * `./foo_test` Has no flag, and thus runs all its tests. - * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. - * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`. - * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`. - * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. - * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`. - -_Availability:_ Linux, Windows, Mac. - -### Temporarily Disabling Tests ### - -If you have a broken test that you cannot fix right away, you can add the -`DISABLED_` prefix to its name. This will exclude it from execution. This is -better than commenting out the code or using `#if 0`, as disabled tests are -still compiled (and thus won't rot). - -If you need to disable all tests in a test case, you can either add `DISABLED_` -to the front of the name of each test, or alternatively add it to the front of -the test case name. - -For example, the following tests won't be run by Google Test, even though they -will still be compiled: - -``` -// Tests that Foo does Abc. -TEST(FooTest, DISABLED_DoesAbc) { ... } - -class DISABLED_BarTest : public ::testing::Test { ... }; - -// Tests that Bar does Xyz. -TEST_F(DISABLED_BarTest, DoesXyz) { ... } -``` - -_Note:_ This feature should only be used for temporary pain-relief. You still -have to fix the disabled tests at a later date. As a reminder, Google Test will -print a banner warning you if a test program contains any disabled tests. - -_Tip:_ You can easily count the number of disabled tests you have -using `grep`. This number can be used as a metric for improving your -test quality. - -_Availability:_ Linux, Windows, Mac. - -### Temporarily Enabling Disabled Tests ### - -To include [disabled tests](#temporarily-disabling-tests) in test -execution, just invoke the test program with the -`--gtest_also_run_disabled_tests` flag or set the -`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other -than `0`. You can combine this with the -[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select -which disabled tests to run. - -_Availability:_ Linux, Windows, Mac; since version 1.3.0. - -## Repeating the Tests ## - -Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it -will fail only 1% of the time, making it rather hard to reproduce the bug under -a debugger. This can be a major source of frustration. - -The `--gtest_repeat` flag allows you to repeat all (or selected) test methods -in a program many times. Hopefully, a flaky test will eventually fail and give -you a chance to debug. Here's how to use it: - -| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. | -|:---------------------------------|:--------------------------------------------------------| -| `$ foo_test --gtest_repeat=-1` | A negative count means repeating forever. | -| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. | -| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. | - -If your test program contains global set-up/tear-down code registered -using `AddGlobalTestEnvironment()`, it will be repeated in each -iteration as well, as the flakiness may be in it. You can also specify -the repeat count by setting the `GTEST_REPEAT` environment variable. - -_Availability:_ Linux, Windows, Mac. - -## Shuffling the Tests ## - -You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` -environment variable to `1`) to run the tests in a program in a random -order. This helps to reveal bad dependencies between tests. - -By default, Google Test uses a random seed calculated from the current -time. Therefore you'll get a different order every time. The console -output includes the random seed value, such that you can reproduce an -order-related test failure later. To specify the random seed -explicitly, use the `--gtest_random_seed=SEED` flag (or set the -`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer -between 0 and 99999. The seed value 0 is special: it tells Google Test -to do the default behavior of calculating the seed from the current -time. - -If you combine this with `--gtest_repeat=N`, Google Test will pick a -different random seed and re-shuffle the tests in each iteration. - -_Availability:_ Linux, Windows, Mac; since v1.4.0. - -## Controlling Test Output ## - -This section teaches how to tweak the way test results are reported. - -### Colored Terminal Output ### - -Google Test can use colors in its terminal output to make it easier to spot -the separation between tests, and whether tests passed. - -You can set the GTEST\_COLOR environment variable or set the `--gtest_color` -command line flag to `yes`, `no`, or `auto` (the default) to enable colors, -disable colors, or let Google Test decide. When the value is `auto`, Google -Test 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`. - -_Availability:_ Linux, Windows, Mac. - -### Suppressing the Elapsed Time ### - -By default, Google Test prints the time it takes to run each test. To -suppress that, run the test program with the `--gtest_print_time=0` -command line flag. Setting the `GTEST_PRINT_TIME` environment -variable to `0` has the same effect. - -_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, -the default behavior is that the elapsed time is **not** printed.) - -**Availability**: Linux, Windows, Mac. - -#### Suppressing UTF-8 Text Output - -In case of assertion failures, gUnit prints expected and actual values of type -`string` both as hex-encoded strings as well as in readable UTF-8 text if they -contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 text -because, for example, you don't have an UTF-8 compatible output medium, run the -test program with `--gunit_print_utf8=0` or set the `GUNIT_PRINT_UTF8` -environment variable to `0`. - -### Generating an XML Report ### - -Google Test 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. - -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 -create the file at the given location. You can also just use the string -`"xml"`, in which case the output can be found in the `test_detail.xml` file in -the current directory. - -If you specify a directory (for example, `"xml:output/directory/"` on Linux or -`"xml:output\directory\"` on Windows), Google Test will create the XML file in -that directory, named after the test executable (e.g. `foo_test.xml` for test -program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left -over from a previous run), Google Test will pick a different name (e.g. -`foo_test_1.xml`) to avoid overwriting it. - -The report uses the format described here. It is based on the -`junitreport` Ant task and can be parsed by popular continuous build -systems like [Hudson](https://hudson.dev.java.net/). Since that format -was originally intended for Java, a little interpretation is required -to make it apply to Google Test tests, as shown here: - -``` - - - - - - - - - -``` - - * The root `` element corresponds to the entire test program. - * `` elements correspond to Google Test test cases. - * `` elements correspond to Google Test test functions. - -For instance, the following program - -``` -TEST(MathTest, Addition) { ... } -TEST(MathTest, Subtraction) { ... } -TEST(LogicTest, NonContradiction) { ... } -``` - -could generate this report: - -``` - - - - - - - - - - - - - - - -``` - -Things to note: - - * The `tests` attribute of a `` or `` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed. - * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds. - * Each `` element corresponds to a single failed Google Test assertion. - * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts. - -_Availability:_ Linux, Windows, Mac. - -#### Generating an JSON Report {#JsonReport} - -gUnit can also emit a JSON report as an alternative format to XML. To generate -the JSON report, set the `GUNIT_OUTPUT` environment variable or the -`--gunit_output` flag to the string `"json:path_to_output_file"`, which will -create the file at the given location. You can also just use the string -`"json"`, in which case the output can be found in the `test_detail.json` file -in the current directory. - -The report format conforms to the following JSON Schema: - -```json -{ - "$schema": "http://json-schema.org/schema#", - "type": "object", - "definitions": { - "TestCase": { - "type": "object", - "properties": { - "name": { "type": "string" }, - "tests": { "type": "integer" }, - "failures": { "type": "integer" }, - "disabled": { "type": "integer" }, - "time": { "type": "string" }, - "testsuite": { - "type": "array", - "items": { - "$ref": "#/definitions/TestInfo" - } - } - } - }, - "TestInfo": { - "type": "object", - "properties": { - "name": { "type": "string" }, - "status": { - "type": "string", - "enum": ["RUN", "NOTRUN"] - }, - "time": { "type": "string" }, - "classname": { "type": "string" }, - "failures": { - "type": "array", - "items": { - "$ref": "#/definitions/Failure" - } - } - } - }, - "Failure": { - "type": "object", - "properties": { - "failures": { "type": "string" }, - "type": { "type": "string" } - } - } - }, - "properties": { - "tests": { "type": "integer" }, - "failures": { "type": "integer" }, - "disabled": { "type": "integer" }, - "errors": { "type": "integer" }, - "timestamp": { - "type": "string", - "format": "date-time" - }, - "time": { "type": "string" }, - "name": { "type": "string" }, - "testsuites": { - "type": "array", - "items": { - "$ref": "#/definitions/TestCase" - } - } - } -} -``` - -The report uses the format that conforms to the following Proto3 using the -[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): - -```proto -syntax = "proto3"; - -package googletest; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; - -message UnitTest { - int32 tests = 1; - int32 failures = 2; - int32 disabled = 3; - int32 errors = 4; - google.protobuf.Timestamp timestamp = 5; - google.protobuf.Duration time = 6; - string name = 7; - repeated TestCase testsuites = 8; -} - -message TestCase { - string name = 1; - int32 tests = 2; - int32 failures = 3; - int32 disabled = 4; - int32 errors = 5; - google.protobuf.Duration time = 6; - repeated TestInfo testsuite = 7; -} - -message TestInfo { - string name = 1; - enum Status { - RUN = 0; - NOTRUN = 1; - } - Status status = 2; - google.protobuf.Duration time = 3; - string classname = 4; - message Failure { - string failures = 1; - string type = 2; - } - repeated Failure failures = 5; -} -``` - -For instance, the following program - -```c++ -TEST(MathTest, Addition) { ... } -TEST(MathTest, Subtraction) { ... } -TEST(LogicTest, NonContradiction) { ... } -``` - -could generate this report: - -```json -{ - "tests": 3, - "failures": 1, - "errors": 0, - "time": "0.035s", - "timestamp": "2011-10-31T18:52:42Z" - "name": "AllTests", - "testsuites": [ - { - "name": "MathTest", - "tests": 2, - "failures": 1, - "errors": 0, - "time": "0.015s", - "testsuite": [ - { - "name": "Addition", - "status": "RUN", - "time": "0.007s", - "classname": "", - "failures": [ - { - "message": "Value of: add(1, 1)\x0A Actual: 3\x0AExpected: 2", - "type": "" - }, - { - "message": "Value of: add(1, -1)\x0A Actual: 1\x0AExpected: 0", - "type": "" - } - ] - }, - { - "name": "Subtraction", - "status": "RUN", - "time": "0.005s", - "classname": "" - } - ] - } - { - "name": "LogicTest", - "tests": 1, - "failures": 0, - "errors": 0, - "time": "0.005s", - "testsuite": [ - { - "name": "NonContradiction", - "status": "RUN", - "time": "0.005s", - "classname": "" - } - ] - } - ] -} -``` - -IMPORTANT: The exact format of the JSON document is subject to change. - -**Availability**: Linux, Windows, Mac. - -## Controlling How Failures Are Reported ## - -### Turning Assertion Failures into Break-Points ### - -When running test programs under a debugger, it's very convenient if the -debugger can catch an assertion failure and automatically drop into interactive -mode. Google Test's _break-on-failure_ mode supports this behavior. - -To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value -other than `0` . Alternatively, you can use the `--gtest_break_on_failure` -command line flag. - -_Availability:_ Linux, Windows, Mac. - -### Disabling Catching Test-Thrown Exceptions ### - -Google Test can be used either with or without exceptions enabled. If -a test throws a C++ exception or (on Windows) a structured exception -(SEH), by default Google Test catches it, reports it as a test -failure, and continues with the next test method. This maximizes the -coverage of a test run. Also, on Windows an uncaught exception will -cause a pop-up window, so catching the exceptions allows you to run -the tests automatically. - -When debugging the test failures, however, you may instead want the -exceptions to be handled by the debugger, such that you can examine -the call stack when an exception is thrown. To achieve that, set the -`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the -`--gtest_catch_exceptions=0` flag when running the tests. - -**Availability**: Linux, Windows, Mac. - -### Letting Another Testing Framework Drive ### - -If you work on a project that has already been using another testing -framework and is not ready to completely switch to Google Test yet, -you can get much of Google Test's benefit by using its assertions in -your existing tests. Just change your `main()` function to look -like: - -``` -#include "gtest/gtest.h" - -int main(int argc, char** argv) { - ::testing::GTEST_FLAG(throw_on_failure) = true; - // Important: Google Test must be initialized. - ::testing::InitGoogleTest(&argc, argv); - - ... whatever your existing testing framework requires ... -} -``` - -With that, you can use Google Test assertions in addition to the -native assertions your testing framework provides, for example: - -``` -void TestFooDoesBar() { - Foo foo; - EXPECT_LE(foo.Bar(1), 100); // A Google Test assertion. - CPPUNIT_ASSERT(foo.IsEmpty()); // A native assertion. -} -``` - -If a Google Test assertion fails, it will print an error message and -throw an exception, which will be treated as a failure by your host -testing framework. If you compile your code with exceptions disabled, -a failed Google Test assertion will instead exit your program with a -non-zero code, which will also signal a test failure to your test -runner. - -If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in -your `main()`, you can alternatively enable this feature by specifying -the `--gtest_throw_on_failure` flag on the command-line or setting the -`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value. - -Death tests are _not_ supported when other test framework is used to organize tests. - -_Availability:_ Linux, Windows, Mac; since v1.3.0. - -## Distributing Test Functions to Multiple Machines ## - -If you have more than one machine you can use to run a test program, -you might want to run the test functions in parallel and get the -result faster. We call this technique _sharding_, where each machine -is called a _shard_. - -Google Test is compatible with test sharding. To take advantage of -this feature, your test runner (not part of Google Test) needs to do -the following: - - 1. Allocate a number of machines (shards) to run the tests. - 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards. It must be the same for all shards. - 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. - 1. Run the same test program on all shards. When Google Test sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once. - 1. Wait for all shards to finish, then collect and report the results. - -Your project may have tests that were written without Google Test and -thus don't understand this protocol. In order for your test runner to -figure out which test supports sharding, it can set the environment -variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path. If a -test program supports sharding, it will create this file to -acknowledge the fact (the actual contents of the file are not -important at this time; although we may stick some useful information -in it in the future.); otherwise it will not create it. - -Here's an example to make it clear. Suppose you have a test program -`foo_test` that contains the following 5 test functions: -``` -TEST(A, V) -TEST(A, W) -TEST(B, X) -TEST(B, Y) -TEST(B, Z) -``` -and you have 3 machines at your disposal. To run the test functions in -parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and -set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. -Then you would run the same `foo_test` on each machine. - -Google Test reserves the right to change how the work is distributed -across the shards, but here's one possible scenario: - - * Machine #0 runs `A.V` and `B.X`. - * Machine #1 runs `A.W` and `B.Y`. - * Machine #2 runs `B.Z`. - -_Availability:_ Linux, Windows, Mac; since version 1.3.0. - -# Fusing Google Test Source Files # - -Google Test's implementation consists of ~30 files (excluding its own -tests). Sometimes you may want them to be packaged up in two files (a -`.h` and a `.cc`) instead, such that you can easily copy them to a new -machine and start hacking there. For this we provide an experimental -Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0). -Assuming you have Python 2.4 or above installed on your machine, just -go to that directory and run -``` -python fuse_gtest_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h` and `gtest/gtest-all.cc` in it. These files contain -everything you need to use Google Test. Just copy them to anywhere -you want and you are ready to write tests. You can use the -[scripts/test/Makefile](../scripts/test/Makefile) -file as an example on how to compile your tests against them. - -# Where to Go from Here # - -Congratulations! You've now learned more advanced Google Test tools and are -ready to tackle more complex testing tasks. If you want to dive even deeper, you -can read the [Frequently-Asked Questions](FAQ.md). diff --git a/googletest/docs/Documentation.md b/googletest/docs/Documentation.md index de6aaae..1b6aa4f 100644 --- a/googletest/docs/Documentation.md +++ b/googletest/docs/Documentation.md @@ -6,7 +6,7 @@ the respective git branch/tag).** * [Primer](primer.md) -- start here if you are new to Google Test. * [Samples](Samples.md) -- learn from examples. - * [AdvancedGuide](AdvancedGuide.md) -- learn more about Google Test. + * [AdvancedGuide](advanced.md) -- learn more about Google Test. * [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac. * [Frequently-Asked Questions](FAQ.md) -- check here before asking a question on the mailing list. diff --git a/googletest/docs/FAQ.md b/googletest/docs/FAQ.md index 362f81b..a886bdc 100644 --- a/googletest/docs/FAQ.md +++ b/googletest/docs/FAQ.md @@ -1,7 +1,7 @@ If you cannot find the answer to your question here, and you have read -[Primer](primer.md) and [AdvancedGuide](AdvancedGuide.md), send it to +[Primer](primer.md) and [AdvancedGuide](advanced.md), send it to googletestframework@googlegroups.com. ## Why should I use Google Test instead of my favorite C++ testing framework? ## @@ -28,11 +28,11 @@ list can help you decide whether it is for you too. * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop. * You can decide which tests to run using name patterns. This saves time when you want to quickly reproduce a test failure. * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson. - * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](AdvancedGuide.md#global-set-up-and-tear-down) and tests parameterized by [values](AdvancedGuide.md#value-parameterized-tests) or [types](docs/AdvancedGuide.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: - * expand your testing vocabulary by defining [custom predicates](AdvancedGuide.md#predicate-assertions-for-better-error-messages), - * teach Google Test how to [print your types](AdvancedGuide.md#teaching-google-test-how-to-print-your-values), - * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](AdvancedGuide.md#catching-failures), and - * reflect on the test cases or change the test output format by intercepting the [test events](AdvancedGuide.md#extending-google-test-by-handling-test-events). + * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](advanced.md#global-set-up-and-tear-down) and tests parameterized by [values](advanced.md#value-parameterized-tests) or [types](docs/advanced.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: + * expand your testing vocabulary by defining [custom predicates](advanced.md#predicate-assertions-for-better-error-messages), + * teach Google Test how to [print your types](advanced.md#teaching-google-test-how-to-print-your-values), + * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](advanced.md#catching-failures), and + * reflect on the test cases or change the test output format by intercepting the [test events](advanced.md#extending-google-test-by-handling-test-events). ## I'm getting warnings when compiling Google Test. Would you fix them? ## @@ -754,7 +754,7 @@ EXPECT_TRUE(internal::Func(12345)); ## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ## -No. You can use a feature called [value-parameterized tests](AdvancedGuide.md#Value_Parameterized_Tests) which +No. You can use a feature called [value-parameterized tests](advanced.md#Value_Parameterized_Tests) which lets you repeat your tests with different parameters, without defining it more than once. ## How do I test a file that defines main()? ## @@ -849,7 +849,7 @@ expression syntax (http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). On Windows, it uses a limited variant of regular expression syntax. For more details, see the -[regular expression syntax](AdvancedGuide.md#Regular_Expression_Syntax). +[regular expression syntax](advanced.md#Regular_Expression_Syntax). ## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ## diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md new file mode 100644 index 0000000..857967a --- /dev/null +++ b/googletest/docs/advanced.md @@ -0,0 +1,2416 @@ + + +Now that you have read [Primer](primer.md) and learned how to write tests +using Google Test, it's time to learn some new tricks. This document +will show you more assertions as well as how to construct complex +failure messages, propagate fatal failures, reuse and speed up your +test fixtures, and use various flags with your tests. + +# More Assertions # + +This section covers some less frequently used, but still significant, +assertions. + +## Explicit Success and Failure ## + +These three assertions do not actually test a value or expression. Instead, +they generate a success or failure directly. Like the macros that actually +perform a test, you may stream a custom failure message into them. + +| `SUCCEED();` | +|:-------------| + +Generates a success. This does NOT make the overall test succeed. A test is +considered successful only if none of its assertions fail during its execution. + +Note: `SUCCEED()` is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED()` messages to Google Test's +output in the future. + +| `FAIL();` | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` | +|:-----------|:-----------------|:------------------------------------------------------| + +`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal +failure. These are useful when control flow, rather than a Boolean expression, +determines the test's success or failure. For example, you might want to write +something like: + +``` +switch(expression) { + case 1: ... some checks ... + case 2: ... some other checks + ... + default: FAIL() << "We shouldn't get here."; +} +``` + +Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information. + +_Availability_: Linux, Windows, Mac. + +## Exception Assertions ## + +These are for verifying that a piece of code throws (or does not +throw) an exception of the given type: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type | +| `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type | +| `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception | + +Examples: + +``` +ASSERT_THROW(Foo(5), bar_exception); + +EXPECT_NO_THROW({ + int n = 5; + Bar(&n); +}); +``` + +_Availability_: Linux, Windows, Mac; since version 1.1.0. + +## Predicate Assertions for Better Error Messages ## + +Even though Google Test has a rich set of assertions, they can never be +complete, as it's impossible (nor a good idea) to anticipate all the scenarios +a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` +to check a complex expression, for lack of a better macro. This has the problem +of not showing you the values of the parts of the expression, making it hard to +understand what went wrong. As a workaround, some users choose to construct the +failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this +is awkward especially when the expression has side-effects or is expensive to +evaluate. + +Google Test gives you three different options to solve this problem: + +### Using an Existing Boolean Function ### + +If you already have a function or a functor that returns `bool` (or a type +that can be implicitly converted to `bool`), you can use it in a _predicate +assertion_ to get the function arguments printed for free: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true | +| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true | +| ... | ... | ... | + +In the above, _predn_ is an _n_-ary predicate function or functor, where +_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds +if the predicate returns `true` when applied to the given arguments, and fails +otherwise. When the assertion fails, it prints the value of each argument. In +either case, the arguments are evaluated exactly once. + +Here's an example. Given + +``` +// Returns true iff m and n have no common divisors except 1. +bool MutuallyPrime(int m, int n) { ... } +const int a = 3; +const int b = 4; +const int c = 10; +``` + +the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the +assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message + +
+!MutuallyPrime(b, c) is false, where
+b is 4
+c is 10
+
+ +**Notes:** + + 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](FAQ.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. + 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. + +_Availability_: Linux, Windows, Mac. + +### Using a Function That Returns an AssertionResult ### + +While `EXPECT_PRED*()` and friends are handy for a quick job, the +syntax is not satisfactory: you have to use different macros for +different arities, and it feels more like Lisp than C++. The +`::testing::AssertionResult` class solves this problem. + +An `AssertionResult` object represents the result of an assertion +(whether it's a success or a failure, and an associated message). You +can create an `AssertionResult` using one of these factory +functions: + +``` +namespace testing { + +// Returns an AssertionResult object to indicate that an assertion has +// succeeded. +AssertionResult AssertionSuccess(); + +// Returns an AssertionResult object to indicate that an assertion has +// failed. +AssertionResult AssertionFailure(); + +} +``` + +You can then use the `<<` operator to stream messages to the +`AssertionResult` object. + +To provide more readable messages in Boolean assertions +(e.g. `EXPECT_TRUE()`), write a predicate function that returns +`AssertionResult` instead of `bool`. For example, if you define +`IsEven()` as: + +``` +::testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return ::testing::AssertionSuccess(); + else + return ::testing::AssertionFailure() << n << " is odd"; +} +``` + +instead of: + +``` +bool IsEven(int n) { + return (n % 2) == 0; +} +``` + +the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: + +
+Value of: IsEven(Fib(4))
+Actual: false (*3 is odd*)
+Expected: true
+
+ +instead of a more opaque + +
+Value of: IsEven(Fib(4))
+Actual: false
+Expected: true
+
+ +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` +as well, and are fine with making the predicate slower in the success +case, you can supply a success message: + +``` +::testing::AssertionResult IsEven(int n) { + if ((n % 2) == 0) + return ::testing::AssertionSuccess() << n << " is even"; + else + return ::testing::AssertionFailure() << n << " is odd"; +} +``` + +Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print + +
+Value of: IsEven(Fib(6))
+Actual: true (8 is even)
+Expected: false
+
+ +_Availability_: Linux, Windows, Mac; since version 1.4.1. + +### Using a Predicate-Formatter ### + +If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and +`(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your +predicate do not support streaming to `ostream`, you can instead use the +following _predicate-formatter assertions_ to _fully_ customize how the +message is formatted: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful | +| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful | +| `...` | `...` | `...` | + +The difference between this and the previous two groups of macros is that instead of +a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_ +(_pred\_formatn_), which is a function or functor with the signature: + +`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);` + +where _val1_, _val2_, ..., and _valn_ are the values of the predicate +arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding +expressions as they appear in the source code. The types `T1`, `T2`, ..., and +`Tn` can be either value types or reference types. For example, if an +argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`, +whichever is appropriate. + +A predicate-formatter returns a `::testing::AssertionResult` object to indicate +whether the assertion has succeeded or not. The only way to create such an +object is to call one of these factory functions: + +As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`: + +``` +// Returns the smallest prime common divisor of m and n, +// or 1 when m and n are mutually prime. +int SmallestPrimeCommonDivisor(int m, int n) { ... } + +// A predicate-formatter for asserting that two integers are mutually prime. +::testing::AssertionResult AssertMutuallyPrime(const char* m_expr, + const char* n_expr, + int m, + int n) { + if (MutuallyPrime(m, n)) + return ::testing::AssertionSuccess(); + + return ::testing::AssertionFailure() + << m_expr << " and " << n_expr << " (" << m << " and " << n + << ") are not mutually prime, " << "as they have a common divisor " + << SmallestPrimeCommonDivisor(m, n); +} +``` + +With this predicate-formatter, we can use + +``` +EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); +``` + +to generate the message + +
+b and c (4 and 10) are not mutually prime, as they have a common divisor 2.
+
+ +As you may have realized, many of the assertions we introduced earlier are +special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are +indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. + +_Availability_: Linux, Windows, Mac. + + +## Floating-Point Comparison ## + +Comparing floating-point numbers is tricky. Due to round-off errors, it is +very unlikely that two floating-points will match exactly. Therefore, +`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points +can have a wide value range, no single fixed error bound works. It's better to +compare by a fixed relative error bound, except for values close to 0 due to +the loss of precision there. + +In general, for floating-point comparison to make sense, the user needs to +carefully choose the error bound. If they don't want or care to, comparing in +terms of Units in the Last Place (ULPs) is a good default, and Google Test +provides assertions to do this. Full details about ULPs are quite long; if you +want to learn more, see +[this article on float comparison](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +### Floating-Point Macros ### + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_FLOAT_EQ(`_val1, val2_`);` | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal | +| `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal | + +By "almost equal", we mean the two values are within 4 ULP's from each +other. + +The following assertions allow you to choose the acceptable error bound: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error | + +_Availability_: Linux, Windows, Mac. + +### Floating-Point Predicate-Format Functions ### + +Some floating-point operations are useful, but not that often used. In order +to avoid an explosion of new macros, we provide them as predicate-format +functions that can be used in predicate assertion macros (e.g. +`EXPECT_PRED_FORMAT2`, etc). + +``` +EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); +EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); +``` + +Verifies that _val1_ is less than, or almost equal to, _val2_. You can +replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. + +_Availability_: Linux, Windows, Mac. + +## Windows HRESULT assertions ## + +These assertions test for `HRESULT` success or failure. + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` | +| `ASSERT_HRESULT_FAILED(`_expression_`);` | `EXPECT_HRESULT_FAILED(`_expression_`);` | _expression_ is a failure `HRESULT` | + +The generated output contains the human-readable error message +associated with the `HRESULT` code returned by _expression_. + +You might use them like this: + +``` +CComPtr shell; +ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); +CComVariant empty; +ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); +``` + +_Availability_: Windows. + +## Type Assertions ## + +You can call the function +``` +::testing::StaticAssertTypeEq(); +``` +to assert that types `T1` and `T2` are the same. The function does +nothing if the assertion is satisfied. If the types are different, +the function call will fail to compile, and the compiler error message +will likely (depending on the compiler) show you the actual values of +`T1` and `T2`. This is mainly useful inside template code. + +_Caveat:_ When used inside a member function of a class template or a +function template, `StaticAssertTypeEq()` is effective _only if_ +the function is instantiated. For example, given: +``` +template class Foo { + public: + void Bar() { ::testing::StaticAssertTypeEq(); } +}; +``` +the code: +``` +void Test1() { Foo foo; } +``` +will _not_ generate a compiler error, as `Foo::Bar()` is never +actually instantiated. Instead, you need: +``` +void Test2() { Foo foo; foo.Bar(); } +``` +to cause a compiler error. + +_Availability:_ Linux, Windows, Mac; since version 1.3.0. + +## Assertion Placement ## + +You can use assertions in any C++ function. In particular, it doesn't +have to be a method of the test fixture class. The one constraint is +that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`) +can only be used in void-returning functions. This is a consequence of +Google Test not using exceptions. By placing it in a non-void function +you'll get a confusing compile error like +`"error: void value not ignored as it ought to be"`. + +If you need to use assertions in a function that returns non-void, one option +is to make the function return the value in an out parameter instead. For +example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You +need to make sure that `*result` contains some sensible value even when the +function returns prematurely. As the function now returns `void`, you can use +any assertion inside of it. + +If changing the function's type is not an option, you should just use +assertions that generate non-fatal failures, such as `ADD_FAILURE*` and +`EXPECT_*`. + +_Note_: Constructors and destructors are not considered void-returning +functions, according to the C++ language specification, and so you may not use +fatal assertions in them. You'll get a compilation error if you try. A simple +workaround is to transfer the entire body of the constructor or destructor to a +private void-returning method. However, you should be aware that a fatal +assertion failure in a constructor does not terminate the current test, as your +intuition might suggest; it merely returns from the constructor early, possibly +leaving your object in a partially-constructed state. Likewise, a fatal +assertion failure in a destructor may leave your object in a +partially-destructed state. Use assertions carefully in these situations! + +# Teaching Google Test How to Print Your Values # + +When a test assertion such as `EXPECT_EQ` fails, Google Test prints the +argument values to help you debug. It does this using a +user-extensible value printer. + +This printer knows how to print built-in C++ types, native arrays, STL +containers, and any type that supports the `<<` operator. For other +types, it prints the raw bytes in the value and hopes that you the +user can figure it out. + +As mentioned earlier, the printer is _extensible_. That means +you can teach it to do a better job at printing your particular type +than to dump the bytes. To do that, define `<<` for your type: + +``` +#include + +namespace foo { + +class Bar { ... }; // We want Google Test to be able to print instances of this. + +// It's important that the << operator is defined in the SAME +// namespace that defines Bar. C++'s look-up rules rely on that. +::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { + return os << bar.DebugString(); // whatever needed to print bar to os +} + +} // namespace foo +``` + +Sometimes, this might not be an option: your team may consider it bad +style to have a `<<` operator for `Bar`, or `Bar` may already have a +`<<` operator that doesn't do what you want (and you cannot change +it). If so, you can instead define a `PrintTo()` function like this: + +``` +#include + +namespace foo { + +class Bar { ... }; + +// It's important that PrintTo() is defined in the SAME +// namespace that defines Bar. C++'s look-up rules rely on that. +void PrintTo(const Bar& bar, ::std::ostream* os) { + *os << bar.DebugString(); // whatever needed to print bar to os +} + +} // namespace foo +``` + +If you have defined both `<<` and `PrintTo()`, the latter will be used +when Google Test is concerned. This allows you to customize how the value +appears in Google Test's output without affecting code that relies on the +behavior of its `<<` operator. + +If you want to print a value `x` using Google Test's value printer +yourself, just call `::testing::PrintToString(`_x_`)`, which +returns an `std::string`: + +``` +vector > bar_ints = GetBarIntVector(); + +EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) + << "bar_ints = " << ::testing::PrintToString(bar_ints); +``` + +# Death Tests # + +In many applications, there are assertions that can cause application failure +if a condition is not met. These sanity checks, which ensure that the program +is in a known good state, are there to fail at the earliest possible time after +some program state is corrupted. If the assertion checks the wrong condition, +then the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test +that such assertion statements work as expected. + +Since these precondition checks cause the processes to die, we call such tests +_death tests_. More generally, any test that checks that a program terminates +(except by throwing an exception) in an expected fashion is also a death test. + +Note that if a piece of code throws an exception, we don't consider it "death" +for the purpose of death tests, as the caller of the code could catch the exception +and avoid the crash. If you want to verify exceptions thrown by your code, +see [Exception Assertions](#exception-assertions). + +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures). + +## How to Write a Death Test ## + +Google Test has the following macros to support death tests: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error | +| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing | +| `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ | + +where _statement_ is a statement that is expected to cause the process to +die, _predicate_ is a function or function object that evaluates an integer +exit status, and _regex_ is a regular expression that the stderr output of +_statement_ is expected to match. Note that _statement_ can be _any valid +statement_ (including _compound statement_) and doesn't have to be an +expression. + +As usual, the `ASSERT` variants abort the current test function, while the +`EXPECT` variants do not. + +**Note:** We use the word "crash" here to mean that the process +terminates with a _non-zero_ exit status code. There are two +possibilities: either the process has called `exit()` or `_exit()` +with a non-zero value, or it may be killed by a signal. + +This means that if _statement_ terminates the process with a 0 exit +code, it is _not_ considered a crash by `EXPECT_DEATH`. Use +`EXPECT_EXIT` instead if this is the case, or if you want to restrict +the exit code more precisely. + +A predicate here must accept an `int` and return a `bool`. The death test +succeeds only if the predicate returns `true`. Google Test defines a few +predicates that handle the most common cases: + +``` +::testing::ExitedWithCode(exit_code) +``` + +This expression is `true` if the program exited normally with the given exit +code. + +``` +::testing::KilledBySignal(signal_number) // Not available on Windows. +``` + +This expression is `true` if the program was killed by the given signal. + +The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate +that verifies the process' exit code is non-zero. + +Note that a death test only cares about three things: + + 1. does _statement_ abort or exit the process? + 1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And + 1. does the stderr output match _regex_? + +In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process. + +To write a death test, simply use one of the above macros inside your test +function. For example, + +``` +TEST(MyDeathTest, Foo) { + // This death test uses a compound statement. + ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()"); +} +TEST(MyDeathTest, NormalExit) { + EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); +} +TEST(MyDeathTest, KillMyself) { + EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); +} +``` + +verifies that: + + * calling `Foo(5)` causes the process to die with the given error message, + * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and + * calling `KillMyself()` kills the process with signal `SIGKILL`. + +The test function body may contain other assertions and statements as well, if +necessary. + +_Important:_ We strongly recommend you to follow the convention of naming your +test case (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The `Death Tests And Threads` section below +explains why. + +If a test fixture class is shared by normal tests and death tests, you +can use typedef to introduce an alias for the fixture class and avoid +duplicating its code: +``` +class FooTest : public ::testing::Test { ... }; + +typedef FooTest FooDeathTest; + +TEST_F(FooTest, DoesThis) { + // normal test +} + +TEST_F(FooDeathTest, DoesThat) { + // death test +} +``` + +_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0). `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0. + +## Regular Expression Syntax ## + +On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the +[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) +syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). + +On Windows, Google Test uses its own simple regular expression +implementation. It lacks many features you can find in POSIX extended +regular expressions. For example, we don't support union (`"x|y"`), +grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count +(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a +literal character, period (`.`), or a single `\\` escape sequence; `x` +and `y` denote regular expressions.): + +| `c` | matches any literal character `c` | +|:----|:----------------------------------| +| `\\d` | matches any decimal digit | +| `\\D` | matches any character that's not a decimal digit | +| `\\f` | matches `\f` | +| `\\n` | matches `\n` | +| `\\r` | matches `\r` | +| `\\s` | matches any ASCII whitespace, including `\n` | +| `\\S` | matches any character that's not a whitespace | +| `\\t` | matches `\t` | +| `\\v` | matches `\v` | +| `\\w` | matches any letter, `_`, or decimal digit | +| `\\W` | matches any character that `\\w` doesn't match | +| `\\c` | matches any literal character `c`, which must be a punctuation | +| `\\.` | matches the `.` character | +| `.` | matches any single character except `\n` | +| `A?` | matches 0 or 1 occurrences of `A` | +| `A*` | matches 0 or many occurrences of `A` | +| `A+` | matches 1 or many occurrences of `A` | +| `^` | matches the beginning of a string (not that of each line) | +| `$` | matches the end of a string (not that of each line) | +| `xy` | matches `x` followed by `y` | + +To help you determine which capability is available on your system, +Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX +extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses +the simple version. If you want your death tests to work in both +cases, you can either `#if` on these macros or use the more limited +syntax only. + +## How It Works ## + +Under the hood, `ASSERT_EXIT()` spawns a new process and executes the +death test statement in that process. The details of how precisely +that happens depend on the platform and the variable +`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the +command-line flag `--gtest_death_test_style`). + + * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which: + * If the variable's value is `"fast"`, the death test statement is immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run. + * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to +fail. Currently, the flag's default value is `"fast"`. However, we reserve the +right to change it in the future. Therefore, your tests should not depend on +this. + +In either case, the parent process waits for the child process to complete, and checks that + + 1. the child's exit status satisfies the predicate, and + 1. the child's stderr matches the regular expression. + +If the death test statement runs to completion without dying, the child +process will nonetheless terminate, and the assertion fails. + +## Death Tests And Threads ## + +The reason for the two death test styles has to do with thread safety. Due to +well-known problems with forking in the presence of threads, death tests should +be run in a single-threaded context. Sometimes, however, it isn't feasible to +arrange that kind of environment. For example, statically-initialized modules +may start threads before main is ever reached. Once threads have been created, +it may be difficult or impossible to clean them up. + +Google Test has three features intended to raise awareness of threading issues. + + 1. A warning is emitted if multiple threads are running when a death test is encountered. + 1. Test cases with a name ending in "DeathTest" are run before all other tests. + 1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. + +It's perfectly fine to create threads inside a death test statement; they are +executed in a separate process and cannot affect the parent. + +## Death Test Styles ## + +The "threadsafe" death test style was introduced in order to help mitigate the +risks of testing in a possibly multithreaded environment. It trades increased +test execution time (potentially dramatically so) for improved thread safety. +We suggest using the faster, default "fast" style unless your test has specific +problems with it. + +You can choose a particular style of death tests by setting the flag +programmatically: + +``` +::testing::FLAGS_gtest_death_test_style = "threadsafe"; +``` + +You can do this in `main()` to set the style for all death tests in the +binary, or in individual tests. Recall that flags are saved before running each +test and restored afterwards, so you need not do that yourself. For example: + +``` +TEST(MyDeathTest, TestOne) { + ::testing::FLAGS_gtest_death_test_style = "threadsafe"; + // This test is run in the "threadsafe" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +TEST(MyDeathTest, TestTwo) { + // This test is run in the "fast" style: + ASSERT_DEATH(ThisShouldDie(), ""); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::FLAGS_gtest_death_test_style = "fast"; + return RUN_ALL_TESTS(); +} +``` + +## Caveats ## + +The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement. +If it leaves the current function via a `return` statement or by throwing an exception, +the death test is considered to have failed. Some Google Test macros may return +from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_. + +Since _statement_ runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will _not_ be observable +in the parent process. In particular, if you release memory in a death test, +your program will fail the heap check as the parent process will never see the +memory reclaimed. To solve this problem, you can + + 1. try not to free memory in a death test; + 1. free the memory again in the parent process; or + 1. do not use the heap checker in your program. + +Due to an implementation detail, you cannot place multiple death test +assertions on the same line; otherwise, compilation will fail with an unobvious +error message. + +Despite the improved thread safety afforded by the "threadsafe" style of death +test, thread problems such as deadlock are still possible in the presence of +handlers registered with `pthread_atfork(3)`. + +# Using Assertions in Sub-routines # + +## Adding Traces to Assertions ## + +If a test sub-routine is called from several places, when an assertion +inside it fails, it can be hard to tell which invocation of the +sub-routine the failure is from. You can alleviate this problem using +extra logging or custom failure messages, but that usually clutters up +your tests. A better solution is to use the `SCOPED_TRACE` macro or +the `ScopedTrace` utility: + +| `SCOPED_TRACE(`_message_`);` | `::testing::ScopedTrace trace(`_"file\_path"_`, `_line\_number_`, `_message_`);` | +|:-----------------------------|:---------------------------------------------------------------------------------| + +where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` +macro will cause the current file name, line number, and the given message to be +added in every failure message. `ScopedTrace` accepts explicit file name and +line number in arguments, which is useful for writing test helpers. The effect +will be undone when the control leaves the current lexical scope. + +For example, + +``` +10: void Sub1(int n) { +11: EXPECT_EQ(1, Bar(n)); +12: EXPECT_EQ(2, Bar(n + 1)); +13: } +14: +15: TEST(FooTest, Bar) { +16: { +17: SCOPED_TRACE("A"); // This trace point will be included in +18: // every failure in this scope. +19: Sub1(1); +20: } +21: // Now it won't. +22: Sub1(9); +23: } +``` + +could result in messages like these: + +``` +path/to/foo_test.cc:11: Failure +Value of: Bar(n) +Expected: 1 + Actual: 2 + Trace: +path/to/foo_test.cc:17: A + +path/to/foo_test.cc:12: Failure +Value of: Bar(n + 1) +Expected: 2 + Actual: 3 +``` + +Without the trace, it would've been difficult to know which invocation +of `Sub1()` the two failures come from respectively. (You could add an +extra message to each assertion in `Sub1()` to indicate the value of +`n`, but that's tedious.) + +Some tips on using `SCOPED_TRACE`: + + 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site. + 1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from. + 1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`. + 1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. + 1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! + +_Availability:_ Linux, Windows, Mac. + +## Propagating Fatal Failures ## + +A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that +when they fail they only abort the _current function_, not the entire test. For +example, the following test will segfault: +``` +void Subroutine() { + // Generates a fatal failure and aborts the current function. + ASSERT_EQ(1, 2); + // The following won't be executed. + ... +} + +TEST(FooTest, Bar) { + Subroutine(); + // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + // The actual behavior: the function goes on after Subroutine() returns. + int* p = NULL; + *p = 3; // Segfault! +} +``` + +To alleviate this, gUnit provides three different solutions. You could use +either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the +`HasFatalFailure()` function. They are described in the following two +subsections. + +#### Asserting on Subroutines with an exception + +The following code can turn ASSERT-failure into an exception: + +```c++ +class ThrowListener : public testing::EmptyTestEventListener { + void OnTestPartResult(const testing::TestPartResult& result) override { + if (result.type() == testing::TestPartResult::kFatalFailure) { + throw testing::AssertionException(result); + } + } +}; +int main(int argc, char** argv) { + ... + testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); + return RUN_ALL_TESTS(); +} +``` + +This listener should be added after other listeners if you have any, otherwise +they won't see failed `OnTestPartResult`. + +### Asserting on Subroutines ### + +As shown above, if your test calls a subroutine that has an `ASSERT_*` +failure in it, the test will continue after the subroutine +returns. This may not be what you want. + +Often people want fatal failures to propagate like exceptions. For +that Google Test offers the following macros: + +| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | +|:--------------------|:-----------------------|:-------------| +| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. | + +Only failures in the thread that executes the assertion are checked to +determine the result of this type of assertions. If _statement_ +creates new threads, failures in these threads are ignored. + +Examples: + +``` +ASSERT_NO_FATAL_FAILURE(Foo()); + +int i; +EXPECT_NO_FATAL_FAILURE({ + i = Bar(); +}); +``` + +_Availability:_ Linux, Windows, Mac. Assertions from multiple threads +are currently not supported. + +### Checking for Failures in the Current Test ### + +`HasFatalFailure()` in the `::testing::Test` class returns `true` if an +assertion in the current test has suffered a fatal failure. This +allows functions to catch fatal failures in a sub-routine and return +early. + +``` +class Test { + public: + ... + static bool HasFatalFailure(); +}; +``` + +The typical usage, which basically simulates the behavior of a thrown +exception, is: + +``` +TEST(FooTest, Bar) { + Subroutine(); + // Aborts if Subroutine() had a fatal failure. + if (HasFatalFailure()) + return; + // The following won't be executed. + ... +} +``` + +If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test +fixture, you must add the `::testing::Test::` prefix, as in: + +``` +if (::testing::Test::HasFatalFailure()) + return; +``` + +Similarly, `HasNonfatalFailure()` returns `true` if the current test +has at least one non-fatal failure, and `HasFailure()` returns `true` +if the current test has at least one failure of either kind. + +_Availability:_ Linux, Windows, Mac. `HasNonfatalFailure()` and +`HasFailure()` are available since version 1.4.0. + +# Logging Additional Information # + +In your test code, you can call `RecordProperty("key", value)` to log +additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output +if you specify one. For example, the test + +``` +TEST_F(WidgetUsageTest, MinAndMaxWidgets) { + RecordProperty("MaximumWidgets", ComputeMaxUsage()); + RecordProperty("MinimumWidgets", ComputeMinUsage()); +} +``` + +will output XML like this: + +``` +... + +... +``` + +_Note_: + * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class. + * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`). + * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element. + +_Availability_: Linux, Windows, Mac. + +# Sharing Resources Between Tests in the Same Test Case # + + + +Google Test creates a new test fixture object for each test in order to make +tests independent and easier to debug. However, sometimes tests use resources +that are expensive to set up, making the one-copy-per-test model prohibitively +expensive. + +If the tests don't change the resource, there's no harm in them sharing a +single resource copy. So, in addition to per-test set-up/tear-down, Google Test +also supports per-test-case set-up/tear-down. To use it: + + 1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources. + 1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down. + +That's it! Google Test automatically calls `SetUpTestCase()` before running the +_first test_ in the `FooTest` test case (i.e. before creating the first +`FooTest` object), and calls `TearDownTestCase()` after running the _last test_ +in it (i.e. after deleting the last `FooTest` object). In between, the tests +can use the shared resources. + +Remember that the test order is undefined, so your code can't depend on a test +preceding or following another. Also, the tests must either not modify the +state of any shared resource, or, if they do modify the state, they must +restore the state to its original value before passing control to the next +test. + +Here's an example of per-test-case set-up and tear-down: +``` +class FooTest : public ::testing::Test { + protected: + // Per-test-case set-up. + // Called before the first test in this test case. + // Can be omitted if not needed. + static void SetUpTestCase() { + shared_resource_ = new ...; + } + + // Per-test-case tear-down. + // Called after the last test in this test case. + // Can be omitted if not needed. + static void TearDownTestCase() { + delete shared_resource_; + shared_resource_ = NULL; + } + + // You can define per-test set-up and tear-down logic as usual. + virtual void SetUp() { ... } + virtual void TearDown() { ... } + + // Some expensive resource shared by all tests. + static T* shared_resource_; +}; + +T* FooTest::shared_resource_ = NULL; + +TEST_F(FooTest, Test1) { + ... you can refer to shared_resource here ... +} +TEST_F(FooTest, Test2) { + ... you can refer to shared_resource here ... +} +``` + +_Availability:_ Linux, Windows, Mac. + +# Global Set-Up and Tear-Down # + +Just as you can do set-up and tear-down at the test level and the test case +level, you can also do it at the test program level. Here's how. + +First, you subclass the `::testing::Environment` class to define a test +environment, which knows how to set-up and tear-down: + +``` +class Environment { + public: + virtual ~Environment() {} + // Override this to define how to set up the environment. + virtual void SetUp() {} + // Override this to define how to tear down the environment. + virtual void TearDown() {} +}; +``` + +Then, you register an instance of your environment class with Google Test by +calling the `::testing::AddGlobalTestEnvironment()` function: + +``` +Environment* AddGlobalTestEnvironment(Environment* env); +``` + +Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of +the environment object, then runs the tests if there was no fatal failures, and +finally calls `TearDown()` of the environment object. + +It's OK to register multiple environment objects. In this case, their `SetUp()` +will be called in the order they are registered, and their `TearDown()` will be +called in the reverse order. + +Note that Google Test takes ownership of the registered environment objects. +Therefore **do not delete them** by yourself. + +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is +called, probably in `main()`. If you use `gtest_main`, you need to call +this before `main()` starts for it to take effect. One way to do this is to +define a global variable like this: + +``` +::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); +``` + +However, we strongly recommend you to write your own `main()` and call +`AddGlobalTestEnvironment()` there, as relying on initialization of global +variables makes the code harder to read and may cause problems when you +register multiple environments from different translation units and the +environments have dependencies among them (remember that the compiler doesn't +guarantee the order in which global variables from different translation units +are initialized). + +_Availability:_ Linux, Windows, Mac. + + +# Value Parameterized Tests # + +_Value-parameterized tests_ allow you to test your code with different +parameters without writing multiple copies of the same test. + +Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag. + +``` +TEST(MyCodeTest, TestFoo) { + // A code to test foo(). +} +``` + +Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code. + +``` +void TestFooHelper(bool flag_value) { + flag = flag_value; + // A code to test foo(). +} + +TEST(MyCodeTest, TestFoo) { + TestFooHelper(false); + TestFooHelper(true); +} +``` + +But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred? + +Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values. + +Here are some other situations when value-parameterized tests come handy: + + * You want to test different implementations of an OO interface. + * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! + +## How to Write Value-Parameterized Tests ## + +To write value-parameterized tests, first you should define a fixture +class. It must be derived from both `::testing::Test` and +`::testing::WithParamInterface` (the latter is a pure interface), +where `T` is the type of your parameter values. For convenience, you +can just derive the fixture class from `::testing::TestWithParam`, +which itself is derived from both `::testing::Test` and +`::testing::WithParamInterface`. `T` can be any copyable type. If +it's a raw pointer, you are responsible for managing the lifespan of +the pointed values. + +``` +class FooTest : public ::testing::TestWithParam { + // You can implement all the usual fixture class members here. + // To access the test parameter, call GetParam() from class + // TestWithParam. +}; + +// Or, when you want to add parameters to a pre-existing fixture class: +class BaseTest : public ::testing::Test { + ... +}; +class BarTest : public BaseTest, + public ::testing::WithParamInterface { + ... +}; +``` + +Then, use the `TEST_P` macro to define as many test patterns using +this fixture as you want. The `_P` suffix is for "parameterized" or +"pattern", whichever you prefer to think. + +``` +TEST_P(FooTest, DoesBlah) { + // Inside a test, access the test parameter with the GetParam() method + // of the TestWithParam class: + EXPECT_TRUE(foo.Blah(GetParam())); + ... +} + +TEST_P(FooTest, HasBlahBlah) { + ... +} +``` + +Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test +case with any set of parameters you want. Google Test defines a number of +functions for generating test parameters. They return what we call +(surprise!) _parameter generators_. Here is a summary of them, +which are all in the `testing` namespace: + +| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | +|:----------------------------|:------------------------------------------------------------------------------------------------------------------| +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time. | +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](../include/gtest/internal/gtest-port.h) for more information. | + +For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h). + +The following statement will instantiate tests from the `FooTest` test case +each with parameter values `"meeny"`, `"miny"`, and `"moe"`. + +``` +INSTANTIATE_TEST_CASE_P(InstantiationName, + FooTest, + ::testing::Values("meeny", "miny", "moe")); +``` + +To distinguish different instances of the pattern (yes, you can +instantiate it more than once), the first argument to +`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual +test case name. Remember to pick unique prefixes for different +instantiations. The tests from the instantiation above will have these +names: + + * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` + * `InstantiationName/FooTest.DoesBlah/1` for `"miny"` + * `InstantiationName/FooTest.DoesBlah/2` for `"moe"` + * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` + * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` + * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` + +You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests). + +This statement will instantiate all tests from `FooTest` again, each +with parameter values `"cat"` and `"dog"`: + +``` +const char* pets[] = {"cat", "dog"}; +INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, + ::testing::ValuesIn(pets)); +``` + +The tests from the instantiation above will have these names: + + * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` + * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` + * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` + * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` + +Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_ +tests in the given test case, whether their definitions come before or +_after_ the `INSTANTIATE_TEST_CASE_P` statement. + +You can see +[these](../samples/sample7_unittest.cc) +[files](../samples/sample8_unittest.cc) for more examples. + +_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0. + +## Creating Value-Parameterized Abstract Tests ## + +In the above, we define and instantiate `FooTest` in the same source +file. Sometimes you may want to define value-parameterized tests in a +library and let other people instantiate them later. This pattern is +known as abstract tests. As an example of its application, when you +are designing an interface you can write a standard suite of abstract +tests (perhaps using a factory function as the test parameter) that +all implementations of the interface are expected to pass. When +someone implements the interface, they can instantiate your suite to get +all the interface-conformance tests for free. + +To define abstract tests, you should organize your code like this: + + 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests. + 1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests. + +Once they are defined, you can instantiate them by including +`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking +with `foo_param_test.cc`. You can instantiate the same abstract test +case multiple times, possibly in different source files. + +# Typed Tests # + +Suppose you have multiple implementations of the same interface and +want to make sure that all of them satisfy some common requirements. +Or, you may have defined several types that are supposed to conform to +the same "concept" and you want to verify it. In both cases, you want +the same test logic repeated for different types. + +While you can write one `TEST` or `TEST_F` for each type you want to +test (and you may even factor the test logic into a function template +that you invoke from the `TEST`), it's tedious and doesn't scale: +if you want _m_ tests over _n_ types, you'll end up writing _m\*n_ +`TEST`s. + +_Typed tests_ allow you to repeat the same test logic over a list of +types. You only need to write the test logic once, although you must +know the type list when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized +by a type. Remember to derive it from `::testing::Test`: + +``` +template +class FooTest : public ::testing::Test { + public: + ... + typedef std::list List; + static T shared_; + T value_; +}; +``` + +Next, associate a list of types with the test case, which will be +repeated for each type in the list: + +``` +typedef ::testing::Types MyTypes; +TYPED_TEST_CASE(FooTest, MyTypes); +``` + +The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse +correctly. Otherwise the compiler will think that each comma in the +type list introduces a new macro argument. + +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test +for this test case. You can repeat this as many times as you want: + +``` +TYPED_TEST(FooTest, DoesBlah) { + // Inside a test, refer to the special name TypeParam to get the type + // parameter. Since we are inside a derived class template, C++ requires + // us to visit the members of FooTest via 'this'. + TypeParam n = this->value_; + + // To visit static members of the fixture, add the 'TestFixture::' + // prefix. + n += TestFixture::shared_; + + // To refer to typedefs in the fixture, add the 'typename TestFixture::' + // prefix. The 'typename' is required to satisfy the compiler. + typename TestFixture::List values; + values.push_back(n); + ... +} + +TYPED_TEST(FooTest, HasPropertyA) { ... } +``` + +You can see [`samples/sample6_unittest.cc`](../samples/sample6_unittest.cc) for a complete example. + +_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; +since version 1.1.0. + +# Type-Parameterized Tests # + +_Type-parameterized tests_ are like typed tests, except that they +don't require you to know the list of types ahead of time. Instead, +you can define the test logic first and instantiate it with different +type lists later. You can even instantiate it more than once in the +same program. + +If you are designing an interface or concept, you can define a suite +of type-parameterized tests to verify properties that any valid +implementation of the interface/concept should have. Then, the author +of each implementation can just instantiate the test suite with his +type to verify that it conforms to the requirements, without having to +write similar tests repeatedly. Here's an example: + +First, define a fixture class template, as we did with typed tests: + +``` +template +class FooTest : public ::testing::Test { + ... +}; +``` + +Next, declare that you will define a type-parameterized test case: + +``` +TYPED_TEST_CASE_P(FooTest); +``` + +The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. + +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You +can repeat this as many times as you want: + +``` +TYPED_TEST_P(FooTest, DoesBlah) { + // Inside a test, refer to TypeParam to get the type parameter. + TypeParam n = 0; + ... +} + +TYPED_TEST_P(FooTest, HasPropertyA) { ... } +``` + +Now the tricky part: you need to register all test patterns using the +`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. +The first argument of the macro is the test case name; the rest are +the names of the tests in this test case: + +``` +REGISTER_TYPED_TEST_CASE_P(FooTest, + DoesBlah, HasPropertyA); +``` + +Finally, you are free to instantiate the pattern with the types you +want. If you put the above code in a header file, you can `#include` +it in multiple C++ source files and instantiate it multiple times. + +``` +typedef ::testing::Types MyTypes; +INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); +``` + +To distinguish different instances of the pattern, the first argument +to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be +added to the actual test case name. Remember to pick unique prefixes +for different instances. + +In the special case where the type list contains only one type, you +can write that type directly without `::testing::Types<...>`, like this: + +``` +INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); +``` + +You can see `samples/sample6_unittest.cc` for a complete example. + +_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; +since version 1.1.0. + +# Testing Private Code # + +If you change your software's internal implementation, your tests should not +break as long as the change is not observable by users. Therefore, per the +_black-box testing principle_, most of the time you should test your code +through its public interfaces. + +If you still find yourself needing to test internal implementation code, +consider if there's a better design that wouldn't require you to do so. If you +absolutely have to test non-public interface code though, you can. There are +two cases to consider: + + * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and + * Private or protected class members. + +## Static Functions ## + +Both static functions and definitions/declarations in an unnamed namespace are +only visible within the same translation unit. To test them, you can `#include` +the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc` +files is not a good way to reuse code - you should not do this in production +code!) + +However, a better approach is to move the private code into the +`foo::internal` namespace, where `foo` is the namespace your project normally +uses, and put the private declarations in a `*-internal.h` file. Your +production `.cc` files and your tests are allowed to include this internal +header, but your clients are not. This way, you can fully test your internal +implementation without leaking it to your clients. + +## Private Class Members ## + +Private class members are only accessible from within the class or by friends. +To access a class' private members, you can declare your test fixture as a +friend to the class and define accessors in your fixture. Tests using the +fixture can then access the private members of your production class via the +accessors in the fixture. Note that even though your fixture is a friend to +your production class, your tests are not automatically friends to it, as they +are technically defined in sub-classes of the fixture. + +Another way to test private members is to refactor them into an implementation +class, which is then declared in a `*-internal.h` file. Your clients aren't +allowed to include this header but your tests can. Such is called the Pimpl +(Private Implementation) idiom. + +Or, you can declare an individual test as a friend of your class by adding this +line in the class body: + +``` +FRIEND_TEST(TestCaseName, TestName); +``` + +For example, +``` +// foo.h +#include "gtest/gtest_prod.h" + +// Defines FRIEND_TEST. +class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); + int Bar(void* x); +}; + +// foo_test.cc +... +TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(0, foo.Bar(NULL)); + // Uses Foo's private member Bar(). +} +``` + +Pay special attention when your class is defined in a namespace, as you should +define your test fixtures and tests in the same namespace if you want them to +be friends of your class. For example, if the code to be tested looks like: + +``` +namespace my_namespace { + +class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... + definition of the class Foo + ... +}; + +} // namespace my_namespace +``` + +Your test code should be something like: + +``` +namespace my_namespace { +class FooTest : public ::testing::Test { + protected: + ... +}; + +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +} // namespace my_namespace +``` + +# Catching Failures # + +If you are building a testing utility on top of Google Test, you'll +want to test your utility. What framework would you use to test it? +Google Test, of course. + +The challenge is to verify that your testing utility reports failures +correctly. In frameworks that report a failure by throwing an +exception, you could catch the exception and assert on it. But Google +Test doesn't use exceptions, so how do we test that a piece of code +generates an expected failure? + +`"gtest/gtest-spi.h"` contains some constructs to do this. After +`#include`ing this header, you can use + +| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` | +|:--------------------------------------------------| + +to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure +whose message contains the given _substring_, or use + +| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` | +|:-----------------------------------------------------| + +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. + +For technical reasons, there are some caveats: + + 1. You cannot stream a failure message to either macro. + 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object. + 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value. + +_Note:_ Google Test is designed with threads in mind. Once the +synchronization primitives in `"gtest/internal/gtest-port.h"` have +been implemented, Google Test will become thread-safe, meaning that +you can then use assertions in multiple threads concurrently. Before +that, however, Google Test only supports single-threaded usage. Once +thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()` +will capture failures in the current thread only. If _statement_ +creates new threads, failures in these threads will be ignored. If +you want to capture failures from all threads instead, you should use +the following macros: + +| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | +|:-----------------------------------------------------------------| +| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | + +# Getting the Current Test's Name # + +Sometimes a function may need to know the name of the currently running test. +For example, you may be using the `SetUp()` method of your test fixture to set +the golden file name based on which test is running. The `::testing::TestInfo` +class has this information: + +``` +namespace testing { + +class TestInfo { + public: + // Returns the test case name and the test name, respectively. + // + // Do NOT delete or free the return value - it's managed by the + // TestInfo class. + const char* test_case_name() const; + const char* name() const; +}; + +} // namespace testing +``` + + +> To obtain a `TestInfo` object for the currently running test, call +`current_test_info()` on the `UnitTest` singleton object: + +``` +// Gets information about the currently running test. +// Do NOT delete the returned object - it's managed by the UnitTest class. +const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); +printf("We are in test %s of test case %s.\n", + test_info->name(), test_info->test_case_name()); +``` + +`current_test_info()` returns a null pointer if no test is running. In +particular, you cannot find the test case name in `SetUpTestCase()`, +`TearDownTestCase()` (where you know the test case name implicitly), or +functions called from them. + +_Availability:_ Linux, Windows, Mac. + +# Extending Google Test by Handling Test Events # + +Google Test provides an event listener API to let you receive +notifications about the progress of a test program and test +failures. The events you can listen to include the start and end of +the test program, a test case, or a test method, among others. You may +use this API to augment or replace the standard console output, +replace the XML output, or provide a completely different form of +output, such as a GUI or a database. You can also use test events as +checkpoints to implement a resource leak checker, for example. + +_Availability:_ Linux, Windows, Mac; since v1.4.0. + +## Defining Event Listeners ## + +To define a event listener, you subclass either +[testing::TestEventListener](../include/gtest/gtest.h#L991) +or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L1044). +The former is an (abstract) interface, where each pure virtual method
+can be overridden to handle a test event
(For example, when a test +starts, the `OnTestStart()` method will be called.). The latter provides +an empty implementation of all methods in the interface, such that a +subclass only needs to override the methods it cares about. + +When an event is fired, its context is passed to the handler function +as an argument. The following argument types are used: + * [UnitTest](../include/gtest/gtest.h#L1151) reflects the state of the entire test program, + * [TestCase](../include/gtest/gtest.h#L778) has information about a test case, which can contain one or more tests, + * [TestInfo](../include/gtest/gtest.h#L644) contains the state of a test, and + * [TestPartResult](../include/gtest/gtest-test-part.h#L47) represents the result of a test assertion. + +An event handler function can examine the argument it receives to find +out interesting information about the event and the test program's +state. Here's an example: + +``` + class MinimalistPrinter : public ::testing::EmptyTestEventListener { + // Called before a test starts. + virtual void OnTestStart(const ::testing::TestInfo& test_info) { + printf("*** Test %s.%s starting.\n", + test_info.test_case_name(), test_info.name()); + } + + // Called after a failed assertion or a SUCCEED() invocation. + virtual void OnTestPartResult( + const ::testing::TestPartResult& test_part_result) { + printf("%s in %s:%d\n%s\n", + test_part_result.failed() ? "*** Failure" : "Success", + test_part_result.file_name(), + test_part_result.line_number(), + test_part_result.summary()); + } + + // Called after a test ends. + virtual void OnTestEnd(const ::testing::TestInfo& test_info) { + printf("*** Test %s.%s ending.\n", + test_info.test_case_name(), test_info.name()); + } + }; +``` + +## Using Event Listeners ## + +To use the event listener you have defined, add an instance of it to +the Google Test event listener list (represented by class +[TestEventListeners](../include/gtest/gtest.h#L1064) +- note the "s" at the end of the name) in your +`main()` function, before calling `RUN_ALL_TESTS()`: +``` +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + // Gets hold of the event listener list. + ::testing::TestEventListeners& listeners = + ::testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. Google Test takes the ownership. + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +} +``` + +There's only one problem: the default test result printer is still in +effect, so its output will mingle with the output from your minimalist +printer. To suppress the default printer, just release it from the +event listener list and delete it. You can do so by adding one line: +``` + ... + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new MinimalistPrinter); + return RUN_ALL_TESTS(); +``` + +Now, sit back and enjoy a completely different output from your +tests. For more details, you can read this +[sample](../samples/sample9_unittest.cc). + +You may append more than one listener to the list. When an `On*Start()` +or `OnTestPartResult()` event is fired, the listeners will receive it in +the order they appear in the list (since new listeners are added to +the end of the list, the default text printer and the default XML +generator will receive the event first). An `On*End()` event will be +received by the listeners in the _reverse_ order. This allows output by +listeners added later to be framed by output from listeners added +earlier. + +## Generating Failures in Listeners ## + +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, +`FAIL()`, etc) when processing an event. There are some restrictions: + + 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively). + 1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure. + +When you add listeners to the listener list, you should put listeners +that handle `OnTestPartResult()` _before_ listeners that can generate +failures. This ensures that failures generated by the latter are +attributed to the right test by the former. + +We have a sample of failure-raising listener +[here](../samples/sample10_unittest.cc). + +# Running Test Programs: Advanced Options # + +Google Test test programs are ordinary executables. Once built, you can run +them directly and affect their behavior via the following environment variables +and/or command line flags. For the flags to work, your programs must call +`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. + +To see a list of supported flags and their usage, please run your test +program with the `--help` flag. You can also use `-h`, `-?`, or `/?` +for short. This feature is added in version 1.3.0. + +If an option is specified both by an environment variable and by a +flag, the latter takes precedence. Most of the options can also be +set/read in code: to access the value of command line flag +`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`. A common pattern is +to set the value of a flag before calling `::testing::InitGoogleTest()` +to change the default value of the flag: +``` +int main(int argc, char** argv) { + // Disables elapsed time by default. + ::testing::GTEST_FLAG(print_time) = false; + + // This allows the user to override the flag on the command line. + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} +``` + +## Selecting Tests ## + +This section shows various options for choosing which tests to run. + +### Listing Test Names ### + +Sometimes it is necessary to list the available tests in a program before +running them so that a filter may be applied if needed. Including the flag +`--gtest_list_tests` overrides all other flags and lists tests in the following +format: +``` +TestCase1. + TestName1 + TestName2 +TestCase2. + TestName +``` + +None of the tests listed are actually run if the flag is provided. There is no +corresponding environment variable for this flag. + +_Availability:_ Linux, Windows, Mac. + +### Running a Subset of the Tests ### + +By default, a Google Test program runs all tests the user has defined. +Sometimes, you want to run only a subset of the tests (e.g. for debugging or +quickly verifying a change). If you set the `GTEST_FILTER` environment variable +or the `--gtest_filter` flag to a filter string, Google Test will only run the +tests whose full names (in the form of `TestCaseName.TestName`) match the +filter. + +The format of a filter is a '`:`'-separated list of wildcard patterns (called +the positive patterns) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the negative patterns). A test matches the +filter if and only if it matches any of the positive patterns but does not +match any of the negative patterns. + +A pattern may contain `'*'` (matches any string) or `'?'` (matches any single +character). For convenience, the filter `'*-NegativePatterns'` can be also +written as `'-NegativePatterns'`. + +For example: + + * `./foo_test` Has no flag, and thus runs all its tests. + * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. + * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`. + * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`. + * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. + * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`. + +_Availability:_ Linux, Windows, Mac. + +### Temporarily Disabling Tests ### + +If you have a broken test that you cannot fix right away, you can add the +`DISABLED_` prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using `#if 0`, as disabled tests are +still compiled (and thus won't rot). + +If you need to disable all tests in a test case, you can either add `DISABLED_` +to the front of the name of each test, or alternatively add it to the front of +the test case name. + +For example, the following tests won't be run by Google Test, even though they +will still be compiled: + +``` +// Tests that Foo does Abc. +TEST(FooTest, DISABLED_DoesAbc) { ... } + +class DISABLED_BarTest : public ::testing::Test { ... }; + +// Tests that Bar does Xyz. +TEST_F(DISABLED_BarTest, DoesXyz) { ... } +``` + +_Note:_ This feature should only be used for temporary pain-relief. You still +have to fix the disabled tests at a later date. As a reminder, Google Test will +print a banner warning you if a test program contains any disabled tests. + +_Tip:_ You can easily count the number of disabled tests you have +using `grep`. This number can be used as a metric for improving your +test quality. + +_Availability:_ Linux, Windows, Mac. + +### Temporarily Enabling Disabled Tests ### + +To include [disabled tests](#temporarily-disabling-tests) in test +execution, just invoke the test program with the +`--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other +than `0`. You can combine this with the +[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select +which disabled tests to run. + +_Availability:_ Linux, Windows, Mac; since version 1.3.0. + +## Repeating the Tests ## + +Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it +will fail only 1% of the time, making it rather hard to reproduce the bug under +a debugger. This can be a major source of frustration. + +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods +in a program many times. Hopefully, a flaky test will eventually fail and give +you a chance to debug. Here's how to use it: + +| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. | +|:---------------------------------|:--------------------------------------------------------| +| `$ foo_test --gtest_repeat=-1` | A negative count means repeating forever. | +| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. | +| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. | + +If your test program contains global set-up/tear-down code registered +using `AddGlobalTestEnvironment()`, it will be repeated in each +iteration as well, as the flakiness may be in it. You can also specify +the repeat count by setting the `GTEST_REPEAT` environment variable. + +_Availability:_ Linux, Windows, Mac. + +## Shuffling the Tests ## + +You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` +environment variable to `1`) to run the tests in a program in a random +order. This helps to reveal bad dependencies between tests. + +By default, Google Test uses a random seed calculated from the current +time. Therefore you'll get a different order every time. The console +output includes the random seed value, such that you can reproduce an +order-related test failure later. To specify the random seed +explicitly, use the `--gtest_random_seed=SEED` flag (or set the +`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer +between 0 and 99999. The seed value 0 is special: it tells Google Test +to do the default behavior of calculating the seed from the current +time. + +If you combine this with `--gtest_repeat=N`, Google Test will pick a +different random seed and re-shuffle the tests in each iteration. + +_Availability:_ Linux, Windows, Mac; since v1.4.0. + +## Controlling Test Output ## + +This section teaches how to tweak the way test results are reported. + +### Colored Terminal Output ### + +Google Test can use colors in its terminal output to make it easier to spot +the separation between tests, and whether tests passed. + +You can set the GTEST\_COLOR environment variable or set the `--gtest_color` +command line flag to `yes`, `no`, or `auto` (the default) to enable colors, +disable colors, or let Google Test decide. When the value is `auto`, Google +Test 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`. + +_Availability:_ Linux, Windows, Mac. + +### Suppressing the Elapsed Time ### + +By default, Google Test prints the time it takes to run each test. To +suppress that, run the test program with the `--gtest_print_time=0` +command line flag. Setting the `GTEST_PRINT_TIME` environment +variable to `0` has the same effect. + +_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, +the default behavior is that the elapsed time is **not** printed.) + +**Availability**: Linux, Windows, Mac. + +#### Suppressing UTF-8 Text Output + +In case of assertion failures, gUnit prints expected and actual values of type +`string` both as hex-encoded strings as well as in readable UTF-8 text if they +contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 text +because, for example, you don't have an UTF-8 compatible output medium, run the +test program with `--gunit_print_utf8=0` or set the `GUNIT_PRINT_UTF8` +environment variable to `0`. + +### Generating an XML Report ### + +Google Test 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. + +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 +create the file at the given location. You can also just use the string +`"xml"`, in which case the output can be found in the `test_detail.xml` file in +the current directory. + +If you specify a directory (for example, `"xml:output/directory/"` on Linux or +`"xml:output\directory\"` on Windows), Google Test will create the XML file in +that directory, named after the test executable (e.g. `foo_test.xml` for test +program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left +over from a previous run), Google Test will pick a different name (e.g. +`foo_test_1.xml`) to avoid overwriting it. + +The report uses the format described here. It is based on the +`junitreport` Ant task and can be parsed by popular continuous build +systems like [Hudson](https://hudson.dev.java.net/). Since that format +was originally intended for Java, a little interpretation is required +to make it apply to Google Test tests, as shown here: + +``` + + + + + + + + + +``` + + * The root `` element corresponds to the entire test program. + * `` elements correspond to Google Test test cases. + * `` elements correspond to Google Test test functions. + +For instance, the following program + +``` +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +``` + + + + + + + + + + + + + + + +``` + +Things to note: + + * The `tests` attribute of a `` or `` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed. + * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds. + * Each `` element corresponds to a single failed Google Test assertion. + * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts. + +_Availability:_ Linux, Windows, Mac. + +#### Generating an JSON Report {#JsonReport} + +gUnit can also emit a JSON report as an alternative format to XML. To generate +the JSON report, set the `GUNIT_OUTPUT` environment variable or the +`--gunit_output` flag to the string `"json:path_to_output_file"`, which will +create the file at the given location. You can also just use the string +`"json"`, in which case the output can be found in the `test_detail.json` file +in the current directory. + +The report format conforms to the following JSON Schema: + +```json +{ + "$schema": "http://json-schema.org/schema#", + "type": "object", + "definitions": { + "TestCase": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "time": { "type": "string" }, + "testsuite": { + "type": "array", + "items": { + "$ref": "#/definitions/TestInfo" + } + } + } + }, + "TestInfo": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "status": { + "type": "string", + "enum": ["RUN", "NOTRUN"] + }, + "time": { "type": "string" }, + "classname": { "type": "string" }, + "failures": { + "type": "array", + "items": { + "$ref": "#/definitions/Failure" + } + } + } + }, + "Failure": { + "type": "object", + "properties": { + "failures": { "type": "string" }, + "type": { "type": "string" } + } + } + }, + "properties": { + "tests": { "type": "integer" }, + "failures": { "type": "integer" }, + "disabled": { "type": "integer" }, + "errors": { "type": "integer" }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "time": { "type": "string" }, + "name": { "type": "string" }, + "testsuites": { + "type": "array", + "items": { + "$ref": "#/definitions/TestCase" + } + } + } +} +``` + +The report uses the format that conforms to the following Proto3 using the +[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): + +```proto +syntax = "proto3"; + +package googletest; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; + +message UnitTest { + int32 tests = 1; + int32 failures = 2; + int32 disabled = 3; + int32 errors = 4; + google.protobuf.Timestamp timestamp = 5; + google.protobuf.Duration time = 6; + string name = 7; + repeated TestCase testsuites = 8; +} + +message TestCase { + string name = 1; + int32 tests = 2; + int32 failures = 3; + int32 disabled = 4; + int32 errors = 5; + google.protobuf.Duration time = 6; + repeated TestInfo testsuite = 7; +} + +message TestInfo { + string name = 1; + enum Status { + RUN = 0; + NOTRUN = 1; + } + Status status = 2; + google.protobuf.Duration time = 3; + string classname = 4; + message Failure { + string failures = 1; + string type = 2; + } + repeated Failure failures = 5; +} +``` + +For instance, the following program + +```c++ +TEST(MathTest, Addition) { ... } +TEST(MathTest, Subtraction) { ... } +TEST(LogicTest, NonContradiction) { ... } +``` + +could generate this report: + +```json +{ + "tests": 3, + "failures": 1, + "errors": 0, + "time": "0.035s", + "timestamp": "2011-10-31T18:52:42Z" + "name": "AllTests", + "testsuites": [ + { + "name": "MathTest", + "tests": 2, + "failures": 1, + "errors": 0, + "time": "0.015s", + "testsuite": [ + { + "name": "Addition", + "status": "RUN", + "time": "0.007s", + "classname": "", + "failures": [ + { + "message": "Value of: add(1, 1)\x0A Actual: 3\x0AExpected: 2", + "type": "" + }, + { + "message": "Value of: add(1, -1)\x0A Actual: 1\x0AExpected: 0", + "type": "" + } + ] + }, + { + "name": "Subtraction", + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + } + { + "name": "LogicTest", + "tests": 1, + "failures": 0, + "errors": 0, + "time": "0.005s", + "testsuite": [ + { + "name": "NonContradiction", + "status": "RUN", + "time": "0.005s", + "classname": "" + } + ] + } + ] +} +``` + +IMPORTANT: The exact format of the JSON document is subject to change. + +**Availability**: Linux, Windows, Mac. + +## Controlling How Failures Are Reported ## + +### Turning Assertion Failures into Break-Points ### + +When running test programs under a debugger, it's very convenient if the +debugger can catch an assertion failure and automatically drop into interactive +mode. Google Test's _break-on-failure_ mode supports this behavior. + +To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value +other than `0` . Alternatively, you can use the `--gtest_break_on_failure` +command line flag. + +_Availability:_ Linux, Windows, Mac. + +### Disabling Catching Test-Thrown Exceptions ### + +Google Test can be used either with or without exceptions enabled. If +a test throws a C++ exception or (on Windows) a structured exception +(SEH), by default Google Test catches it, reports it as a test +failure, and continues with the next test method. This maximizes the +coverage of a test run. Also, on Windows an uncaught exception will +cause a pop-up window, so catching the exceptions allows you to run +the tests automatically. + +When debugging the test failures, however, you may instead want the +exceptions to be handled by the debugger, such that you can examine +the call stack when an exception is thrown. To achieve that, set the +`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the +`--gtest_catch_exceptions=0` flag when running the tests. + +**Availability**: Linux, Windows, Mac. + +### Letting Another Testing Framework Drive ### + +If you work on a project that has already been using another testing +framework and is not ready to completely switch to Google Test yet, +you can get much of Google Test's benefit by using its assertions in +your existing tests. Just change your `main()` function to look +like: + +``` +#include "gtest/gtest.h" + +int main(int argc, char** argv) { + ::testing::GTEST_FLAG(throw_on_failure) = true; + // Important: Google Test must be initialized. + ::testing::InitGoogleTest(&argc, argv); + + ... whatever your existing testing framework requires ... +} +``` + +With that, you can use Google Test assertions in addition to the +native assertions your testing framework provides, for example: + +``` +void TestFooDoesBar() { + Foo foo; + EXPECT_LE(foo.Bar(1), 100); // A Google Test assertion. + CPPUNIT_ASSERT(foo.IsEmpty()); // A native assertion. +} +``` + +If a Google Test assertion fails, it will print an error message and +throw an exception, which will be treated as a failure by your host +testing framework. If you compile your code with exceptions disabled, +a failed Google Test assertion will instead exit your program with a +non-zero code, which will also signal a test failure to your test +runner. + +If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in +your `main()`, you can alternatively enable this feature by specifying +the `--gtest_throw_on_failure` flag on the command-line or setting the +`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value. + +Death tests are _not_ supported when other test framework is used to organize tests. + +_Availability:_ Linux, Windows, Mac; since v1.3.0. + +## Distributing Test Functions to Multiple Machines ## + +If you have more than one machine you can use to run a test program, +you might want to run the test functions in parallel and get the +result faster. We call this technique _sharding_, where each machine +is called a _shard_. + +Google Test is compatible with test sharding. To take advantage of +this feature, your test runner (not part of Google Test) needs to do +the following: + + 1. Allocate a number of machines (shards) to run the tests. + 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards. It must be the same for all shards. + 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. + 1. Run the same test program on all shards. When Google Test sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once. + 1. Wait for all shards to finish, then collect and report the results. + +Your project may have tests that were written without Google Test and +thus don't understand this protocol. In order for your test runner to +figure out which test supports sharding, it can set the environment +variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path. If a +test program supports sharding, it will create this file to +acknowledge the fact (the actual contents of the file are not +important at this time; although we may stick some useful information +in it in the future.); otherwise it will not create it. + +Here's an example to make it clear. Suppose you have a test program +`foo_test` that contains the following 5 test functions: +``` +TEST(A, V) +TEST(A, W) +TEST(B, X) +TEST(B, Y) +TEST(B, Z) +``` +and you have 3 machines at your disposal. To run the test functions in +parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and +set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. +Then you would run the same `foo_test` on each machine. + +Google Test reserves the right to change how the work is distributed +across the shards, but here's one possible scenario: + + * Machine #0 runs `A.V` and `B.X`. + * Machine #1 runs `A.W` and `B.Y`. + * Machine #2 runs `B.Z`. + +_Availability:_ Linux, Windows, Mac; since version 1.3.0. + +# Fusing Google Test Source Files # + +Google Test's implementation consists of ~30 files (excluding its own +tests). Sometimes you may want them to be packaged up in two files (a +`.h` and a `.cc`) instead, such that you can easily copy them to a new +machine and start hacking there. For this we provide an experimental +Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0). +Assuming you have Python 2.4 or above installed on your machine, just +go to that directory and run +``` +python fuse_gtest_files.py OUTPUT_DIR +``` + +and you should see an `OUTPUT_DIR` directory being created with files +`gtest/gtest.h` and `gtest/gtest-all.cc` in it. These files contain +everything you need to use Google Test. Just copy them to anywhere +you want and you are ready to write tests. You can use the +[scripts/test/Makefile](../scripts/test/Makefile) +file as an example on how to compile your tests against them. + +# Where to Go from Here # + +Congratulations! You've now learned more advanced Google Test tools and are +ready to tackle more complex testing tasks. If you want to dive even deeper, you +can read the [Frequently-Asked Questions](FAQ.md). diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 5e8ee0c..561ad02 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -229,7 +229,7 @@ A `NULL` pointer and an empty string are considered _different_. _Availability_: Linux, Windows, Mac. See also: For more string comparison tricks (substring, prefix, suffix, and -regular expression matching, for example), see the [Advanced Google Test Guide](AdvancedGuide.md). +regular expression matching, for example), see the [Advanced Google Test Guide](advanced.md). # Simple Tests # @@ -494,7 +494,7 @@ int main(int argc, char **argv) { The `::testing::InitGoogleTest()` function parses the command line for Google Test flags, and removes all recognized flags. This allows the user to control a -test program's behavior via various flags, which we'll cover in [AdvancedGuide](AdvancedGuide.md). +test program's behavior via various flags, which we'll cover in [AdvancedGuide](advanced.md). You must call this function before calling `RUN_ALL_TESTS()`, or the flags won't be properly initialized. @@ -523,7 +523,7 @@ There is one more pitfall, though. If you use Google Test as a static library (t Congratulations! You've learned the Google Test basics. You can start writing and running Google Test tests, read some [samples](Samples.md), or continue with -[AdvancedGuide](AdvancedGuide.md), which describes many more useful Google Test features. +[AdvancedGuide](advanced.md), which describes many more useful Google Test features. # Known Limitations # diff --git a/googletest/scripts/fuse_gtest_files.py b/googletest/scripts/fuse_gtest_files.py index 9a5c8d3..d0dd464 100755 --- a/googletest/scripts/fuse_gtest_files.py +++ b/googletest/scripts/fuse_gtest_files.py @@ -52,7 +52,7 @@ EXAMPLES This tool is experimental. In particular, it assumes that there is no conditional inclusion of Google Test headers. Please report any problems to googletestframework@googlegroups.com. You can read -https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md for +https://github.com/google/googletest/blob/master/googletest/docs/advanced.md for more information. """ diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 5406392..3498ffe 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -5196,7 +5196,7 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see -// https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md +// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? -- cgit v0.12 From 4490be87897d598a403bb4a115a3a0fd79a37ca3 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 11 Jun 2018 11:49:02 -0400 Subject: Rename FAQ.md to faq.md and adjust the links. Part of documentation rationalization --- googletest/docs/Documentation.md | 2 +- googletest/docs/FAQ.md | 1092 -------------------------------------- googletest/docs/advanced.md | 4 +- googletest/docs/faq.md | 1092 ++++++++++++++++++++++++++++++++++++++ googletest/docs/primer.md | 2 +- 5 files changed, 1096 insertions(+), 1096 deletions(-) delete mode 100644 googletest/docs/FAQ.md create mode 100644 googletest/docs/faq.md diff --git a/googletest/docs/Documentation.md b/googletest/docs/Documentation.md index 1b6aa4f..b6c77af 100644 --- a/googletest/docs/Documentation.md +++ b/googletest/docs/Documentation.md @@ -8,7 +8,7 @@ the respective git branch/tag).** * [Samples](Samples.md) -- learn from examples. * [AdvancedGuide](advanced.md) -- learn more about Google Test. * [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac. - * [Frequently-Asked Questions](FAQ.md) -- check here before asking a question on the mailing list. + * [Frequently-Asked Questions](faq.md) -- check here before asking a question on the mailing list. To contribute code to Google Test, read: diff --git a/googletest/docs/FAQ.md b/googletest/docs/FAQ.md deleted file mode 100644 index a886bdc..0000000 --- a/googletest/docs/FAQ.md +++ /dev/null @@ -1,1092 +0,0 @@ - - -If you cannot find the answer to your question here, and you have read -[Primer](primer.md) and [AdvancedGuide](advanced.md), send it to -googletestframework@googlegroups.com. - -## Why should I use Google Test instead of my favorite C++ testing framework? ## - -First, let us say clearly that we don't want to get into the debate of -which C++ testing framework is **the best**. There exist many fine -frameworks for writing C++ tests, and we have tremendous respect for -the developers and users of them. We don't think there is (or will -be) a single best framework - you have to pick the right tool for the -particular task you are tackling. - -We created Google Test because we couldn't find the right combination -of features and conveniences in an existing framework to satisfy _our_ -needs. The following is a list of things that _we_ like about Google -Test. We don't claim them to be unique to Google Test - rather, the -combination of them makes Google Test the choice for us. We hope this -list can help you decide whether it is for you too. - - * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc. As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems. - * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle. - * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`. It doesn't require a new set of macros or special functions. - * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them. - * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions. - * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop. - * You can decide which tests to run using name patterns. This saves time when you want to quickly reproduce a test failure. - * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson. - * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](advanced.md#global-set-up-and-tear-down) and tests parameterized by [values](advanced.md#value-parameterized-tests) or [types](docs/advanced.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: - * expand your testing vocabulary by defining [custom predicates](advanced.md#predicate-assertions-for-better-error-messages), - * teach Google Test how to [print your types](advanced.md#teaching-google-test-how-to-print-your-values), - * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](advanced.md#catching-failures), and - * reflect on the test cases or change the test output format by intercepting the [test events](advanced.md#extending-google-test-by-handling-test-events). - -## I'm getting warnings when compiling Google Test. Would you fix them? ## - -We strive to minimize compiler warnings Google Test generates. Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS. - -Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment: - - * You may be using a different compiler as we use, or a different version of the same compiler. We cannot possibly test for all compilers. - * You may be compiling on a different platform as we do. - * Your project may be using different compiler flags as we do. - -It is not always possible to make Google Test warning-free for everyone. Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex. - -If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers. That'll suppress warnings from Google Test headers. - -## Why should not test case names and test names contain underscore? ## - -Underscore (`_`) is special, as C++ reserves the following to be used by -the compiler and the standard library: - - 1. any identifier that starts with an `_` followed by an upper-case letter, and - 1. any identifier that contains two consecutive underscores (i.e. `__`) _anywhere_ in its name. - -User code is _prohibited_ from using such identifiers. - -Now let's look at what this means for `TEST` and `TEST_F`. - -Currently `TEST(TestCaseName, TestName)` generates a class named -`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` -contains `_`? - - 1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid. - 1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid. - 1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid. - 1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid. - -So clearly `TestCaseName` and `TestName` cannot start or end with `_` -(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't -followed by an upper-case letter. But that's getting complicated. So -for simplicity we just say that it cannot start with `_`.). - -It may seem fine for `TestCaseName` and `TestName` to contain `_` in the -middle. However, consider this: -``` cpp -TEST(Time, Flies_Like_An_Arrow) { ... } -TEST(Time_Flies, Like_An_Arrow) { ... } -``` - -Now, the two `TEST`s will both generate the same class -(`Time_Files_Like_An_Arrow_Test`). That's not good. - -So for simplicity, we just ask the users to avoid `_` in `TestCaseName` -and `TestName`. The rule is more constraining than necessary, but it's -simple and easy to remember. It also gives Google Test some wiggle -room in case its implementation needs to change in the future. - -If you violate the rule, there may not be immediately consequences, -but your test may (just may) break with a new compiler (or a new -version of the compiler you are using) or with a new version of Google -Test. Therefore it's best to follow the rule. - -## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ## - -In the early days, we said that you could install -compiled Google Test libraries on `*`nix systems using `make install`. -Then every user of your machine can write tests without -recompiling Google Test. - -This seemed like a good idea, but it has a -got-cha: every user needs to compile their tests using the _same_ compiler -flags used to compile the installed Google Test libraries; otherwise -they may run into undefined behaviors (i.e. the tests can behave -strangely and may even crash for no obvious reasons). - -Why? Because C++ has this thing called the One-Definition Rule: if -two C++ source files contain different definitions of the same -class/function/variable, and you link them together, you violate the -rule. The linker may or may not catch the error (in many cases it's -not required by the C++ standard to catch the violation). If it -doesn't, you get strange run-time behaviors that are unexpected and -hard to debug. - -If you compile Google Test and your test code using different compiler -flags, they may see different definitions of the same -class/function/variable (e.g. due to the use of `#if` in Google Test). -Therefore, for your sanity, we recommend to avoid installing pre-compiled -Google Test libraries. Instead, each project should compile -Google Test itself such that it can be sure that the same flags are -used for both Google Test and the tests. - -## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ## - -(Answered by Trevor Robinson) - -Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or -`msvc\gtest.sln`. Go through the migration wizard to migrate the -solution and project files to Visual Studio 2008. Select -`Configuration Manager...` from the `Build` menu. Select `` from -the `Active solution platform` dropdown. Select `x64` from the new -platform dropdown, leave `Copy settings from` set to `Win32` and -`Create new project platforms` checked, then click `OK`. You now have -`Win32` and `x64` platform configurations, selectable from the -`Standard` toolbar, which allow you to toggle between building 32-bit or -64-bit binaries (or both at once using Batch Build). - -In order to prevent build output files from overwriting one another, -you'll need to change the `Intermediate Directory` settings for the -newly created platform configuration across all the projects. To do -this, multi-select (e.g. using shift-click) all projects (but not the -solution) in the `Solution Explorer`. Right-click one of them and -select `Properties`. In the left pane, select `Configuration Properties`, -and from the `Configuration` dropdown, select `All Configurations`. -Make sure the selected platform is `x64`. For the -`Intermediate Directory` setting, change the value from -`$(PlatformName)\$(ConfigurationName)` to -`$(OutDir)\$(ProjectName)`. Click `OK` and then build the -solution. When the build is complete, the 64-bit binaries will be in -the `msvc\x64\Debug` directory. - -## Can I use Google Test on MinGW? ## - -We haven't tested this ourselves, but Per Abrahamsen reported that he -was able to compile and install Google Test successfully when using -MinGW from Cygwin. You'll need to configure it with: - -`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"` - -You should be able to replace the `-mno-cygwin` option with direct links -to the real MinGW binaries, but we haven't tried that. - -Caveats: - - * There are many warnings when compiling. - * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW. - -We also have reports on successful cross compilation of Google Test -MinGW binaries on Linux using -[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows) -on the WxWidgets site. - -Please contact `googletestframework@googlegroups.com` if you are -interested in improving the support for MinGW. - -## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ## - -Due to some peculiarity of C++, it requires some non-trivial template -meta programming tricks to support using `NULL` as an argument of the -`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where -it's most needed (otherwise we make the implementation of Google Test -harder to maintain and more error-prone than necessary). - -The `EXPECT_EQ()` macro takes the _expected_ value as its first -argument and the _actual_ value as the second. It's reasonable that -someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this -indeed was requested several times. Therefore we implemented it. - -The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the -assertion fails, you already know that `ptr` must be `NULL`, so it -doesn't add any information to print ptr in this case. That means -`EXPECT_TRUE(ptr != NULL)` works just as well. - -If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll -have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, -we don't have a convention on the order of the two arguments for -`EXPECT_NE`. This means using the template meta programming tricks -twice in the implementation, making it even harder to understand and -maintain. We believe the benefit doesn't justify the cost. - -Finally, with the growth of Google Mock's [matcher](../../googlemock/docs/CookBook.md#using-matchers-in-google-test-assertions) library, we are -encouraging people to use the unified `EXPECT_THAT(value, matcher)` -syntax more often in tests. One significant advantage of the matcher -approach is that matchers can be easily combined to form new matchers, -while the `EXPECT_NE`, etc, macros cannot be easily -combined. Therefore we want to invest more in the matchers than in the -`EXPECT_XX()` macros. - -## Does Google Test support running tests in parallel? ## - -Test runners tend to be tightly coupled with the build/test -environment, and Google Test doesn't try to solve the problem of -running tests in parallel. Instead, we tried to make Google Test work -nicely with test runners. For example, Google Test's XML report -contains the time spent on each test, and its `gtest_list_tests` and -`gtest_filter` flags can be used for splitting the execution of test -methods into multiple processes. These functionalities can help the -test runner run the tests in parallel. - -## Why don't Google Test run the tests in different threads to speed things up? ## - -It's difficult to write thread-safe code. Most tests are not written -with thread-safety in mind, and thus may not work correctly in a -multi-threaded setting. - -If you think about it, it's already hard to make your code work when -you know what other threads are doing. It's much harder, and -sometimes even impossible, to make your code work when you don't know -what other threads are doing (remember that test methods can be added, -deleted, or modified after your test was written). If you want to run -the tests in parallel, you'd better run them in different processes. - -## Why aren't Google Test assertions implemented using exceptions? ## - -Our original motivation was to be able to use Google Test in projects -that disable exceptions. Later we realized some additional benefits -of this approach: - - 1. Throwing in a destructor is undefined behavior in C++. Not using exceptions means Google Test's assertions are safe to use in destructors. - 1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing. - 1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code: -``` cpp -try { ... ASSERT_TRUE(...) ... } -catch (...) { ... } -``` -The above code will pass even if the `ASSERT_TRUE` throws. While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test. - -The downside of not using exceptions is that `ASSERT_*` (implemented -using `return`) will only abort the current function, not the current -`TEST`. - -## Why do we use two different macros for tests with and without fixtures? ## - -Unfortunately, C++'s macro system doesn't allow us to use the same -macro for both cases. One possibility is to provide only one macro -for tests with fixtures, and require the user to define an empty -fixture sometimes: - -``` cpp -class FooTest : public ::testing::Test {}; - -TEST_F(FooTest, DoesThis) { ... } -``` -or -``` cpp -typedef ::testing::Test FooTest; - -TEST_F(FooTest, DoesThat) { ... } -``` - -Yet, many people think this is one line too many. :-) Our goal was to -make it really easy to write tests, so we tried to make simple tests -trivial to create. That means using a separate macro for such tests. - -We think neither approach is ideal, yet either of them is reasonable. -In the end, it probably doesn't matter much either way. - -## Why don't we use structs as test fixtures? ## - -We like to use structs only when representing passive data. This -distinction between structs and classes is good for documenting the -intent of the code's author. Since test fixtures have logic like -`SetUp()` and `TearDown()`, they are better defined as classes. - -## Why are death tests implemented as assertions instead of using a test runner? ## - -Our goal was to make death tests as convenient for a user as C++ -possibly allows. In particular: - - * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect. The death test would be written in C++, while the runner spec may or may not be. A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative. - * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn. - * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will. You are not limited to one death test per test method. For example, you can write something like: -``` cpp - if (FooCondition()) { - ASSERT_DEATH(Bar(), "blah"); - } else { - ASSERT_EQ(5, Bar()); - } -``` -If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users. The fewer artificial limitations the better. - * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information. For example, -``` cpp - const int count = GetCount(); // Only known at run time. - for (int i = 1; i <= count; i++) { - ASSERT_DEATH({ - double* buffer = new double[i]; - ... initializes buffer ... - Foo(buffer, i) - }, "blah blah"); - } -``` -The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility. - -Another interesting thing about `ASSERT_DEATH` is that it calls `fork()` -to create a child process to run the death test. This is lightening -fast, as `fork()` uses copy-on-write pages and incurs almost zero -overhead, and the child process starts from the user-supplied -statement directly, skipping all global and local initialization and -any code leading to the given statement. If you launch the child -process from scratch, it can take seconds just to load everything and -start running if the test links to many libraries dynamically. - -## My death test modifies some state, but the change seems lost after the death test finishes. Why? ## - -Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the -expected crash won't kill the test program (i.e. the parent process). As a -result, any in-memory side effects they incur are observable in their -respective sub-processes, but not in the parent process. You can think of them -as running in a parallel universe, more or less. - -## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ## - -If your class has a static data member: - -``` cpp -// foo.h -class Foo { - ... - static const int kBar = 100; -}; -``` - -You also need to define it _outside_ of the class body in `foo.cc`: - -``` cpp -const int Foo::kBar; // No initializer here. -``` - -Otherwise your code is **invalid C++**, and may break in unexpected ways. In -particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc) -will generate an "undefined reference" linker error. - -## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ## - -Google Test doesn't yet have good support for this kind of tests, or -data-driven tests in general. We hope to be able to make improvements in this -area soon. - -## Can I derive a test fixture from another? ## - -Yes. - -Each test fixture has a corresponding and same named test case. This means only -one test case can use a particular fixture. Sometimes, however, multiple test -cases may want to use the same or slightly different fixtures. For example, you -may want to make sure that all of a GUI library's test cases don't leak -important system resources like fonts and brushes. - -In Google Test, you share a fixture among test cases by putting the shared -logic in a base test fixture, then deriving from that base a separate fixture -for each test case that wants to use this common logic. You then use `TEST_F()` -to write tests using each derived fixture. - -Typically, your code looks like this: - -``` cpp -// Defines a base test fixture. -class BaseTest : public ::testing::Test { - protected: - ... -}; - -// Derives a fixture FooTest from BaseTest. -class FooTest : public BaseTest { - protected: - virtual void SetUp() { - BaseTest::SetUp(); // Sets up the base fixture first. - ... additional set-up work ... - } - virtual void TearDown() { - ... clean-up work for FooTest ... - BaseTest::TearDown(); // Remember to tear down the base fixture - // after cleaning up FooTest! - } - ... functions and variables for FooTest ... -}; - -// Tests that use the fixture FooTest. -TEST_F(FooTest, Bar) { ... } -TEST_F(FooTest, Baz) { ... } - -... additional fixtures derived from BaseTest ... -``` - -If necessary, you can continue to derive test fixtures from a derived fixture. -Google Test has no limit on how deep the hierarchy can be. - -For a complete example using derived test fixtures, see -[sample5](../samples/sample5_unittest.cc). - -## My compiler complains "void value not ignored as it ought to be." What does this mean? ## - -You're probably using an `ASSERT_*()` in a function that doesn't return `void`. -`ASSERT_*()` can only be used in `void` functions. - -## My death test hangs (or seg-faults). How do I fix it? ## - -In Google Test, death tests are run in a child process and the way they work is -delicate. To write death tests you really need to understand how they work. -Please make sure you have read this. - -In particular, death tests don't like having multiple threads in the parent -process. So the first thing you can try is to eliminate creating threads -outside of `EXPECT_DEATH()`. - -Sometimes this is impossible as some library you must use may be creating -threads before `main()` is even reached. In this case, you can try to minimize -the chance of conflicts by either moving as many activities as possible inside -`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or -leaving as few things as possible in it. Also, you can try to set the death -test style to `"threadsafe"`, which is safer but slower, and see if it helps. - -If you go with thread-safe death tests, remember that they rerun the test -program from the beginning in the child process. Therefore make sure your -program can run side-by-side with itself and is deterministic. - -In the end, this boils down to good concurrent programming. You have to make -sure that there is no race conditions or dead locks in your program. No silver -bullet - sorry! - -## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ## - -The first thing to remember is that Google Test does not reuse the -same test fixture object across multiple tests. For each `TEST_F`, -Google Test will create a fresh test fixture object, _immediately_ -call `SetUp()`, run the test body, call `TearDown()`, and then -_immediately_ delete the test fixture object. - -When you need to write per-test set-up and tear-down logic, you have -the choice between using the test fixture constructor/destructor or -`SetUp()/TearDown()`. The former is usually preferred, as it has the -following benefits: - - * By initializing a member variable in the constructor, we have the option to make it `const`, which helps prevent accidental changes to its value and makes the tests more obviously correct. - * In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With `SetUp()/TearDown()`, a subclass may make the mistake of forgetting to call the base class' `SetUp()/TearDown()` or call them at the wrong moment. - -You may still want to use `SetUp()/TearDown()` in the following rare cases: - * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. - * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag. - * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overridden in a derived class, you have to use `SetUp()/TearDown()`. - -## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ## - -If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is -overloaded or a template, the compiler will have trouble figuring out which -overloaded version it should use. `ASSERT_PRED_FORMAT*` and -`EXPECT_PRED_FORMAT*` don't have this problem. - -If you see this error, you might want to switch to -`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure -message. If, however, that is not an option, you can resolve the problem by -explicitly telling the compiler which version to pick. - -For example, suppose you have - -``` cpp -bool IsPositive(int n) { - return n > 0; -} -bool IsPositive(double x) { - return x > 0; -} -``` - -you will get a compiler error if you write - -``` cpp -EXPECT_PRED1(IsPositive, 5); -``` - -However, this will work: - -``` cpp -EXPECT_PRED1(static_cast(IsPositive), 5); -``` - -(The stuff inside the angled brackets for the `static_cast` operator is the -type of the function pointer for the `int`-version of `IsPositive()`.) - -As another example, when you have a template function - -``` cpp -template -bool IsNegative(T x) { - return x < 0; -} -``` - -you can use it in a predicate assertion like this: - -``` cpp -ASSERT_PRED1(IsNegative, -5); -``` - -Things are more interesting if your template has more than one parameters. The -following won't compile: - -``` cpp -ASSERT_PRED2(GreaterThan, 5, 0); -``` - - -as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, -which is one more than expected. The workaround is to wrap the predicate -function in parentheses: - -``` cpp -ASSERT_PRED2((GreaterThan), 5, 0); -``` - - -## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ## - -Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, -instead of - -``` cpp -return RUN_ALL_TESTS(); -``` - -they write - -``` cpp -RUN_ALL_TESTS(); -``` - -This is wrong and dangerous. A test runner needs to see the return value of -`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()` -function ignores it, your test will be considered successful even if it has a -Google Test assertion failure. Very bad. - -To help the users avoid this dangerous bug, the implementation of -`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is -ignored. If you see this warning, the fix is simple: just make sure its value -is used as the return value of `main()`. - -## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ## - -Due to a peculiarity of C++, in order to support the syntax for streaming -messages to an `ASSERT_*`, e.g. - -``` cpp -ASSERT_EQ(1, Foo()) << "blah blah" << foo; -``` - -we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and -`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the -content of your constructor/destructor to a private void member function, or -switch to `EXPECT_*()` if that works. This section in the user's guide explains -it. - -## My set-up function is not called. Why? ## - -C++ is case-sensitive. It should be spelled as `SetUp()`. Did you -spell it as `Setup()`? - -Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and -wonder why it's never called. - -## How do I jump to the line of a failure in Emacs directly? ## - -Google Test's failure message format is understood by Emacs and many other -IDEs, like acme and XCode. If a Google Test message is in a compilation buffer -in Emacs, then it's clickable. You can now hit `enter` on a message to jump to -the corresponding source code, or use `C-x `` to jump to the next failure. - -## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ## - -You don't have to. Instead of - -``` cpp -class FooTest : public BaseTest {}; - -TEST_F(FooTest, Abc) { ... } -TEST_F(FooTest, Def) { ... } - -class BarTest : public BaseTest {}; - -TEST_F(BarTest, Abc) { ... } -TEST_F(BarTest, Def) { ... } -``` - -you can simply `typedef` the test fixtures: -``` cpp -typedef BaseTest FooTest; - -TEST_F(FooTest, Abc) { ... } -TEST_F(FooTest, Def) { ... } - -typedef BaseTest BarTest; - -TEST_F(BarTest, Abc) { ... } -TEST_F(BarTest, Def) { ... } -``` - -## The Google Test output is buried in a whole bunch of log messages. What do I do? ## - -The Google Test output is meant to be a concise and human-friendly report. If -your test generates textual output itself, it will mix with the Google Test -output, making it hard to read. However, there is an easy solution to this -problem. - -Since most log messages go to stderr, we decided to let Google Test output go -to stdout. This way, you can easily separate the two using redirection. For -example: -``` -./my_test > googletest_output.txt -``` - -## Why should I prefer test fixtures over global variables? ## - -There are several good reasons: - 1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other. - 1. Global variables pollute the global namespace. - 1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common. - -## How do I test private class members without writing FRIEND\_TEST()s? ## - -You should try to write testable code, which means classes should be easily -tested from their public interface. One way to achieve this is the Pimpl idiom: -you move all private members of a class into a helper class, and make all -members of the helper class public. - -You have several other options that don't require using `FRIEND_TEST`: - * Write the tests as members of the fixture class: -``` cpp -class Foo { - friend class FooTest; - ... -}; - -class FooTest : public ::testing::Test { - protected: - ... - void Test1() {...} // This accesses private members of class Foo. - void Test2() {...} // So does this one. -}; - -TEST_F(FooTest, Test1) { - Test1(); -} - -TEST_F(FooTest, Test2) { - Test2(); -} -``` - * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests: -``` cpp -class Foo { - friend class FooTest; - ... -}; - -class FooTest : public ::testing::Test { - protected: - ... - T1 get_private_member1(Foo* obj) { - return obj->private_member1_; - } -}; - -TEST_F(FooTest, Test1) { - ... - get_private_member1(x) - ... -} -``` - * If the methods are declared **protected**, you can change their access level in a test-only subclass: -``` cpp -class YourClass { - ... - protected: // protected access for testability. - int DoSomethingReturningInt(); - ... -}; - -// in the your_class_test.cc file: -class TestableYourClass : public YourClass { - ... - public: using YourClass::DoSomethingReturningInt; // changes access rights - ... -}; - -TEST_F(YourClassTest, DoSomethingTest) { - TestableYourClass obj; - assertEquals(expected_value, obj.DoSomethingReturningInt()); -} -``` - -## How do I test private class static members without writing FRIEND\_TEST()s? ## - -We find private static methods clutter the header file. They are -implementation details and ideally should be kept out of a .h. So often I make -them free functions instead. - -Instead of: -``` cpp -// foo.h -class Foo { - ... - private: - static bool Func(int n); -}; - -// foo.cc -bool Foo::Func(int n) { ... } - -// foo_test.cc -EXPECT_TRUE(Foo::Func(12345)); -``` - -You probably should better write: -``` cpp -// foo.h -class Foo { - ... -}; - -// foo.cc -namespace internal { - bool Func(int n) { ... } -} - -// foo_test.cc -namespace internal { - bool Func(int n); -} - -EXPECT_TRUE(internal::Func(12345)); -``` - -## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ## - -No. You can use a feature called [value-parameterized tests](advanced.md#Value_Parameterized_Tests) which -lets you repeat your tests with different parameters, without defining it more than once. - -## How do I test a file that defines main()? ## - -To test a `foo.cc` file, you need to compile and link it into your unit test -program. However, when the file contains a definition for the `main()` -function, it will clash with the `main()` of your unit test, and will result in -a build error. - -The right solution is to split it into three files: - 1. `foo.h` which contains the declarations, - 1. `foo.cc` which contains the definitions except `main()`, and - 1. `foo_main.cc` which contains nothing but the definition of `main()`. - -Then `foo.cc` can be easily tested. - -If you are adding tests to an existing file and don't want an intrusive change -like this, there is a hack: just include the entire `foo.cc` file in your unit -test. For example: -``` cpp -// File foo_unittest.cc - -// The headers section -... - -// Renames main() in foo.cc to make room for the unit test main() -#define main FooMain - -#include "a/b/foo.cc" - -// The tests start here. -... -``` - - -However, please remember this is a hack and should only be used as the last -resort. - -## What can the statement argument in ASSERT\_DEATH() be? ## - -`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used -wherever `_statement_` is valid. So basically `_statement_` can be any C++ -statement that makes sense in the current context. In particular, it can -reference global and/or local variables, and can be: - * a simple function call (often the case), - * a complex expression, or - * a compound statement. - -Some examples are shown here: - -``` cpp -// A death test can be a simple function call. -TEST(MyDeathTest, FunctionCall) { - ASSERT_DEATH(Xyz(5), "Xyz failed"); -} - -// Or a complex expression that references variables and functions. -TEST(MyDeathTest, ComplexExpression) { - const bool c = Condition(); - ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), - "(Func1|Method) failed"); -} - -// Death assertions can be used any where in a function. In -// particular, they can be inside a loop. -TEST(MyDeathTest, InsideLoop) { - // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. - for (int i = 0; i < 5; i++) { - EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", - ::testing::Message() << "where i is " << i); - } -} - -// A death assertion can contain a compound statement. -TEST(MyDeathTest, CompoundStatement) { - // Verifies that at lease one of Bar(0), Bar(1), ..., and - // Bar(4) dies. - ASSERT_DEATH({ - for (int i = 0; i < 5; i++) { - Bar(i); - } - }, - "Bar has \\d+ errors");} -``` - -`googletest_unittest.cc` contains more examples if you are interested. - -## What syntax does the regular expression in ASSERT\_DEATH use? ## - -On POSIX systems, Google Test uses the POSIX Extended regular -expression syntax -(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). -On Windows, it uses a limited variant of regular expression -syntax. For more details, see the -[regular expression syntax](advanced.md#Regular_Expression_Syntax). - -## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ## - -Google Test needs to be able to create objects of your test fixture class, so -it must have a default constructor. Normally the compiler will define one for -you. However, there are cases where you have to define your own: - * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty. - * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.) - -## Why does ASSERT\_DEATH complain about previous threads that were already joined? ## - -With the Linux pthread library, there is no turning back once you cross the -line from single thread to multiple threads. The first time you create a -thread, a manager thread is created in addition, so you get 3, not 2, threads. -Later when the thread you create joins the main thread, the thread count -decrements by 1, but the manager thread will never be killed, so you still have -2 threads, which means you cannot safely run a death test. - -The new NPTL thread library doesn't suffer from this problem, as it doesn't -create a manager thread. However, if you don't control which machine your test -runs on, you shouldn't depend on this. - -## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ## - -Google Test does not interleave tests from different test cases. That is, it -runs all tests in one test case first, and then runs all tests in the next test -case, and so on. Google Test does this because it needs to set up a test case -before the first test in it is run, and tear it down afterwords. Splitting up -the test case would require multiple set-up and tear-down processes, which is -inefficient and makes the semantics unclean. - -If we were to determine the order of tests based on test name instead of test -case name, then we would have a problem with the following situation: - -``` cpp -TEST_F(FooTest, AbcDeathTest) { ... } -TEST_F(FooTest, Uvw) { ... } - -TEST_F(BarTest, DefDeathTest) { ... } -TEST_F(BarTest, Xyz) { ... } -``` - -Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't -interleave tests from different test cases, we need to run all tests in the -`FooTest` case before running any test in the `BarTest` case. This contradicts -with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. - -## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ## - -You don't have to, but if you like, you may split up the test case into -`FooTest` and `FooDeathTest`, where the names make it clear that they are -related: - -``` cpp -class FooTest : public ::testing::Test { ... }; - -TEST_F(FooTest, Abc) { ... } -TEST_F(FooTest, Def) { ... } - -typedef FooTest FooDeathTest; - -TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } -TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } -``` - -## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ## - -If you use a user-defined type `FooType` in an assertion, you must make sure -there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function -defined such that we can print a value of `FooType`. - -In addition, if `FooType` is declared in a name space, the `<<` operator also -needs to be defined in the _same_ name space. - -## How do I suppress the memory leak messages on Windows? ## - -Since the statically initialized Google Test singleton requires allocations on -the heap, the Visual C++ memory leak detector will report memory leaks at the -end of the program run. The easiest way to avoid this is to use the -`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any -statically initialized heap objects. See MSDN for more details and additional -heap check/debug routines. - -## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ## - -You may get a number of the following linker error or warnings if you -attempt to link your test project with the Google Test library when -your project and the are not built using the same compiler settings. - - * LNK2005: symbol already defined in object - * LNK4217: locally defined symbol 'symbol' imported in function 'function' - * LNK4049: locally defined symbol 'symbol' imported - -The Google Test project (gtest.vcproj) has the Runtime Library option -set to /MT (use multi-threaded static libraries, /MTd for debug). If -your project uses something else, for example /MD (use multi-threaded -DLLs, /MDd for debug), you need to change the setting in the Google -Test project to match your project's. - -To update this setting open the project properties in the Visual -Studio IDE then select the branch Configuration Properties | C/C++ | -Code Generation and change the option "Runtime Library". You may also try -using gtest-md.vcproj instead of gtest.vcproj. - -## I put my tests in a library and Google Test doesn't run them. What's happening? ## -Have you read a -[warning](primer.md#important-note-for-visual-c-users) on -the Google Test Primer page? - -## I want to use Google Test with Visual Studio but don't know where to start. ## -Many people are in your position and one of them posted his solution to our mailing list. - -## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ## -Google Test uses parts of the standard C++ library that SunStudio does not support. -Our users reported success using alternative implementations. Try running the build after running this command: - -`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'` - -## How can my code detect if it is running in a test? ## - -If you write code that sniffs whether it's running in a test and does -different things accordingly, you are leaking test-only logic into -production code and there is no easy way to ensure that the test-only -code paths aren't run by mistake in production. Such cleverness also -leads to -[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug). -Therefore we strongly advise against the practice, and Google Test doesn't -provide a way to do it. - -In general, the recommended way to cause the code to behave -differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html). -You can inject different functionality from the test and from the -production code. Since your production code doesn't link in the -for-test logic at all, there is no danger in accidentally running it. - -However, if you _really_, _really_, _really_ have no choice, and if -you follow the rule of ending your test program names with `_test`, -you can use the _horrible_ hack of sniffing your executable name -(`argv[0]` in `main()`) to know whether the code is under test. - -## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ## - -In C++, macros don't obey namespaces. Therefore two libraries that -both define a macro of the same name will clash if you `#include` both -definitions. In case a Google Test macro clashes with another -library, you can force Google Test to rename its macro to avoid the -conflict. - -Specifically, if both Google Test and some other code define macro -`FOO`, you can add -``` - -DGTEST_DONT_DEFINE_FOO=1 -``` -to the compiler flags to tell Google Test to change the macro's name -from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write -``` cpp - GTEST_TEST(SomeTest, DoesThis) { ... } -``` -instead of -``` cpp - TEST(SomeTest, DoesThis) { ... } -``` -in order to define a test. - -Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have . You can see the full list of covered macros [here](../include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file. - - -## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ## - -Yes. - -The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). - -``` cpp -namespace foo { -TEST(CoolTest, DoSomething) { - SUCCEED(); -} -} // namespace foo - -namespace bar { -TEST(CoolTest, DoSomething) { - SUCCEED(); -} -} // namespace bar -``` - -However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name. - -``` cpp -namespace foo { -class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest -TEST_F(CoolTest, DoSomething) { - SUCCEED(); -} -} // namespace foo - -namespace bar { -class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest -TEST_F(CoolTest, DoSomething) { - SUCCEED(); -} -} // namespace bar -``` - -## How do I build Google Testing Framework with Xcode 4? ## - -If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like -"Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](../README.md) file on how to resolve this. - -## How do I easily discover the flags needed for GoogleTest? ## - -GoogleTest (and GoogleMock) now support discovering all necessary flags using pkg-config. -See the [pkg-config guide](Pkgconfig.md) on how you can easily discover all compiler and -linker flags using pkg-config. - -## My question is not covered in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](../docs), - 1. search the mailing list [archive](https://groups.google.com/forum/#!forum/googletestframework), - 1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.). - -Please note that creating an issue in the -[issue tracker](https://github.com/google/googletest/issues) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the commit hash if you check out from Git directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 857967a..73b7954 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -125,7 +125,7 @@ c is 10
**Notes:** - 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](FAQ.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. + 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](faq.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. _Availability_: Linux, Windows, Mac. @@ -2413,4 +2413,4 @@ file as an example on how to compile your tests against them. Congratulations! You've now learned more advanced Google Test tools and are ready to tackle more complex testing tasks. If you want to dive even deeper, you -can read the [Frequently-Asked Questions](FAQ.md). +can read the [Frequently-Asked Questions](faq.md). diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md new file mode 100644 index 0000000..a886bdc --- /dev/null +++ b/googletest/docs/faq.md @@ -0,0 +1,1092 @@ + + +If you cannot find the answer to your question here, and you have read +[Primer](primer.md) and [AdvancedGuide](advanced.md), send it to +googletestframework@googlegroups.com. + +## Why should I use Google Test instead of my favorite C++ testing framework? ## + +First, let us say clearly that we don't want to get into the debate of +which C++ testing framework is **the best**. There exist many fine +frameworks for writing C++ tests, and we have tremendous respect for +the developers and users of them. We don't think there is (or will +be) a single best framework - you have to pick the right tool for the +particular task you are tackling. + +We created Google Test because we couldn't find the right combination +of features and conveniences in an existing framework to satisfy _our_ +needs. The following is a list of things that _we_ like about Google +Test. We don't claim them to be unique to Google Test - rather, the +combination of them makes Google Test the choice for us. We hope this +list can help you decide whether it is for you too. + + * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc. As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems. + * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle. + * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`. It doesn't require a new set of macros or special functions. + * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them. + * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions. + * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop. + * You can decide which tests to run using name patterns. This saves time when you want to quickly reproduce a test failure. + * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson. + * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](advanced.md#global-set-up-and-tear-down) and tests parameterized by [values](advanced.md#value-parameterized-tests) or [types](docs/advanced.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: + * expand your testing vocabulary by defining [custom predicates](advanced.md#predicate-assertions-for-better-error-messages), + * teach Google Test how to [print your types](advanced.md#teaching-google-test-how-to-print-your-values), + * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](advanced.md#catching-failures), and + * reflect on the test cases or change the test output format by intercepting the [test events](advanced.md#extending-google-test-by-handling-test-events). + +## I'm getting warnings when compiling Google Test. Would you fix them? ## + +We strive to minimize compiler warnings Google Test generates. Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS. + +Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment: + + * You may be using a different compiler as we use, or a different version of the same compiler. We cannot possibly test for all compilers. + * You may be compiling on a different platform as we do. + * Your project may be using different compiler flags as we do. + +It is not always possible to make Google Test warning-free for everyone. Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex. + +If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers. That'll suppress warnings from Google Test headers. + +## Why should not test case names and test names contain underscore? ## + +Underscore (`_`) is special, as C++ reserves the following to be used by +the compiler and the standard library: + + 1. any identifier that starts with an `_` followed by an upper-case letter, and + 1. any identifier that contains two consecutive underscores (i.e. `__`) _anywhere_ in its name. + +User code is _prohibited_ from using such identifiers. + +Now let's look at what this means for `TEST` and `TEST_F`. + +Currently `TEST(TestCaseName, TestName)` generates a class named +`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` +contains `_`? + + 1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid. + 1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid. + 1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid. + 1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid. + +So clearly `TestCaseName` and `TestName` cannot start or end with `_` +(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't +followed by an upper-case letter. But that's getting complicated. So +for simplicity we just say that it cannot start with `_`.). + +It may seem fine for `TestCaseName` and `TestName` to contain `_` in the +middle. However, consider this: +``` cpp +TEST(Time, Flies_Like_An_Arrow) { ... } +TEST(Time_Flies, Like_An_Arrow) { ... } +``` + +Now, the two `TEST`s will both generate the same class +(`Time_Files_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestCaseName` +and `TestName`. The rule is more constraining than necessary, but it's +simple and easy to remember. It also gives Google Test some wiggle +room in case its implementation needs to change in the future. + +If you violate the rule, there may not be immediately consequences, +but your test may (just may) break with a new compiler (or a new +version of the compiler you are using) or with a new version of Google +Test. Therefore it's best to follow the rule. + +## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ## + +In the early days, we said that you could install +compiled Google Test libraries on `*`nix systems using `make install`. +Then every user of your machine can write tests without +recompiling Google Test. + +This seemed like a good idea, but it has a +got-cha: every user needs to compile their tests using the _same_ compiler +flags used to compile the installed Google Test libraries; otherwise +they may run into undefined behaviors (i.e. the tests can behave +strangely and may even crash for no obvious reasons). + +Why? Because C++ has this thing called the One-Definition Rule: if +two C++ source files contain different definitions of the same +class/function/variable, and you link them together, you violate the +rule. The linker may or may not catch the error (in many cases it's +not required by the C++ standard to catch the violation). If it +doesn't, you get strange run-time behaviors that are unexpected and +hard to debug. + +If you compile Google Test and your test code using different compiler +flags, they may see different definitions of the same +class/function/variable (e.g. due to the use of `#if` in Google Test). +Therefore, for your sanity, we recommend to avoid installing pre-compiled +Google Test libraries. Instead, each project should compile +Google Test itself such that it can be sure that the same flags are +used for both Google Test and the tests. + +## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ## + +(Answered by Trevor Robinson) + +Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or +`msvc\gtest.sln`. Go through the migration wizard to migrate the +solution and project files to Visual Studio 2008. Select +`Configuration Manager...` from the `Build` menu. Select `` from +the `Active solution platform` dropdown. Select `x64` from the new +platform dropdown, leave `Copy settings from` set to `Win32` and +`Create new project platforms` checked, then click `OK`. You now have +`Win32` and `x64` platform configurations, selectable from the +`Standard` toolbar, which allow you to toggle between building 32-bit or +64-bit binaries (or both at once using Batch Build). + +In order to prevent build output files from overwriting one another, +you'll need to change the `Intermediate Directory` settings for the +newly created platform configuration across all the projects. To do +this, multi-select (e.g. using shift-click) all projects (but not the +solution) in the `Solution Explorer`. Right-click one of them and +select `Properties`. In the left pane, select `Configuration Properties`, +and from the `Configuration` dropdown, select `All Configurations`. +Make sure the selected platform is `x64`. For the +`Intermediate Directory` setting, change the value from +`$(PlatformName)\$(ConfigurationName)` to +`$(OutDir)\$(ProjectName)`. Click `OK` and then build the +solution. When the build is complete, the 64-bit binaries will be in +the `msvc\x64\Debug` directory. + +## Can I use Google Test on MinGW? ## + +We haven't tested this ourselves, but Per Abrahamsen reported that he +was able to compile and install Google Test successfully when using +MinGW from Cygwin. You'll need to configure it with: + +`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"` + +You should be able to replace the `-mno-cygwin` option with direct links +to the real MinGW binaries, but we haven't tried that. + +Caveats: + + * There are many warnings when compiling. + * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW. + +We also have reports on successful cross compilation of Google Test +MinGW binaries on Linux using +[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows) +on the WxWidgets site. + +Please contact `googletestframework@googlegroups.com` if you are +interested in improving the support for MinGW. + +## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ## + +Due to some peculiarity of C++, it requires some non-trivial template +meta programming tricks to support using `NULL` as an argument of the +`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where +it's most needed (otherwise we make the implementation of Google Test +harder to maintain and more error-prone than necessary). + +The `EXPECT_EQ()` macro takes the _expected_ value as its first +argument and the _actual_ value as the second. It's reasonable that +someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this +indeed was requested several times. Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the +assertion fails, you already know that `ptr` must be `NULL`, so it +doesn't add any information to print ptr in this case. That means +`EXPECT_TRUE(ptr != NULL)` works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll +have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, +we don't have a convention on the order of the two arguments for +`EXPECT_NE`. This means using the template meta programming tricks +twice in the implementation, making it even harder to understand and +maintain. We believe the benefit doesn't justify the cost. + +Finally, with the growth of Google Mock's [matcher](../../googlemock/docs/CookBook.md#using-matchers-in-google-test-assertions) library, we are +encouraging people to use the unified `EXPECT_THAT(value, matcher)` +syntax more often in tests. One significant advantage of the matcher +approach is that matchers can be easily combined to form new matchers, +while the `EXPECT_NE`, etc, macros cannot be easily +combined. Therefore we want to invest more in the matchers than in the +`EXPECT_XX()` macros. + +## Does Google Test support running tests in parallel? ## + +Test runners tend to be tightly coupled with the build/test +environment, and Google Test doesn't try to solve the problem of +running tests in parallel. Instead, we tried to make Google Test work +nicely with test runners. For example, Google Test's XML report +contains the time spent on each test, and its `gtest_list_tests` and +`gtest_filter` flags can be used for splitting the execution of test +methods into multiple processes. These functionalities can help the +test runner run the tests in parallel. + +## Why don't Google Test run the tests in different threads to speed things up? ## + +It's difficult to write thread-safe code. Most tests are not written +with thread-safety in mind, and thus may not work correctly in a +multi-threaded setting. + +If you think about it, it's already hard to make your code work when +you know what other threads are doing. It's much harder, and +sometimes even impossible, to make your code work when you don't know +what other threads are doing (remember that test methods can be added, +deleted, or modified after your test was written). If you want to run +the tests in parallel, you'd better run them in different processes. + +## Why aren't Google Test assertions implemented using exceptions? ## + +Our original motivation was to be able to use Google Test in projects +that disable exceptions. Later we realized some additional benefits +of this approach: + + 1. Throwing in a destructor is undefined behavior in C++. Not using exceptions means Google Test's assertions are safe to use in destructors. + 1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing. + 1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code: +``` cpp +try { ... ASSERT_TRUE(...) ... } +catch (...) { ... } +``` +The above code will pass even if the `ASSERT_TRUE` throws. While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test. + +The downside of not using exceptions is that `ASSERT_*` (implemented +using `return`) will only abort the current function, not the current +`TEST`. + +## Why do we use two different macros for tests with and without fixtures? ## + +Unfortunately, C++'s macro system doesn't allow us to use the same +macro for both cases. One possibility is to provide only one macro +for tests with fixtures, and require the user to define an empty +fixture sometimes: + +``` cpp +class FooTest : public ::testing::Test {}; + +TEST_F(FooTest, DoesThis) { ... } +``` +or +``` cpp +typedef ::testing::Test FooTest; + +TEST_F(FooTest, DoesThat) { ... } +``` + +Yet, many people think this is one line too many. :-) Our goal was to +make it really easy to write tests, so we tried to make simple tests +trivial to create. That means using a separate macro for such tests. + +We think neither approach is ideal, yet either of them is reasonable. +In the end, it probably doesn't matter much either way. + +## Why don't we use structs as test fixtures? ## + +We like to use structs only when representing passive data. This +distinction between structs and classes is good for documenting the +intent of the code's author. Since test fixtures have logic like +`SetUp()` and `TearDown()`, they are better defined as classes. + +## Why are death tests implemented as assertions instead of using a test runner? ## + +Our goal was to make death tests as convenient for a user as C++ +possibly allows. In particular: + + * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect. The death test would be written in C++, while the runner spec may or may not be. A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative. + * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn. + * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will. You are not limited to one death test per test method. For example, you can write something like: +``` cpp + if (FooCondition()) { + ASSERT_DEATH(Bar(), "blah"); + } else { + ASSERT_EQ(5, Bar()); + } +``` +If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users. The fewer artificial limitations the better. + * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information. For example, +``` cpp + const int count = GetCount(); // Only known at run time. + for (int i = 1; i <= count; i++) { + ASSERT_DEATH({ + double* buffer = new double[i]; + ... initializes buffer ... + Foo(buffer, i) + }, "blah blah"); + } +``` +The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility. + +Another interesting thing about `ASSERT_DEATH` is that it calls `fork()` +to create a child process to run the death test. This is lightening +fast, as `fork()` uses copy-on-write pages and incurs almost zero +overhead, and the child process starts from the user-supplied +statement directly, skipping all global and local initialization and +any code leading to the given statement. If you launch the child +process from scratch, it can take seconds just to load everything and +start running if the test links to many libraries dynamically. + +## My death test modifies some state, but the change seems lost after the death test finishes. Why? ## + +Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their +respective sub-processes, but not in the parent process. You can think of them +as running in a parallel universe, more or less. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ## + +If your class has a static data member: + +``` cpp +// foo.h +class Foo { + ... + static const int kBar = 100; +}; +``` + +You also need to define it _outside_ of the class body in `foo.cc`: + +``` cpp +const int Foo::kBar; // No initializer here. +``` + +Otherwise your code is **invalid C++**, and may break in unexpected ways. In +particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc) +will generate an "undefined reference" linker error. + +## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ## + +Google Test doesn't yet have good support for this kind of tests, or +data-driven tests in general. We hope to be able to make improvements in this +area soon. + +## Can I derive a test fixture from another? ## + +Yes. + +Each test fixture has a corresponding and same named test case. This means only +one test case can use a particular fixture. Sometimes, however, multiple test +cases may want to use the same or slightly different fixtures. For example, you +may want to make sure that all of a GUI library's test cases don't leak +important system resources like fonts and brushes. + +In Google Test, you share a fixture among test cases by putting the shared +logic in a base test fixture, then deriving from that base a separate fixture +for each test case that wants to use this common logic. You then use `TEST_F()` +to write tests using each derived fixture. + +Typically, your code looks like this: + +``` cpp +// Defines a base test fixture. +class BaseTest : public ::testing::Test { + protected: + ... +}; + +// Derives a fixture FooTest from BaseTest. +class FooTest : public BaseTest { + protected: + virtual void SetUp() { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + virtual void TearDown() { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + ... functions and variables for FooTest ... +}; + +// Tests that use the fixture FooTest. +TEST_F(FooTest, Bar) { ... } +TEST_F(FooTest, Baz) { ... } + +... additional fixtures derived from BaseTest ... +``` + +If necessary, you can continue to derive test fixtures from a derived fixture. +Google Test has no limit on how deep the hierarchy can be. + +For a complete example using derived test fixtures, see +[sample5](../samples/sample5_unittest.cc). + +## My compiler complains "void value not ignored as it ought to be." What does this mean? ## + +You're probably using an `ASSERT_*()` in a function that doesn't return `void`. +`ASSERT_*()` can only be used in `void` functions. + +## My death test hangs (or seg-faults). How do I fix it? ## + +In Google Test, death tests are run in a child process and the way they work is +delicate. To write death tests you really need to understand how they work. +Please make sure you have read this. + +In particular, death tests don't like having multiple threads in the parent +process. So the first thing you can try is to eliminate creating threads +outside of `EXPECT_DEATH()`. + +Sometimes this is impossible as some library you must use may be creating +threads before `main()` is even reached. In this case, you can try to minimize +the chance of conflicts by either moving as many activities as possible inside +`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or +leaving as few things as possible in it. Also, you can try to set the death +test style to `"threadsafe"`, which is safer but slower, and see if it helps. + +If you go with thread-safe death tests, remember that they rerun the test +program from the beginning in the child process. Therefore make sure your +program can run side-by-side with itself and is deterministic. + +In the end, this boils down to good concurrent programming. You have to make +sure that there is no race conditions or dead locks in your program. No silver +bullet - sorry! + +## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ## + +The first thing to remember is that Google Test does not reuse the +same test fixture object across multiple tests. For each `TEST_F`, +Google Test will create a fresh test fixture object, _immediately_ +call `SetUp()`, run the test body, call `TearDown()`, and then +_immediately_ delete the test fixture object. + +When you need to write per-test set-up and tear-down logic, you have +the choice between using the test fixture constructor/destructor or +`SetUp()/TearDown()`. The former is usually preferred, as it has the +following benefits: + + * By initializing a member variable in the constructor, we have the option to make it `const`, which helps prevent accidental changes to its value and makes the tests more obviously correct. + * In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With `SetUp()/TearDown()`, a subclass may make the mistake of forgetting to call the base class' `SetUp()/TearDown()` or call them at the wrong moment. + +You may still want to use `SetUp()/TearDown()` in the following rare cases: + * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. + * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag. + * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overridden in a derived class, you have to use `SetUp()/TearDown()`. + +## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ## + +If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is +overloaded or a template, the compiler will have trouble figuring out which +overloaded version it should use. `ASSERT_PRED_FORMAT*` and +`EXPECT_PRED_FORMAT*` don't have this problem. + +If you see this error, you might want to switch to +`(ASSERT|EXPECT)_PRED_FORMAT*`, which will also give you a better failure +message. If, however, that is not an option, you can resolve the problem by +explicitly telling the compiler which version to pick. + +For example, suppose you have + +``` cpp +bool IsPositive(int n) { + return n > 0; +} +bool IsPositive(double x) { + return x > 0; +} +``` + +you will get a compiler error if you write + +``` cpp +EXPECT_PRED1(IsPositive, 5); +``` + +However, this will work: + +``` cpp +EXPECT_PRED1(static_cast(IsPositive), 5); +``` + +(The stuff inside the angled brackets for the `static_cast` operator is the +type of the function pointer for the `int`-version of `IsPositive()`.) + +As another example, when you have a template function + +``` cpp +template +bool IsNegative(T x) { + return x < 0; +} +``` + +you can use it in a predicate assertion like this: + +``` cpp +ASSERT_PRED1(IsNegative, -5); +``` + +Things are more interesting if your template has more than one parameters. The +following won't compile: + +``` cpp +ASSERT_PRED2(GreaterThan, 5, 0); +``` + + +as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, +which is one more than expected. The workaround is to wrap the predicate +function in parentheses: + +``` cpp +ASSERT_PRED2((GreaterThan), 5, 0); +``` + + +## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ## + +Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, +instead of + +``` cpp +return RUN_ALL_TESTS(); +``` + +they write + +``` cpp +RUN_ALL_TESTS(); +``` + +This is wrong and dangerous. A test runner needs to see the return value of +`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()` +function ignores it, your test will be considered successful even if it has a +Google Test assertion failure. Very bad. + +To help the users avoid this dangerous bug, the implementation of +`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is +ignored. If you see this warning, the fix is simple: just make sure its value +is used as the return value of `main()`. + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ## + +Due to a peculiarity of C++, in order to support the syntax for streaming +messages to an `ASSERT_*`, e.g. + +``` cpp +ASSERT_EQ(1, Foo()) << "blah blah" << foo; +``` + +we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and +`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the +content of your constructor/destructor to a private void member function, or +switch to `EXPECT_*()` if that works. This section in the user's guide explains +it. + +## My set-up function is not called. Why? ## + +C++ is case-sensitive. It should be spelled as `SetUp()`. Did you +spell it as `Setup()`? + +Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and +wonder why it's never called. + +## How do I jump to the line of a failure in Emacs directly? ## + +Google Test's failure message format is understood by Emacs and many other +IDEs, like acme and XCode. If a Google Test message is in a compilation buffer +in Emacs, then it's clickable. You can now hit `enter` on a message to jump to +the corresponding source code, or use `C-x `` to jump to the next failure. + +## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ## + +You don't have to. Instead of + +``` cpp +class FooTest : public BaseTest {}; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +class BarTest : public BaseTest {}; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +you can simply `typedef` the test fixtures: +``` cpp +typedef BaseTest FooTest; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef BaseTest BarTest; + +TEST_F(BarTest, Abc) { ... } +TEST_F(BarTest, Def) { ... } +``` + +## The Google Test output is buried in a whole bunch of log messages. What do I do? ## + +The Google Test output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the Google Test +output, making it hard to read. However, there is an easy solution to this +problem. + +Since most log messages go to stderr, we decided to let Google Test output go +to stdout. This way, you can easily separate the two using redirection. For +example: +``` +./my_test > googletest_output.txt +``` + +## Why should I prefer test fixtures over global variables? ## + +There are several good reasons: + 1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other. + 1. Global variables pollute the global namespace. + 1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common. + +## How do I test private class members without writing FRIEND\_TEST()s? ## + +You should try to write testable code, which means classes should be easily +tested from their public interface. One way to achieve this is the Pimpl idiom: +you move all private members of a class into a helper class, and make all +members of the helper class public. + +You have several other options that don't require using `FRIEND_TEST`: + * Write the tests as members of the fixture class: +``` cpp +class Foo { + friend class FooTest; + ... +}; + +class FooTest : public ::testing::Test { + protected: + ... + void Test1() {...} // This accesses private members of class Foo. + void Test2() {...} // So does this one. +}; + +TEST_F(FooTest, Test1) { + Test1(); +} + +TEST_F(FooTest, Test2) { + Test2(); +} +``` + * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests: +``` cpp +class Foo { + friend class FooTest; + ... +}; + +class FooTest : public ::testing::Test { + protected: + ... + T1 get_private_member1(Foo* obj) { + return obj->private_member1_; + } +}; + +TEST_F(FooTest, Test1) { + ... + get_private_member1(x) + ... +} +``` + * If the methods are declared **protected**, you can change their access level in a test-only subclass: +``` cpp +class YourClass { + ... + protected: // protected access for testability. + int DoSomethingReturningInt(); + ... +}; + +// in the your_class_test.cc file: +class TestableYourClass : public YourClass { + ... + public: using YourClass::DoSomethingReturningInt; // changes access rights + ... +}; + +TEST_F(YourClassTest, DoSomethingTest) { + TestableYourClass obj; + assertEquals(expected_value, obj.DoSomethingReturningInt()); +} +``` + +## How do I test private class static members without writing FRIEND\_TEST()s? ## + +We find private static methods clutter the header file. They are +implementation details and ideally should be kept out of a .h. So often I make +them free functions instead. + +Instead of: +``` cpp +// foo.h +class Foo { + ... + private: + static bool Func(int n); +}; + +// foo.cc +bool Foo::Func(int n) { ... } + +// foo_test.cc +EXPECT_TRUE(Foo::Func(12345)); +``` + +You probably should better write: +``` cpp +// foo.h +class Foo { + ... +}; + +// foo.cc +namespace internal { + bool Func(int n) { ... } +} + +// foo_test.cc +namespace internal { + bool Func(int n); +} + +EXPECT_TRUE(internal::Func(12345)); +``` + +## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ## + +No. You can use a feature called [value-parameterized tests](advanced.md#Value_Parameterized_Tests) which +lets you repeat your tests with different parameters, without defining it more than once. + +## How do I test a file that defines main()? ## + +To test a `foo.cc` file, you need to compile and link it into your unit test +program. However, when the file contains a definition for the `main()` +function, it will clash with the `main()` of your unit test, and will result in +a build error. + +The right solution is to split it into three files: + 1. `foo.h` which contains the declarations, + 1. `foo.cc` which contains the definitions except `main()`, and + 1. `foo_main.cc` which contains nothing but the definition of `main()`. + +Then `foo.cc` can be easily tested. + +If you are adding tests to an existing file and don't want an intrusive change +like this, there is a hack: just include the entire `foo.cc` file in your unit +test. For example: +``` cpp +// File foo_unittest.cc + +// The headers section +... + +// Renames main() in foo.cc to make room for the unit test main() +#define main FooMain + +#include "a/b/foo.cc" + +// The tests start here. +... +``` + + +However, please remember this is a hack and should only be used as the last +resort. + +## What can the statement argument in ASSERT\_DEATH() be? ## + +`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used +wherever `_statement_` is valid. So basically `_statement_` can be any C++ +statement that makes sense in the current context. In particular, it can +reference global and/or local variables, and can be: + * a simple function call (often the case), + * a complex expression, or + * a compound statement. + +Some examples are shown here: + +``` cpp +// A death test can be a simple function call. +TEST(MyDeathTest, FunctionCall) { + ASSERT_DEATH(Xyz(5), "Xyz failed"); +} + +// Or a complex expression that references variables and functions. +TEST(MyDeathTest, ComplexExpression) { + const bool c = Condition(); + ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), + "(Func1|Method) failed"); +} + +// Death assertions can be used any where in a function. In +// particular, they can be inside a loop. +TEST(MyDeathTest, InsideLoop) { + // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. + for (int i = 0; i < 5; i++) { + EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", + ::testing::Message() << "where i is " << i); + } +} + +// A death assertion can contain a compound statement. +TEST(MyDeathTest, CompoundStatement) { + // Verifies that at lease one of Bar(0), Bar(1), ..., and + // Bar(4) dies. + ASSERT_DEATH({ + for (int i = 0; i < 5; i++) { + Bar(i); + } + }, + "Bar has \\d+ errors");} +``` + +`googletest_unittest.cc` contains more examples if you are interested. + +## What syntax does the regular expression in ASSERT\_DEATH use? ## + +On POSIX systems, Google Test uses the POSIX Extended regular +expression syntax +(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). +On Windows, it uses a limited variant of regular expression +syntax. For more details, see the +[regular expression syntax](advanced.md#Regular_Expression_Syntax). + +## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ## + +Google Test needs to be able to create objects of your test fixture class, so +it must have a default constructor. Normally the compiler will define one for +you. However, there are cases where you have to define your own: + * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty. + * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.) + +## Why does ASSERT\_DEATH complain about previous threads that were already joined? ## + +With the Linux pthread library, there is no turning back once you cross the +line from single thread to multiple threads. The first time you create a +thread, a manager thread is created in addition, so you get 3, not 2, threads. +Later when the thread you create joins the main thread, the thread count +decrements by 1, but the manager thread will never be killed, so you still have +2 threads, which means you cannot safely run a death test. + +The new NPTL thread library doesn't suffer from this problem, as it doesn't +create a manager thread. However, if you don't control which machine your test +runs on, you shouldn't depend on this. + +## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ## + +Google Test does not interleave tests from different test cases. That is, it +runs all tests in one test case first, and then runs all tests in the next test +case, and so on. Google Test does this because it needs to set up a test case +before the first test in it is run, and tear it down afterwords. Splitting up +the test case would require multiple set-up and tear-down processes, which is +inefficient and makes the semantics unclean. + +If we were to determine the order of tests based on test name instead of test +case name, then we would have a problem with the following situation: + +``` cpp +TEST_F(FooTest, AbcDeathTest) { ... } +TEST_F(FooTest, Uvw) { ... } + +TEST_F(BarTest, DefDeathTest) { ... } +TEST_F(BarTest, Xyz) { ... } +``` + +Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't +interleave tests from different test cases, we need to run all tests in the +`FooTest` case before running any test in the `BarTest` case. This contradicts +with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. + +## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ## + +You don't have to, but if you like, you may split up the test case into +`FooTest` and `FooDeathTest`, where the names make it clear that they are +related: + +``` cpp +class FooTest : public ::testing::Test { ... }; + +TEST_F(FooTest, Abc) { ... } +TEST_F(FooTest, Def) { ... } + +typedef FooTest FooDeathTest; + +TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } +TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } +``` + +## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ## + +If you use a user-defined type `FooType` in an assertion, you must make sure +there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function +defined such that we can print a value of `FooType`. + +In addition, if `FooType` is declared in a name space, the `<<` operator also +needs to be defined in the _same_ name space. + +## How do I suppress the memory leak messages on Windows? ## + +Since the statically initialized Google Test singleton requires allocations on +the heap, the Visual C++ memory leak detector will report memory leaks at the +end of the program run. The easiest way to avoid this is to use the +`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any +statically initialized heap objects. See MSDN for more details and additional +heap check/debug routines. + +## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ## + +You may get a number of the following linker error or warnings if you +attempt to link your test project with the Google Test library when +your project and the are not built using the same compiler settings. + + * LNK2005: symbol already defined in object + * LNK4217: locally defined symbol 'symbol' imported in function 'function' + * LNK4049: locally defined symbol 'symbol' imported + +The Google Test project (gtest.vcproj) has the Runtime Library option +set to /MT (use multi-threaded static libraries, /MTd for debug). If +your project uses something else, for example /MD (use multi-threaded +DLLs, /MDd for debug), you need to change the setting in the Google +Test project to match your project's. + +To update this setting open the project properties in the Visual +Studio IDE then select the branch Configuration Properties | C/C++ | +Code Generation and change the option "Runtime Library". You may also try +using gtest-md.vcproj instead of gtest.vcproj. + +## I put my tests in a library and Google Test doesn't run them. What's happening? ## +Have you read a +[warning](primer.md#important-note-for-visual-c-users) on +the Google Test Primer page? + +## I want to use Google Test with Visual Studio but don't know where to start. ## +Many people are in your position and one of them posted his solution to our mailing list. + +## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ## +Google Test uses parts of the standard C++ library that SunStudio does not support. +Our users reported success using alternative implementations. Try running the build after running this command: + +`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'` + +## How can my code detect if it is running in a test? ## + +If you write code that sniffs whether it's running in a test and does +different things accordingly, you are leaking test-only logic into +production code and there is no easy way to ensure that the test-only +code paths aren't run by mistake in production. Such cleverness also +leads to +[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug). +Therefore we strongly advise against the practice, and Google Test doesn't +provide a way to do it. + +In general, the recommended way to cause the code to behave +differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html). +You can inject different functionality from the test and from the +production code. Since your production code doesn't link in the +for-test logic at all, there is no danger in accidentally running it. + +However, if you _really_, _really_, _really_ have no choice, and if +you follow the rule of ending your test program names with `_test`, +you can use the _horrible_ hack of sniffing your executable name +(`argv[0]` in `main()`) to know whether the code is under test. + +## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ## + +In C++, macros don't obey namespaces. Therefore two libraries that +both define a macro of the same name will clash if you `#include` both +definitions. In case a Google Test macro clashes with another +library, you can force Google Test to rename its macro to avoid the +conflict. + +Specifically, if both Google Test and some other code define macro +`FOO`, you can add +``` + -DGTEST_DONT_DEFINE_FOO=1 +``` +to the compiler flags to tell Google Test to change the macro's name +from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write +``` cpp + GTEST_TEST(SomeTest, DoesThis) { ... } +``` +instead of +``` cpp + TEST(SomeTest, DoesThis) { ... } +``` +in order to define a test. + +Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have . You can see the full list of covered macros [here](../include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file. + + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ## + +Yes. + +The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). + +``` cpp +namespace foo { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +TEST(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` + +However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name. + +``` cpp +namespace foo { +class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace foo + +namespace bar { +class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest +TEST_F(CoolTest, DoSomething) { + SUCCEED(); +} +} // namespace bar +``` + +## How do I build Google Testing Framework with Xcode 4? ## + +If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like +"Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](../README.md) file on how to resolve this. + +## How do I easily discover the flags needed for GoogleTest? ## + +GoogleTest (and GoogleMock) now support discovering all necessary flags using pkg-config. +See the [pkg-config guide](Pkgconfig.md) on how you can easily discover all compiler and +linker flags using pkg-config. + +## My question is not covered in your FAQ! ## + +If you cannot find the answer to your question in this FAQ, there are +some other resources you can use: + + 1. read other [wiki pages](../docs), + 1. search the mailing list [archive](https://groups.google.com/forum/#!forum/googletestframework), + 1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.). + +Please note that creating an issue in the +[issue tracker](https://github.com/google/googletest/issues) is _not_ +a good way to get your answer, as it is monitored infrequently by a +very small number of people. + +When asking a question, it's helpful to provide as much of the +following information as possible (people cannot help you if there's +not enough information in your question): + + * the version (or the commit hash if you check out from Git directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version), + * your operating system, + * the name and version of your compiler, + * the complete command line flags you give to your compiler, + * the complete compiler error messages (if the question is about compilation), + * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 561ad02..48ce894 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -290,7 +290,7 @@ To create a fixture, just: 1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes. 1. Inside the class, declare any objects you plan to use. 1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you. - 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](FAQ.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function). + 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](faq.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function). 1. If needed, define subroutines for your tests to share. When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to -- cgit v0.12 From 109f848bc83f6618bb12c15e92ea17d0cbba3c54 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 11 Jun 2018 11:54:27 -0400 Subject: Rename Samples.md to samples.md and adjust the links --- googletest/docs/Documentation.md | 2 +- googletest/docs/Samples.md | 14 -------------- googletest/docs/primer.md | 2 +- googletest/docs/samples.md | 14 ++++++++++++++ 4 files changed, 16 insertions(+), 16 deletions(-) delete mode 100644 googletest/docs/Samples.md create mode 100644 googletest/docs/samples.md diff --git a/googletest/docs/Documentation.md b/googletest/docs/Documentation.md index b6c77af..6c3bf7a 100644 --- a/googletest/docs/Documentation.md +++ b/googletest/docs/Documentation.md @@ -5,7 +5,7 @@ documentation for that specific version instead (e.g. by checking out the respective git branch/tag).** * [Primer](primer.md) -- start here if you are new to Google Test. - * [Samples](Samples.md) -- learn from examples. + * [Samples](samples.md) -- learn from examples. * [AdvancedGuide](advanced.md) -- learn more about Google Test. * [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac. * [Frequently-Asked Questions](faq.md) -- check here before asking a question on the mailing list. diff --git a/googletest/docs/Samples.md b/googletest/docs/Samples.md deleted file mode 100644 index f21d200..0000000 --- a/googletest/docs/Samples.md +++ /dev/null @@ -1,14 +0,0 @@ -If you're like us, you'd like to look at some Google Test sample code. The -[samples folder](../samples) has a number of well-commented samples showing how to use a -variety of Google Test features. - - * [Sample #1](../samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions. - * [Sample #2](../samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions. - * [Sample #3](../samples/sample3_unittest.cc) uses a test fixture. - * [Sample #4](../samples/sample4_unittest.cc) is another basic example of using Google Test. - * [Sample #5](../samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it. - * [Sample #6](../samples/sample6_unittest.cc) demonstrates type-parameterized tests. - * [Sample #7](../samples/sample7_unittest.cc) teaches the basics of value-parameterized tests. - * [Sample #8](../samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests. - * [Sample #9](../samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results. - * [Sample #10](../samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker. diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 48ce894..52b99f9 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -522,7 +522,7 @@ There is one more pitfall, though. If you use Google Test as a static library (t # Where to Go from Here # Congratulations! You've learned the Google Test basics. You can start writing -and running Google Test tests, read some [samples](Samples.md), or continue with +and running Google Test tests, read some [samples](samples.md), or continue with [AdvancedGuide](advanced.md), which describes many more useful Google Test features. # Known Limitations # diff --git a/googletest/docs/samples.md b/googletest/docs/samples.md new file mode 100644 index 0000000..f21d200 --- /dev/null +++ b/googletest/docs/samples.md @@ -0,0 +1,14 @@ +If you're like us, you'd like to look at some Google Test sample code. The +[samples folder](../samples) has a number of well-commented samples showing how to use a +variety of Google Test features. + + * [Sample #1](../samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions. + * [Sample #2](../samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions. + * [Sample #3](../samples/sample3_unittest.cc) uses a test fixture. + * [Sample #4](../samples/sample4_unittest.cc) is another basic example of using Google Test. + * [Sample #5](../samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it. + * [Sample #6](../samples/sample6_unittest.cc) demonstrates type-parameterized tests. + * [Sample #7](../samples/sample7_unittest.cc) teaches the basics of value-parameterized tests. + * [Sample #8](../samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests. + * [Sample #9](../samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results. + * [Sample #10](../samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker. -- cgit v0.12 From 0b958a03e9f757c5f744f09fac2f82b6d896561b Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 11 Jun 2018 12:07:45 -0400 Subject: Removed "Documentation.md" not adding value and not consitent with internal docs --- googlemock/docs/FrequentlyAskedQuestions.md | 1 - googletest/docs/Documentation.md | 16 ---------------- 2 files changed, 17 deletions(-) delete mode 100644 googletest/docs/Documentation.md diff --git a/googlemock/docs/FrequentlyAskedQuestions.md b/googlemock/docs/FrequentlyAskedQuestions.md index ccaa3d7..23f7da0 100644 --- a/googlemock/docs/FrequentlyAskedQuestions.md +++ b/googlemock/docs/FrequentlyAskedQuestions.md @@ -607,7 +607,6 @@ See this [recipe](CookBook.md#mocking_side_effects) for more details and an exam If you cannot find the answer to your question in this FAQ, there are some other resources you can use: - 1. read other [documentation](Documentation.md), 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). diff --git a/googletest/docs/Documentation.md b/googletest/docs/Documentation.md deleted file mode 100644 index 6c3bf7a..0000000 --- a/googletest/docs/Documentation.md +++ /dev/null @@ -1,16 +0,0 @@ -This page lists all documentation markdown files for Google Test **(the -current git version)** --- **if you use a former version of Google Test, please read the -documentation for that specific version instead (e.g. by checking out -the respective git branch/tag).** - - * [Primer](primer.md) -- start here if you are new to Google Test. - * [Samples](samples.md) -- learn from examples. - * [AdvancedGuide](advanced.md) -- learn more about Google Test. - * [XcodeGuide](XcodeGuide.md) -- how to use Google Test in Xcode on Mac. - * [Frequently-Asked Questions](faq.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Test, read: - - * [CONTRIBUTING](../../CONTRIBUTING.md) -- read this _before_ writing your first patch. - * [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files. -- cgit v0.12 From 95a96e1c1dee0c5a0635f8a46eb844b7c3192c51 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 11 Jun 2018 13:12:14 -0400 Subject: Sync with internal docs --- googletest/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/README.md b/googletest/README.md index 225aba2..b6c29a6 100644 --- a/googletest/README.md +++ b/googletest/README.md @@ -54,7 +54,7 @@ it. ### Using CMake ### Google Test comes with a CMake build script ( -[CMakeLists.txt](CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for +[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for cross-platform.). If you don't have CMake installed already, you can download it for free from . -- cgit v0.12 From 025f48f89b426d83f7c46dc723b5758773452878 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 11 Jun 2018 16:11:55 -0400 Subject: Sync with internal docs --- googletest/README.md | 355 ++++++++++++++++++++++++--------------------------- 1 file changed, 168 insertions(+), 187 deletions(-) diff --git a/googletest/README.md b/googletest/README.md index b6c29a6..e30fe80 100644 --- a/googletest/README.md +++ b/googletest/README.md @@ -1,23 +1,21 @@ +### Generic Build Instructions -### Generic Build Instructions ### +#### Setup -#### Setup #### +To build Google Test and your tests that use it, you need to tell your build +system where to find its headers and source files. The exact way to do it +depends on which build system you use, and is usually straightforward. -To build Google Test and your tests that use it, you need to tell your -build system where to find its headers and source files. The exact -way to do it depends on which build system you use, and is usually -straightforward. +#### Build -#### Build #### - -Suppose you put Google Test in directory `${GTEST_DIR}`. To build it, -create a library build target (or a project as called by Visual Studio -and Xcode) to compile +Suppose you put Google Test in directory `${GTEST_DIR}`. To build it, create a +library build target (or a project as called by Visual Studio and Xcode) to +compile ${GTEST_DIR}/src/gtest-all.cc with `${GTEST_DIR}/include` in the system header search path and `${GTEST_DIR}` -in the normal header search path. Assuming a Linux-like system and gcc, +in the normal header search path. Assuming a Linux-like system and gcc, something like the following will do: g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ @@ -26,105 +24,101 @@ something like the following will do: (We need `-pthread` as Google Test uses threads.) -Next, you should compile your test source file with -`${GTEST_DIR}/include` in the system header search path, and link it -with gtest and any other necessary libraries: +Next, you should compile your test source file with `${GTEST_DIR}/include` in +the system header search path, and link it with gtest and any other necessary +libraries: g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \ -o your_test -As an example, the make/ directory contains a Makefile that you can -use to build Google Test on systems where GNU make is available -(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google -Test's own tests. Instead, it just builds the Google Test library and -a sample test. You can use it as a starting point for your own build -script. +As an example, the make/ directory contains a Makefile that you can use to build +Google Test on systems where GNU make is available (e.g. Linux, Mac OS X, and +Cygwin). It doesn't try to build Google Test's own tests. Instead, it just +builds the Google Test library and a sample test. You can use it as a starting +point for your own build script. -If the default settings are correct for your environment, the -following commands should succeed: +If the default settings are correct for your environment, the following commands +should succeed: cd ${GTEST_DIR}/make make ./sample1_unittest -If you see errors, try to tweak the contents of `make/Makefile` to make -them go away. There are instructions in `make/Makefile` on how to do -it. +If you see errors, try to tweak the contents of `make/Makefile` to make them go +away. There are instructions in `make/Makefile` on how to do it. -### Using CMake ### +### Using CMake Google Test comes with a CMake build script ( -[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt)) that can be used on a wide range of platforms ("C" stands for -cross-platform.). If you don't have CMake installed already, you can -download it for free from . +[CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt)) +that can be used on a wide range of platforms ("C" stands for cross-platform.). +If you don't have CMake installed already, you can download it for free from +. -CMake works by generating native makefiles or build projects that can -be used in the compiler environment of your choice. You can either -build Google Test as a standalone project or it can be incorporated -into an existing CMake build for another project. +CMake works by generating native makefiles or build projects that can be used in +the compiler environment of your choice. You can either build Google Test as a +standalone project or it can be incorporated into an existing CMake build for +another project. -#### Standalone CMake Project #### +#### Standalone CMake Project -When building Google Test as a standalone project, the typical -workflow starts with: +When building Google Test as a standalone project, the typical workflow starts +with: mkdir mybuild # Create a directory to hold the build output. cd mybuild cmake ${GTEST_DIR} # Generate native build scripts. -If you want to build Google Test's samples, you should replace the -last command with +If you want to build Google Test's samples, you should replace the last command +with cmake -Dgtest_build_samples=ON ${GTEST_DIR} -If you are on a \*nix system, you should now see a Makefile in the -current directory. Just type 'make' to build gtest. +If you are on a \*nix system, you should now see a Makefile in the current +directory. Just type 'make' to build gtest. -If you use Windows and have Visual Studio installed, a `gtest.sln` file -and several `.vcproj` files will be created. You can then build them -using Visual Studio. +If you use Windows and have Visual Studio installed, a `gtest.sln` file and +several `.vcproj` files will be created. You can then build them using Visual +Studio. On Mac OS X with Xcode installed, a `.xcodeproj` file will be generated. -#### Incorporating Into An Existing CMake Project #### - -If you want to use gtest in a project which already uses CMake, then a -more robust and flexible approach is to build gtest as part of that -project directly. This is done by making the GoogleTest source code -available to the main build and adding it using CMake's -`add_subdirectory()` command. This has the significant advantage that -the same compiler and linker settings are used between gtest and the -rest of your project, so issues associated with using incompatible -libraries (eg debug/release), etc. are avoided. This is particularly -useful on Windows. Making GoogleTest's source code available to the +#### Incorporating Into An Existing CMake Project + +If you want to use gtest in a project which already uses CMake, then a more +robust and flexible approach is to build gtest as part of that project directly. +This is done by making the GoogleTest source code available to the main build +and adding it using CMake's `add_subdirectory()` command. This has the +significant advantage that the same compiler and linker settings are used +between gtest and the rest of your project, so issues associated with using +incompatible libraries (eg debug/release), etc. are avoided. This is +particularly useful on Windows. Making GoogleTest's source code available to the main build can be done a few different ways: -* Download the GoogleTest source code manually and place it at a - known location. This is the least flexible approach and can make - it more difficult to use with continuous integration systems, etc. -* Embed the GoogleTest source code as a direct copy in the main - project's source tree. This is often the simplest approach, but is - also the hardest to keep up to date. Some organizations may not - permit this method. -* Add GoogleTest as a git submodule or equivalent. This may not - always be possible or appropriate. Git submodules, for example, - have their own set of advantages and drawbacks. -* Use CMake to download GoogleTest as part of the build's configure - step. This is just a little more complex, but doesn't have the - limitations of the other methods. - -The last of the above methods is implemented with a small piece -of CMake code in a separate file (e.g. `CMakeLists.txt.in`) which -is copied to the build area and then invoked as a sub-build -_during the CMake stage_. That directory is then pulled into the -main build with `add_subdirectory()`. For example: +* Download the GoogleTest source code manually and place it at a known + location. This is the least flexible approach and can make it more difficult + to use with continuous integration systems, etc. +* Embed the GoogleTest source code as a direct copy in the main project's + source tree. This is often the simplest approach, but is also the hardest to + keep up to date. Some organizations may not permit this method. +* Add GoogleTest as a git submodule or equivalent. This may not always be + possible or appropriate. Git submodules, for example, have their own set of + advantages and drawbacks. +* Use CMake to download GoogleTest as part of the build's configure step. This + is just a little more complex, but doesn't have the limitations of the other + methods. + +The last of the above methods is implemented with a small piece of CMake code in +a separate file (e.g. `CMakeLists.txt.in`) which is copied to the build area and +then invoked as a sub-build _during the CMake stage_. That directory is then +pulled into the main build with `add_subdirectory()`. For example: New file `CMakeLists.txt.in`: cmake_minimum_required(VERSION 2.8.2) - + project(googletest-download NONE) - + include(ExternalProject) ExternalProject_Add(googletest GIT_REPOSITORY https://github.com/google/googletest.git @@ -136,7 +130,7 @@ New file `CMakeLists.txt.in`: INSTALL_COMMAND "" TEST_COMMAND "" ) - + Existing build's `CMakeLists.txt`: # Download and unpack googletest at configure time @@ -157,7 +151,7 @@ Existing build's `CMakeLists.txt`: # Prevent overriding the parent project's compiler/linker # settings on Windows set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - + # Add googletest directly to our build. This defines # the gtest and gtest_main targets. add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src @@ -176,101 +170,93 @@ Existing build's `CMakeLists.txt`: target_link_libraries(example gtest_main) add_test(NAME example_test COMMAND example) -Note that this approach requires CMake 2.8.2 or later due to -its use of the `ExternalProject_Add()` command. The above -technique is discussed in more detail in -[this separate article](http://crascit.com/2015/07/25/cmake-gtest/) -which also contains a link to a fully generalized implementation -of the technique. +Note that this approach requires CMake 2.8.2 or later due to its use of the +`ExternalProject_Add()` command. The above technique is discussed in more detail +in [this separate article](http://crascit.com/2015/07/25/cmake-gtest/) which +also contains a link to a fully generalized implementation of the technique. -##### Visual Studio Dynamic vs Static Runtimes ##### +##### Visual Studio Dynamic vs Static Runtimes -By default, new Visual Studio projects link the C runtimes dynamically -but Google Test links them statically. -This will generate an error that looks something like the following: - gtest.lib(gtest-all.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MDd_DynamicDebug' in main.obj +By default, new Visual Studio projects link the C runtimes dynamically but +Google Test links them statically. This will generate an error that looks +something like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch +detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value +'MDd_DynamicDebug' in main.obj Google Test already has a CMake option for this: `gtest_force_shared_crt` -Enabling this option will make gtest link the runtimes dynamically too, -and match the project in which it is included. +Enabling this option will make gtest link the runtimes dynamically too, and +match the project in which it is included. -### Legacy Build Scripts ### +### Legacy Build Scripts Before settling on CMake, we have been providing hand-maintained build -projects/scripts for Visual Studio, Xcode, and Autotools. While we -continue to provide them for convenience, they are not actively -maintained any more. We highly recommend that you follow the -instructions in the above sections to integrate Google Test -with your existing build system. +projects/scripts for Visual Studio, Xcode, and Autotools. While we continue to +provide them for convenience, they are not actively maintained any more. We +highly recommend that you follow the instructions in the above sections to +integrate Google Test with your existing build system. If you still need to use the legacy build scripts, here's how: -The msvc\ folder contains two solutions with Visual C++ projects. -Open the `gtest.sln` or `gtest-md.sln` file using Visual Studio, and you -are ready to build Google Test the same way you build any Visual -Studio project. Files that have names ending with -md use DLL -versions of Microsoft runtime libraries (the /MD or the /MDd compiler -option). Files without that suffix use static versions of the runtime -libraries (the /MT or the /MTd option). Please note that one must use -the same option to compile both gtest and the test code. If you use -Visual Studio 2005 or above, we recommend the -md version as /MD is -the default for new projects in these versions of Visual Studio. - -On Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using -Xcode. Build the "gtest" target. The universal binary framework will -end up in your selected build directory (selected in the Xcode -"Preferences..." -> "Building" pane and defaults to xcode/build). -Alternatively, at the command line, enter: +The msvc\ folder contains two solutions with Visual C++ projects. Open the +`gtest.sln` or `gtest-md.sln` file using Visual Studio, and you are ready to +build Google Test the same way you build any Visual Studio project. Files that +have names ending with -md use DLL versions of Microsoft runtime libraries (the +/MD or the /MDd compiler option). Files without that suffix use static versions +of the runtime libraries (the /MT or the /MTd option). Please note that one must +use the same option to compile both gtest and the test code. If you use Visual +Studio 2005 or above, we recommend the -md version as /MD is the default for new +projects in these versions of Visual Studio. + +On Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using Xcode. +Build the "gtest" target. The universal binary framework will end up in your +selected build directory (selected in the Xcode "Preferences..." -> "Building" +pane and defaults to xcode/build). Alternatively, at the command line, enter: xcodebuild -This will build the "Release" configuration of gtest.framework in your -default build location. See the "xcodebuild" man page for more -information about building different configurations and building in -different locations. +This will build the "Release" configuration of gtest.framework in your default +build location. See the "xcodebuild" man page for more information about +building different configurations and building in different locations. -If you wish to use the Google Test Xcode project with Xcode 4.x and -above, you need to either: +If you wish to use the Google Test Xcode project with Xcode 4.x and above, you +need to either: - * update the SDK configuration options in xcode/Config/General.xconfig. - Comment options `SDKROOT`, `MACOS_DEPLOYMENT_TARGET`, and `GCC_VERSION`. If - you choose this route you lose the ability to target earlier versions - of MacOS X. - * Install an SDK for an earlier version. This doesn't appear to be - supported by Apple, but has been reported to work - (http://stackoverflow.com/questions/5378518). +* update the SDK configuration options in xcode/Config/General.xconfig. + Comment options `SDKROOT`, `MACOS_DEPLOYMENT_TARGET`, and `GCC_VERSION`. If + you choose this route you lose the ability to target earlier versions of + MacOS X. +* Install an SDK for an earlier version. This doesn't appear to be supported + by Apple, but has been reported to work + (http://stackoverflow.com/questions/5378518). -### Tweaking Google Test ### +### Tweaking Google Test -Google Test can be used in diverse environments. The default -configuration may not work (or may not work well) out of the box in -some environments. However, you can easily tweak Google Test by -defining control macros on the compiler command line. Generally, -these macros are named like `GTEST_XYZ` and you define them to either 1 -or 0 to enable or disable a certain feature. +Google Test can be used in diverse environments. The default configuration may +not work (or may not work well) out of the box in some environments. However, +you can easily tweak Google Test by defining control macros on the compiler +command line. Generally, these macros are named like `GTEST_XYZ` and you define +them to either 1 or 0 to enable or disable a certain feature. -We list the most frequently used macros below. For a complete list, -see file [include/gtest/internal/gtest-port.h](include/gtest/internal/gtest-port.h). +We list the most frequently used macros below. For a complete list, see file +[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/include/gtest/internal/gtest-port.h). -### Choosing a TR1 Tuple Library ### +### Choosing a TR1 Tuple Library -Some Google Test features require the C++ Technical Report 1 (TR1) -tuple library, which is not yet available with all compilers. The -good news is that Google Test implements a subset of TR1 tuple that's -enough for its own need, and will automatically use this when the -compiler doesn't provide TR1 tuple. +Some Google Test features require the C++ Technical Report 1 (TR1) tuple +library, which is not yet available with all compilers. The good news is that +Google Test implements a subset of TR1 tuple that's enough for its own need, and +will automatically use this when the compiler doesn't provide TR1 tuple. -Usually you don't need to care about which tuple library Google Test -uses. However, if your project already uses TR1 tuple, you need to -tell Google Test to use the same TR1 tuple library the rest of your -project uses, or the two tuple implementations will clash. To do -that, add +Usually you don't need to care about which tuple library Google Test uses. +However, if your project already uses TR1 tuple, you need to tell Google Test to +use the same TR1 tuple library the rest of your project uses, or the two tuple +implementations will clash. To do that, add -DGTEST_USE_OWN_TR1_TUPLE=0 -to the compiler flags while compiling Google Test and your tests. If -you want to force Google Test to use its own tuple library, just add +to the compiler flags while compiling Google Test and your tests. If you want to +force Google Test to use its own tuple library, just add -DGTEST_USE_OWN_TR1_TUPLE=1 @@ -282,15 +268,15 @@ If you don't want Google Test to use tuple at all, add and all features using tuple will be disabled. -### Multi-threaded Tests ### +### Multi-threaded Tests -Google Test is thread-safe where the pthread library is available. -After `#include "gtest/gtest.h"`, you can check the `GTEST_IS_THREADSAFE` -macro to see whether this is the case (yes if the macro is `#defined` to -1, no if it's undefined.). +Google Test is thread-safe where the pthread library is available. After +`#include "gtest/gtest.h"`, you can check the `GTEST_IS_THREADSAFE` macro to see +whether this is the case (yes if the macro is `#defined` to 1, no if it's +undefined.). -If Google Test doesn't correctly detect whether pthread is available -in your environment, you can force it with +If Google Test doesn't correctly detect whether pthread is available in your +environment, you can force it with -DGTEST_HAS_PTHREAD=1 @@ -298,26 +284,24 @@ or -DGTEST_HAS_PTHREAD=0 -When Google Test uses pthread, you may need to add flags to your -compiler and/or linker to select the pthread library, or you'll get -link errors. If you use the CMake script or the deprecated Autotools -script, this is taken care of for you. If you use your own build -script, you'll need to read your compiler and linker's manual to -figure out what flags to add. +When Google Test uses pthread, you may need to add flags to your compiler and/or +linker to select the pthread library, or you'll get link errors. If you use the +CMake script or the deprecated Autotools script, this is taken care of for you. +If you use your own build script, you'll need to read your compiler and linker's +manual to figure out what flags to add. -### As a Shared Library (DLL) ### +### As a Shared Library (DLL) -Google Test is compact, so most users can build and link it as a -static library for the simplicity. You can choose to use Google Test -as a shared library (known as a DLL on Windows) if you prefer. +Google Test is compact, so most users can build and link it as a static library +for the simplicity. You can choose to use Google Test as a shared library (known +as a DLL on Windows) if you prefer. To compile *gtest* as a shared library, add -DGTEST_CREATE_SHARED_LIBRARY=1 -to the compiler flags. You'll also need to tell the linker to produce -a shared library instead - consult your linker's manual for how to do -it. +to the compiler flags. You'll also need to tell the linker to produce a shared +library instead - consult your linker's manual for how to do it. To compile your *tests* that use the gtest shared library, add @@ -325,31 +309,28 @@ To compile your *tests* that use the gtest shared library, add to the compiler flags. -Note: while the above steps aren't technically necessary today when -using some compilers (e.g. GCC), they may become necessary in the -future, if we decide to improve the speed of loading the library (see - for details). Therefore you are -recommended to always add the above flags when using Google Test as a -shared library. Otherwise a future release of Google Test may break -your build script. +Note: while the above steps aren't technically necessary today when using some +compilers (e.g. GCC), they may become necessary in the future, if we decide to +improve the speed of loading the library (see + for details). Therefore you are recommended +to always add the above flags when using Google Test as a shared library. +Otherwise a future release of Google Test may break your build script. -### Avoiding Macro Name Clashes ### +### Avoiding Macro Name Clashes -In C++, macros don't obey namespaces. Therefore two libraries that -both define a macro of the same name will clash if you `#include` both -definitions. In case a Google Test macro clashes with another -library, you can force Google Test to rename its macro to avoid the -conflict. +In C++, macros don't obey namespaces. Therefore two libraries that both define a +macro of the same name will clash if you `#include` both definitions. In case a +Google Test macro clashes with another library, you can force Google Test to +rename its macro to avoid the conflict. -Specifically, if both Google Test and some other code define macro -FOO, you can add +Specifically, if both Google Test and some other code define macro FOO, you can +add -DGTEST_DONT_DEFINE_FOO=1 -to the compiler flags to tell Google Test to change the macro's name -from `FOO` to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, -or `TEST`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll -need to write +to the compiler flags to tell Google Test to change the macro's name from `FOO` +to `GTEST_FOO`. Currently `FOO` can be `FAIL`, `SUCCEED`, or `TEST`. For +example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write GTEST_TEST(SomeTest, DoesThis) { ... } -- cgit v0.12 From f4d0631a3970d88199a56883e6148ada05aed7b5 Mon Sep 17 00:00:00 2001 From: Takuto Ikuta Date: Tue, 12 Jun 2018 18:06:29 +0900 Subject: Reduce the number of strcmp calling while initialization When we do parallel test execution with a process for a test, initialization of gtest become performance bottleneck when the test binary contains many testcases. Especially, some parameterlized test in chromium browser affected by largely when address sanitizer is enabled. Address sanitizer does not allow using optimized strcmp function and test addition in parameterized test require lookup of test case using strcmp. This patch reduces the number of strcmp, it is called when registering parameterized test. Using reverse iterator improves the time to find registered tests in such case. Some tests for chromium browser using address sanitizer finished 2x faster with this patch. --- googletest/src/gtest.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 3498ffe..bd6ab7b 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -4907,11 +4907,11 @@ TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) { // Can we find a TestCase with the given name? - const std::vector::const_iterator test_case = - std::find_if(test_cases_.begin(), test_cases_.end(), + const std::vector::const_reverse_iterator test_case = + std::find_if(test_cases_.rbegin(), test_cases_.rend(), TestCaseNameIs(test_case_name)); - if (test_case != test_cases_.end()) + if (test_case != test_cases_.rend()) return *test_case; // No. Let's create one. -- cgit v0.12 From 6a484baf0674085b090cc201557aaf1f2c4b7be7 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 13 Jun 2018 14:26:24 -0400 Subject: Doc sync/internal --- googletest/docs/faq.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index a886bdc..30c64e3 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -1023,7 +1023,7 @@ Yes. The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). -``` cpp +```c++ namespace foo { TEST(CoolTest, DoSomething) { SUCCEED(); @@ -1039,7 +1039,7 @@ TEST(CoolTest, DoSomething) { However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name. -``` cpp +```c++ namespace foo { class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest TEST_F(CoolTest, DoSomething) { -- cgit v0.12 From 3847aecb5f1baca96ad974eccfc1e9ed264eec3a Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 13 Jun 2018 14:29:26 -0400 Subject: Docs sync/internal --- googletest/docs/faq.md | 64 +++++++++++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index 30c64e3..1e2c341 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -76,7 +76,7 @@ for simplicity we just say that it cannot start with `_`.). It may seem fine for `TestCaseName` and `TestName` to contain `_` in the middle. However, consider this: -``` cpp +```c++ TEST(Time, Flies_Like_An_Arrow) { ... } TEST(Time_Flies, Like_An_Arrow) { ... } ``` @@ -242,7 +242,7 @@ of this approach: 1. Throwing in a destructor is undefined behavior in C++. Not using exceptions means Google Test's assertions are safe to use in destructors. 1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing. 1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code: -``` cpp +```c++ try { ... ASSERT_TRUE(...) ... } catch (...) { ... } ``` @@ -259,13 +259,13 @@ macro for both cases. One possibility is to provide only one macro for tests with fixtures, and require the user to define an empty fixture sometimes: -``` cpp +```c++ class FooTest : public ::testing::Test {}; TEST_F(FooTest, DoesThis) { ... } ``` or -``` cpp +```c++ typedef ::testing::Test FooTest; TEST_F(FooTest, DoesThat) { ... } @@ -293,7 +293,7 @@ possibly allows. In particular: * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect. The death test would be written in C++, while the runner spec may or may not be. A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative. * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn. * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will. You are not limited to one death test per test method. For example, you can write something like: -``` cpp +```c++ if (FooCondition()) { ASSERT_DEATH(Bar(), "blah"); } else { @@ -302,7 +302,7 @@ possibly allows. In particular: ``` If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users. The fewer artificial limitations the better. * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information. For example, -``` cpp +```c++ const int count = GetCount(); // Only known at run time. for (int i = 1; i <= count; i++) { ASSERT_DEATH({ @@ -335,7 +335,7 @@ as running in a parallel universe, more or less. If your class has a static data member: -``` cpp +```c++ // foo.h class Foo { ... @@ -345,7 +345,7 @@ class Foo { You also need to define it _outside_ of the class body in `foo.cc`: -``` cpp +```c++ const int Foo::kBar; // No initializer here. ``` @@ -376,7 +376,7 @@ to write tests using each derived fixture. Typically, your code looks like this: -``` cpp +```c++ // Defines a base test fixture. class BaseTest : public ::testing::Test { protected: @@ -476,7 +476,7 @@ explicitly telling the compiler which version to pick. For example, suppose you have -``` cpp +```c++ bool IsPositive(int n) { return n > 0; } @@ -487,13 +487,13 @@ bool IsPositive(double x) { you will get a compiler error if you write -``` cpp +```c++ EXPECT_PRED1(IsPositive, 5); ``` However, this will work: -``` cpp +```c++ EXPECT_PRED1(static_cast(IsPositive), 5); ``` @@ -502,7 +502,7 @@ type of the function pointer for the `int`-version of `IsPositive()`.) As another example, when you have a template function -``` cpp +```c++ template bool IsNegative(T x) { return x < 0; @@ -511,14 +511,14 @@ bool IsNegative(T x) { you can use it in a predicate assertion like this: -``` cpp +```c++ ASSERT_PRED1(IsNegative, -5); ``` Things are more interesting if your template has more than one parameters. The following won't compile: -``` cpp +```c++ ASSERT_PRED2(GreaterThan, 5, 0); ``` @@ -527,7 +527,7 @@ as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which is one more than expected. The workaround is to wrap the predicate function in parentheses: -``` cpp +```c++ ASSERT_PRED2((GreaterThan), 5, 0); ``` @@ -537,13 +537,13 @@ ASSERT_PRED2((GreaterThan), 5, 0); Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, instead of -``` cpp +```c++ return RUN_ALL_TESTS(); ``` they write -``` cpp +```c++ RUN_ALL_TESTS(); ``` @@ -562,7 +562,7 @@ is used as the return value of `main()`. Due to a peculiarity of C++, in order to support the syntax for streaming messages to an `ASSERT_*`, e.g. -``` cpp +```c++ ASSERT_EQ(1, Foo()) << "blah blah" << foo; ``` @@ -591,7 +591,7 @@ the corresponding source code, or use `C-x `` to jump to the next failure. You don't have to. Instead of -``` cpp +```c++ class FooTest : public BaseTest {}; TEST_F(FooTest, Abc) { ... } @@ -604,7 +604,7 @@ TEST_F(BarTest, Def) { ... } ``` you can simply `typedef` the test fixtures: -``` cpp +```c++ typedef BaseTest FooTest; TEST_F(FooTest, Abc) { ... } @@ -646,7 +646,7 @@ members of the helper class public. You have several other options that don't require using `FRIEND_TEST`: * Write the tests as members of the fixture class: -``` cpp +```c++ class Foo { friend class FooTest; ... @@ -668,7 +668,7 @@ TEST_F(FooTest, Test2) { } ``` * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests: -``` cpp +```c++ class Foo { friend class FooTest; ... @@ -689,7 +689,7 @@ TEST_F(FooTest, Test1) { } ``` * If the methods are declared **protected**, you can change their access level in a test-only subclass: -``` cpp +```c++ class YourClass { ... protected: // protected access for testability. @@ -717,7 +717,7 @@ implementation details and ideally should be kept out of a .h. So often I make them free functions instead. Instead of: -``` cpp +```c++ // foo.h class Foo { ... @@ -733,7 +733,7 @@ EXPECT_TRUE(Foo::Func(12345)); ``` You probably should better write: -``` cpp +```c++ // foo.h class Foo { ... @@ -774,7 +774,7 @@ Then `foo.cc` can be easily tested. If you are adding tests to an existing file and don't want an intrusive change like this, there is a hack: just include the entire `foo.cc` file in your unit test. For example: -``` cpp +```c++ // File foo_unittest.cc // The headers section @@ -805,7 +805,7 @@ reference global and/or local variables, and can be: Some examples are shown here: -``` cpp +```c++ // A death test can be a simple function call. TEST(MyDeathTest, FunctionCall) { ASSERT_DEATH(Xyz(5), "Xyz failed"); @@ -884,7 +884,7 @@ inefficient and makes the semantics unclean. If we were to determine the order of tests based on test name instead of test case name, then we would have a problem with the following situation: -``` cpp +```c++ TEST_F(FooTest, AbcDeathTest) { ... } TEST_F(FooTest, Uvw) { ... } @@ -903,7 +903,7 @@ You don't have to, but if you like, you may split up the test case into `FooTest` and `FooDeathTest`, where the names make it clear that they are related: -``` cpp +```c++ class FooTest : public ::testing::Test { ... }; TEST_F(FooTest, Abc) { ... } @@ -1005,11 +1005,11 @@ Specifically, if both Google Test and some other code define macro ``` to the compiler flags to tell Google Test to change the macro's name from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write -``` cpp +```c++ GTEST_TEST(SomeTest, DoesThis) { ... } ``` instead of -``` cpp +```c++ TEST(SomeTest, DoesThis) { ... } ``` in order to define a test. -- cgit v0.12 From c7ec59381fe305655b596381c338aedf929a44f5 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 13 Jun 2018 15:47:07 -0400 Subject: ignore .md for appveyor builds --- appveyor.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/appveyor.yml b/appveyor.yml index 94b1c3a..b1da655 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -78,6 +78,11 @@ build_script: throw "Exec: $ErrorMessage" } + +skip_commits: + files: + - '**/*.md' + test_script: - ps: | # Only enable some builds for pull requests, the AppVeyor queue is too long. -- cgit v0.12 From 0563b52d3acc5661792cf1f8c78661a050afc883 Mon Sep 17 00:00:00 2001 From: Rohan Joyce Date: Thu, 7 Jun 2018 12:17:33 -0400 Subject: Eliminate GTEST_TEST_FILTER_ENV_VAR_. GTEST_TEST_FILTER_ENV_VAR_ was used to specify an environment variable to obtain the default test filter from. By default it was unset which broke "--test_filter" for bazel. This CL eliminates GTEST_TEST_FILTER_ENV_VAR_ and explicitly obtains the default test filter from the environment variable TESTBRIDGE_TEST_ONLY if it exists. --- .../include/gtest/internal/custom/gtest-port.h | 5 -- googletest/src/gtest.cc | 7 ++- googletest/test/BUILD.bazel | 16 ++++++ googletest/test/gtest_testbridge_test.py | 65 ++++++++++++++++++++++ googletest/test/gtest_testbridge_test_.cc | 44 +++++++++++++++ 5 files changed, 129 insertions(+), 8 deletions(-) create mode 100644 googletest/test/gtest_testbridge_test.py create mode 100644 googletest/test/gtest_testbridge_test_.cc diff --git a/googletest/include/gtest/internal/custom/gtest-port.h b/googletest/include/gtest/internal/custom/gtest-port.h index 94884c1..aa5da29 100644 --- a/googletest/include/gtest/internal/custom/gtest-port.h +++ b/googletest/include/gtest/internal/custom/gtest-port.h @@ -41,11 +41,6 @@ // GTEST_DEFINE_int32_(name, default_val, doc) // GTEST_DEFINE_string_(name, default_val, doc) // -// Test filtering: -// GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that -// will be used if --GTEST_FLAG(test_filter) -// is not provided. -// // Logging: // GTEST_LOG_(severity) // GTEST_CHECK_(condition) diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index bd6ab7b..ce6c07f 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -184,13 +184,14 @@ bool g_help_flag = false; } // namespace internal +// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY +// environment variable. static const char* GetDefaultFilter() { -#ifdef GTEST_TEST_FILTER_ENV_VAR_ - const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_); + const char* const testbridge_test_only = + internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY"); if (testbridge_test_only != NULL) { return testbridge_test_only; } -#endif // GTEST_TEST_FILTER_ENV_VAR_ return kUniversalFilter; } diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 6ea18ec..365a855 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -378,3 +378,19 @@ py_test( data = [":gtest_uninitialized_test_"], deps = [":gtest_test_utils"], ) + +cc_binary( + name = "gtest_testbridge_test_", + testonly = 1, + srcs = ["gtest_testbridge_test_.cc"], + deps = ["//:gtest_main"], +) + +# Tests that filtering via testbridge works +py_test( + name = "gtest_testbridge_test", + size = "small", + srcs = ["gtest_testbridge_test.py"], + data = [":gtest_testbridge_test_"], + deps = [":gtest_test_utils"], +) diff --git a/googletest/test/gtest_testbridge_test.py b/googletest/test/gtest_testbridge_test.py new file mode 100644 index 0000000..2075e12 --- /dev/null +++ b/googletest/test/gtest_testbridge_test.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# +# Copyright 2018 Google LLC. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +"""Verifies that Google Test uses filter provided via testbridge.""" + +__author__ = 'rfj@google.com (Rohan Joyce)' + +import os + +import gtest_test_utils + +binary_name = 'gtest_testbridge_test_' +COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name) +TESTBRIDGE_NAME = 'TESTBRIDGE_TEST_ONLY' + + +def Assert(condition): + if not condition: + raise AssertionError + + +class GTestTestFilterTest(gtest_test_utils.TestCase): + + def testTestExecutionIsFiltered(self): + """Tests that the test filter is picked up from the testbridge env var.""" + subprocess_env = os.environ.copy() + + subprocess_env[TESTBRIDGE_NAME] = '*.TestThatSucceeds' + p = gtest_test_utils.Subprocess(COMMAND, env=subprocess_env) + + self.assertEquals(0, p.exit_code) + + Assert('filter = *.TestThatSucceeds' in p.output) + Assert('[ OK ] TestFilterTest.TestThatSucceeds' in p.output) + Assert('[ PASSED ] 1 test.' in p.output) + + +if __name__ == '__main__': + gtest_test_utils.Main() diff --git a/googletest/test/gtest_testbridge_test_.cc b/googletest/test/gtest_testbridge_test_.cc new file mode 100644 index 0000000..0bb069e --- /dev/null +++ b/googletest/test/gtest_testbridge_test_.cc @@ -0,0 +1,44 @@ +// Copyright 2018, Google LLC. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: rfj@google.com (Rohan Joyce) + +// This program is meant to be run by gtest_test_filter_test.py. Do not run +// it directly. + +#include "gtest/gtest.h" + +// These tests are used to detect if filtering is working. Only +// 'TestThatSucceeds' should ever run. + +TEST(TestFilterTest, TestThatSucceeds) {} + +TEST(TestFilterTest, TestThatFails) { + ASSERT_TRUE(false) << "This test should never be run."; +} -- cgit v0.12 From 03ea2fdecb7a4d554813ca6d38cd8c221932f9c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=9C=E4=BF=AE=E6=9D=8F?= Date: Fri, 29 Jun 2018 11:19:46 +0800 Subject: VS2005 with SP1(_MSC_VER=1400) already supports __pragma --- googletest/include/gtest/internal/gtest-port.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 437a4ed..d5ec086 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -313,7 +313,7 @@ // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() -#if _MSC_VER >= 1500 +#if _MSC_VER >= 1400 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ __pragma(warning(push)) \ __pragma(warning(disable: warnings)) -- cgit v0.12 From 4bcc9b9807b256e2a59daabb86156f8658031b68 Mon Sep 17 00:00:00 2001 From: Masaru Tsuchiyama Date: Wed, 23 May 2018 21:11:45 +0900 Subject: This closes #1595: fix compiler error with Visual Studio 2017 on Win10 JP. non-ASCII charactors are interpreted as Shift-JIS on the environment. But the charators in the files are non Shift-JIS charactors and the compiler stops compiling with C4819. To fix the errors, remove non-ASCII charactors. --- googlemock/include/gmock/gmock-generated-function-mockers.h | 8 ++++---- googlemock/include/gmock/gmock-generated-function-mockers.h.pump | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index 126c48c..b8bf7a5 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -352,21 +352,21 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Removes const from this, calls overload 1 // return AdjustConstness_(this)->gmock_GetName(); // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Does not remove const, calls overload 3 // return AdjustConstness_const(this)->gmock_GetName(); // } diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index efcb3e8..6426d9a 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -114,21 +114,21 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Removes const from this, calls overload 1 // return AdjustConstness_(this)->gmock_GetName(); // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { +// const WithoutMatchers&, const Function*) const { // // Does not remove const, calls overload 3 // return AdjustConstness_const(this)->gmock_GetName(); // } -- cgit v0.12 From 4c417877648f5f240aecead1c19d7c1fd340423b Mon Sep 17 00:00:00 2001 From: Derek Mauro Date: Tue, 10 Jul 2018 14:30:42 -0400 Subject: Adds stacktrace support from Abseil to Google Test This change adds the ability to generate stacktraces in Google Test on both failures of assertions/expectations and on crashes. The stacktrace support is conditionally available only when using Abseil with Google Test. To use this support, run the test under Bazel with a command like this: bazel test --define absl=1 --test_env=GTEST_INSTALL_FAILURE_SIGNAL_HANDLER=1 //path/to/your:test The "--define absl=1" part enables stacktraces on assertion/expectation failures. The "--test_env=GTEST_INSTALL_FAILURE_SIGNAL_HANDLER=1" part enables the signal handler that logs a stacktrace in the event of a crash (this also requires the "--define absl=1" part). This is not the default since it may interfere with existing tests. --- BUILD.bazel | 38 ++-- googletest/src/gtest-internal-inl.h | 10 + googletest/src/gtest.cc | 86 ++++++++- googletest/test/BUILD.bazel | 62 +++++-- googletest/test/gtest_output_test.py | 14 +- googletest/test/gtest_output_test_golden_lin.txt | 222 ++++++++++++++++++++++- googletest/test/gtest_xml_output_unittest.py | 7 +- 7 files changed, 391 insertions(+), 48 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index 6d82829..2ed3bf6 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -38,7 +38,7 @@ licenses(["notice"]) config_setting( name = "windows", - values = { "cpu": "x64_windows" }, + values = {"cpu": "x64_windows"}, ) config_setting( @@ -51,7 +51,6 @@ config_setting( values = {"define": "absl=1"}, ) - # Google Test including Google Mock cc_library( name = "gtest", @@ -70,7 +69,7 @@ cc_library( "googlemock/src/gmock_main.cc", ], ), - hdrs =glob([ + hdrs = glob([ "googletest/include/gtest/*.h", "googlemock/include/gmock/*.h", ]), @@ -81,6 +80,14 @@ cc_library( "//conditions:default": ["-pthread"], }, ), + defines = select( + { + ":has_absl": [ + "GTEST_HAS_ABSL=1", + ], + "//conditions:default": [], + }, + ), includes = [ "googlemock", "googlemock/include", @@ -94,21 +101,18 @@ cc_library( "-pthread", ], }), - defines = select ({ - ":has_absl": [ - "GTEST_HAS_ABSL=1", - ], - "//conditions:default": [], - } + deps = select( + { + ":has_absl": [ + "@com_google_absl//absl/debugging:failure_signal_handler", + "@com_google_absl//absl/debugging:stacktrace", + "@com_google_absl//absl/debugging:symbolize", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:optional", + ], + "//conditions:default": [], + }, ), - deps = select ({ - ":has_absl": [ - "@com_google_absl//absl/types:optional", - "@com_google_absl//absl/strings" - ], - "//conditions:default": [], - } - ) ) cc_library( diff --git a/googletest/src/gtest-internal-inl.h b/googletest/src/gtest-internal-inl.h index e77c8b6..c5a4265 100644 --- a/googletest/src/gtest-internal-inl.h +++ b/googletest/src/gtest-internal-inl.h @@ -446,6 +446,16 @@ class OsStackTraceGetter : public OsStackTraceGetterInterface { virtual void UponLeavingGTest(); private: +#if GTEST_HAS_ABSL + Mutex mutex_; // Protects all internal state. + + // We save the stack frame below the frame that calls user code. + // We do this because the address of the frame immediately below + // the user code changes between the call to UponLeavingGTest() + // and any calls to the stack trace code from within the user code. + void* caller_frame_ = nullptr; +#endif // GTEST_HAS_ABSL + GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index ce6c07f..9c25c99 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -139,6 +139,13 @@ # define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS +#if GTEST_HAS_ABSL +#include "absl/debugging/failure_signal_handler.h" +#include "absl/debugging/stacktrace.h" +#include "absl/debugging/symbolize.h" +#include "absl/strings/str_cat.h" +#endif // GTEST_HAS_ABSL + namespace testing { using internal::CountIf; @@ -228,6 +235,13 @@ GTEST_DEFINE_string_( "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); +GTEST_DEFINE_bool_( + install_failure_signal_handler, + internal::BoolFromGTestEnv("install_failure_signal_handler", false), + "If true and supported on the current platform, " GTEST_NAME_ " should " + "install a signal handler that dumps debugging information when fatal " + "signals are raised."); + GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); @@ -4243,12 +4257,67 @@ void StreamingListener::SocketWriter::MakeConnection() { const char* const OsStackTraceGetterInterface::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; -std::string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, - int /*skip_count*/) { +std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) + GTEST_LOCK_EXCLUDED_(mutex_) { +#if GTEST_HAS_ABSL + std::string result; + + if (max_depth <= 0) { + return result; + } + + max_depth = std::min(max_depth, kMaxStackTraceDepth); + + std::vector raw_stack(max_depth); + // Skips the frames requested by the caller, plus this function. + const int raw_stack_size = + absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1); + + void* caller_frame = nullptr; + { + MutexLock lock(&mutex_); + caller_frame = caller_frame_; + } + + for (int i = 0; i < raw_stack_size; ++i) { + if (raw_stack[i] == caller_frame && + !GTEST_FLAG(show_internal_stack_frames)) { + // Add a marker to the trace and stop adding frames. + absl::StrAppend(&result, kElidedFramesMarker, "\n"); + break; + } + + char tmp[1024]; + const char* symbol = "(unknown)"; + if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) { + symbol = tmp; + } + + char line[1024]; + snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol); + result += line; + } + + return result; + +#else // !GTEST_HAS_ABSL + static_cast(max_depth); + static_cast(skip_count); return ""; +#endif // GTEST_HAS_ABSL } -void OsStackTraceGetter::UponLeavingGTest() {} +void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { +#if GTEST_HAS_ABSL + void* caller_frame = nullptr; + if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) { + caller_frame = nullptr; + } + + MutexLock lock(&mutex_); + caller_frame_ = caller_frame; +#endif // GTEST_HAS_ABSL +} // A helper class that creates the premature-exit file in its // constructor and deletes the file in its destructor. @@ -4865,6 +4934,13 @@ void UnitTestImpl::PostFlagParsingInit() { // Configures listeners for streaming test results to the specified server. ConfigureStreamingOutput(); #endif // GTEST_CAN_STREAM_RESULTS_ + +#if GTEST_HAS_ABSL + if (GTEST_FLAG(install_failure_signal_handler)) { + absl::FailureSignalHandlerOptions options; + absl::InstallFailureSignalHandler(options); + } +#endif // GTEST_HAS_ABSL } } @@ -5769,6 +5845,10 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { g_argvs.push_back(StreamableToString(argv[i])); } +#if GTEST_HAS_ABSL + absl::InitializeSymbolizer(g_argvs[0].c_str()); +#endif // GTEST_HAS_ABSL + ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 365a855..405feee 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -34,35 +34,48 @@ licenses(["notice"]) -""" gtest own tests """ +config_setting( + name = "windows", + values = {"cpu": "x64_windows"}, +) + +config_setting( + name = "windows_msvc", + values = {"cpu": "x64_windows_msvc"}, +) + +config_setting( + name = "has_absl", + values = {"define": "absl=1"}, +) #on windows exclude gtest-tuple.h and gtest-tuple_test.cc cc_test( name = "gtest_all_test", size = "small", - srcs = glob( - include = [ - "gtest-*.cc", - "*.h", - "googletest/include/gtest/**/*.h", - ], - exclude = [ - "gtest-unittest-api_test.cc", - "gtest-tuple_test.cc", - "googletest/src/gtest-all.cc", - "gtest_all_test.cc", - "gtest-death-test_ex_test.cc", - "gtest-listener_test.cc", - "gtest-unittest-api_test.cc", - "gtest-param-test_test.cc", - ], - ) + select({ + srcs = glob( + include = [ + "gtest-*.cc", + "*.h", + "googletest/include/gtest/**/*.h", + ], + exclude = [ + "gtest-unittest-api_test.cc", + "gtest-tuple_test.cc", + "googletest/src/gtest-all.cc", + "gtest_all_test.cc", + "gtest-death-test_ex_test.cc", + "gtest-listener_test.cc", + "gtest-unittest-api_test.cc", + "gtest-param-test_test.cc", + ], + ) + select({ "//:windows": [], "//:windows_msvc": [], "//conditions:default": [ "gtest-tuple_test.cc", ], - }), + }), copts = select({ "//:windows": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], "//:windows_msvc": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], @@ -135,7 +148,6 @@ py_library( name = "gtest_test_utils", testonly = 1, srcs = ["gtest_test_utils.py"], - ) cc_binary( @@ -144,6 +156,7 @@ cc_binary( srcs = ["gtest_help_test_.cc"], deps = ["//:gtest_main"], ) + py_test( name = "gtest_help_test", size = "small", @@ -163,6 +176,10 @@ py_test( name = "gtest_output_test", size = "small", srcs = ["gtest_output_test.py"], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), data = [ "gtest_output_test_golden_lin.txt", ":gtest_output_test_", @@ -176,6 +193,7 @@ cc_binary( srcs = ["gtest_color_test_.cc"], deps = ["//:gtest"], ) + py_test( name = "gtest_color_test", size = "small", @@ -327,6 +345,10 @@ py_test( "gtest_xml_output_unittest.py", "gtest_xml_test_utils.py", ], + args = select({ + ":has_absl": [], + "//conditions:default": ["--no_stacktrace_support"], + }), data = [ # We invoke gtest_no_test_unittest to verify the XML output # when the test program contains no test definition. diff --git a/googletest/test/gtest_output_test.py b/googletest/test/gtest_output_test.py index f83d3be..63763b9 100755 --- a/googletest/test/gtest_output_test.py +++ b/googletest/test/gtest_output_test.py @@ -52,6 +52,9 @@ import gtest_test_utils GENGOLDEN_FLAG = '--gengolden' CATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS' +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' IS_WINDOWS = os.name == 'nt' @@ -252,13 +255,12 @@ test_list = GetShellCommandOutput(COMMAND_LIST_TESTS) SUPPORTS_DEATH_TESTS = 'DeathTest' in test_list SUPPORTS_TYPED_TESTS = 'TypedTest' in test_list SUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list -SUPPORTS_STACK_TRACES = IS_LINUX +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS and SUPPORTS_THREADS and - SUPPORTS_STACK_TRACES and - not IS_WINDOWS) + SUPPORTS_STACK_TRACES) class GTestOutputTest(gtest_test_utils.TestCase): def RemoveUnsupportedTests(self, test_output): @@ -325,7 +327,11 @@ class GTestOutputTest(gtest_test_utils.TestCase): if __name__ == '__main__': - if sys.argv[1:] == [GENGOLDEN_FLAG]: + if NO_STACKTRACE_SUPPORT_FLAG in sys.argv: + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) + + if GENGOLDEN_FLAG in sys.argv: if CAN_GENERATE_GOLDEN_FILE: output = GetOutputOfAllCommands() golden_file = open(GOLDEN_PATH, 'wb') diff --git a/googletest/test/gtest_output_test_golden_lin.txt b/googletest/test/gtest_output_test_golden_lin.txt index cbcb720..02a77a8 100644 --- a/googletest/test/gtest_output_test_golden_lin.txt +++ b/googletest/test/gtest_output_test_golden_lin.txt @@ -4,10 +4,14 @@ gtest_output_test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: 2 3 +Stack trace: (omitted) + [==========] Running 68 tests from 30 test cases. [----------] Global test environment set-up. FooEnvironment::SetUp() called. @@ -40,12 +44,16 @@ Expected equality of these values: Which is: "\"Line" actual Which is: "actual \"string\"" +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: golden Which is: "\"Line" actual Which is: "actual \"string\"" +Stack trace: (omitted) + [ FAILED ] NonfatalFailureTest.EscapesStringOperands [ RUN ] NonfatalFailureTest.DiffForLongStrings gtest_output_test_.cc:#: Failure @@ -58,6 +66,8 @@ With diff: -\"Line\0 1\" Line 2 +Stack trace: (omitted) + [ FAILED ] NonfatalFailureTest.DiffForLongStrings [----------] 3 tests from FatalFailureTest [ RUN ] FatalFailureTest.FatalFailureInSubroutine @@ -67,6 +77,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInSubroutine [ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine (expecting a failure that x should be 1) @@ -75,6 +87,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine [ RUN ] FatalFailureTest.NonfatalFailureInSubroutine (expecting a failure on false) @@ -82,6 +96,8 @@ gtest_output_test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine [----------] 1 test from LoggingTest [ RUN ] LoggingTest.InterleavingLoggingAndAssertions @@ -90,10 +106,14 @@ i == 0 i == 1 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + i == 2 i == 3 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + [ FAILED ] LoggingTest.InterleavingLoggingAndAssertions [----------] 7 tests from SCOPED_TRACETest [ RUN ] SCOPED_TRACETest.AcceptedValues @@ -105,20 +125,28 @@ gtest_output_test_.cc:#: (null) gtest_output_test_.cc:#: 1337 gtest_output_test_.cc:#: std::string gtest_output_test_.cc:#: literal string +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.AcceptedValues [ RUN ] SCOPED_TRACETest.ObeysScopes (expected to fail) gtest_output_test_.cc:#: Failure Failed This failure is expected, and shouldn't have a trace. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and should have a trace. Google Test trace: gtest_output_test_.cc:#: Expected trace +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and shouldn't have a trace. +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.ObeysScopes [ RUN ] SCOPED_TRACETest.WorksInLoop (expected to fail) @@ -129,6 +157,8 @@ Expected equality of these values: Which is: 1 Google Test trace: gtest_output_test_.cc:#: i = 1 +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: 1 @@ -136,6 +166,8 @@ Expected equality of these values: Which is: 2 Google Test trace: gtest_output_test_.cc:#: i = 2 +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.WorksInLoop [ RUN ] SCOPED_TRACETest.WorksInSubroutine (expected to fail) @@ -146,6 +178,8 @@ Expected equality of these values: Which is: 1 Google Test trace: gtest_output_test_.cc:#: n = 1 +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Expected equality of these values: 1 @@ -153,6 +187,8 @@ Expected equality of these values: Which is: 2 Google Test trace: gtest_output_test_.cc:#: n = 2 +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.WorksInSubroutine [ RUN ] SCOPED_TRACETest.CanBeNested (expected to fail) @@ -164,6 +200,8 @@ Expected equality of these values: Google Test trace: gtest_output_test_.cc:#: n = 2 gtest_output_test_.cc:#: +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.CanBeNested [ RUN ] SCOPED_TRACETest.CanBeRepeated (expected to fail) @@ -172,12 +210,16 @@ Failed This failure is expected, and should contain trace point A. Google Test trace: gtest_output_test_.cc:#: A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and should contain trace point A and B. Google Test trace: gtest_output_test_.cc:#: B gtest_output_test_.cc:#: A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and should contain trace point A, B, and C. @@ -185,6 +227,8 @@ Google Test trace: gtest_output_test_.cc:#: C gtest_output_test_.cc:#: B gtest_output_test_.cc:#: A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed This failure is expected, and should contain trace point A, B, and D. @@ -192,6 +236,8 @@ Google Test trace: gtest_output_test_.cc:#: D gtest_output_test_.cc:#: B gtest_output_test_.cc:#: A +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.CanBeRepeated [ RUN ] SCOPED_TRACETest.WorksConcurrently (expecting 6 failures) @@ -200,27 +246,39 @@ Failed Expected failure #1 (in thread B, only trace B alive). Google Test trace: gtest_output_test_.cc:#: Trace B +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2 (in thread A, trace A & B both alive). Google Test trace: gtest_output_test_.cc:#: Trace A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3 (in thread B, trace A & B both alive). Google Test trace: gtest_output_test_.cc:#: Trace B +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #4 (in thread B, only trace A alive). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #5 (in thread A, only trace A alive). Google Test trace: gtest_output_test_.cc:#: Trace A +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #6 (in thread A, no trace alive). +Stack trace: (omitted) + [ FAILED ] SCOPED_TRACETest.WorksConcurrently [----------] 1 test from ScopedTraceTest [ RUN ] ScopedTraceTest.WithExplicitFileAndLine @@ -229,6 +287,8 @@ Failed Check that the trace is attached to a particular location. Google Test trace: explicit_file.cc:123: expected trace message +Stack trace: (omitted) + [ FAILED ] ScopedTraceTest.WithExplicitFileAndLine [----------] 1 test from NonFatalFailureInFixtureConstructorTest [ RUN ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor @@ -236,18 +296,28 @@ explicit_file.cc:123: expected trace message gtest_output_test_.cc:#: Failure Failed Expected failure #1, in the test fixture c'tor. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in SetUp(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3, in the test body. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #4, in TearDown. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #5, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] NonFatalFailureInFixtureConstructorTest.FailureInConstructor [----------] 1 test from FatalFailureInFixtureConstructorTest [ RUN ] FatalFailureInFixtureConstructorTest.FailureInConstructor @@ -255,9 +325,13 @@ Expected failure #5, in the test fixture d'tor. gtest_output_test_.cc:#: Failure Failed Expected failure #1, in the test fixture c'tor. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] FatalFailureInFixtureConstructorTest.FailureInConstructor [----------] 1 test from NonFatalFailureInSetUpTest [ RUN ] NonFatalFailureInSetUpTest.FailureInSetUp @@ -265,15 +339,23 @@ Expected failure #2, in the test fixture d'tor. gtest_output_test_.cc:#: Failure Failed Expected failure #1, in SetUp(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in the test function. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3, in TearDown(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #4, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] NonFatalFailureInSetUpTest.FailureInSetUp [----------] 1 test from FatalFailureInSetUpTest [ RUN ] FatalFailureInSetUpTest.FailureInSetUp @@ -281,18 +363,26 @@ Expected failure #4, in the test fixture d'tor. gtest_output_test_.cc:#: Failure Failed Expected failure #1, in SetUp(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #2, in TearDown(). +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected failure #3, in the test fixture d'tor. +Stack trace: (omitted) + [ FAILED ] FatalFailureInSetUpTest.FailureInSetUp [----------] 1 test from AddFailureAtTest [ RUN ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber foo.cc:42: Failure Failed Expected failure in foo.cc +Stack trace: (omitted) + [ FAILED ] AddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber [----------] 4 tests from MixedUpTestCaseTest [ RUN ] MixedUpTestCaseTest.FirstTestFromNamespaceFoo @@ -309,6 +399,8 @@ using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one of the classes to put the tests into different test cases. +Stack trace: (omitted) + [ FAILED ] MixedUpTestCaseTest.ThisShouldFail [ RUN ] MixedUpTestCaseTest.ThisShouldFailToo gtest.cc:#: Failure @@ -320,6 +412,8 @@ using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one of the classes to put the tests into different test cases. +Stack trace: (omitted) + [ FAILED ] MixedUpTestCaseTest.ThisShouldFailToo [----------] 2 tests from MixedUpTestCaseWithSameTestNameTest [ RUN ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail @@ -334,6 +428,8 @@ using two different test fixture classes. This can happen if the two classes are from different namespaces or translation units and have the same name. You should probably rename one of the classes to put the tests into different test cases. +Stack trace: (omitted) + [ FAILED ] MixedUpTestCaseWithSameTestNameTest.TheSecondTestWithThisNameShouldFail [----------] 2 tests from TEST_F_before_TEST_in_same_test_case [ RUN ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F @@ -348,6 +444,8 @@ test DefinedUsingTEST_F is defined using TEST_F but test DefinedUsingTESTAndShouldFail is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test case. +Stack trace: (omitted) + [ FAILED ] TEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail [----------] 2 tests from TEST_before_TEST_F_in_same_test_case [ RUN ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST @@ -362,6 +460,8 @@ test DefinedUsingTEST_FAndShouldFail is defined using TEST_F but test DefinedUsingTEST is defined using TEST. You probably want to change the TEST to TEST_F or move it to another test case. +Stack trace: (omitted) + [ FAILED ] TEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail [----------] 8 tests from ExpectNonfatalFailureTest [ RUN ] ExpectNonfatalFailureTest.CanReferenceGlobalVariables @@ -375,6 +475,8 @@ case. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure [ RUN ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures (expecting a failure) @@ -384,10 +486,16 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure 1. +Stack trace: (omitted) + gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure 2. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures [ RUN ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure @@ -398,6 +506,10 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure [ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementReturns @@ -405,12 +517,16 @@ Expected fatal failure. gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementReturns [ RUN ] ExpectNonfatalFailureTest.FailsWhenStatementThrows (expecting a failure) gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectNonfatalFailureTest.FailsWhenStatementThrows [----------] 8 tests from ExpectFatalFailureTest [ RUN ] ExpectFatalFailureTest.CanReferenceGlobalVariables @@ -424,6 +540,8 @@ Expected: 1 non-fatal failure gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure [ RUN ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures (expecting a failure) @@ -433,10 +551,16 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures [ RUN ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure @@ -447,6 +571,10 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure [ RUN ] ExpectFatalFailureTest.FailsWhenStatementReturns @@ -454,12 +582,16 @@ Expected non-fatal failure. gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFatalFailureTest.FailsWhenStatementReturns [ RUN ] ExpectFatalFailureTest.FailsWhenStatementThrows (expecting a failure) gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFatalFailureTest.FailsWhenStatementThrows [----------] 2 tests from TypedTest/0, where TypeParam = int [ RUN ] TypedTest/0.Success @@ -471,6 +603,8 @@ Expected equality of these values: TypeParam() Which is: 0 Expected failure +Stack trace: (omitted) + [ FAILED ] TypedTest/0.Failure, where TypeParam = int [----------] 2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char [ RUN ] Unsigned/TypedTestP/0.Success @@ -483,8 +617,10 @@ Expected equality of these values: TypeParam() Which is: '\0' Expected failure +Stack trace: (omitted) + [ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char -[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned +[----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int [ RUN ] Unsigned/TypedTestP/1.Success [ OK ] Unsigned/TypedTestP/1.Success [ RUN ] Unsigned/TypedTestP/1.Failure @@ -495,7 +631,9 @@ Expected equality of these values: TypeParam() Which is: 0 Expected failure -[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned +Stack trace: (omitted) + +[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int [----------] 4 tests from ExpectFailureTest [ RUN ] ExpectFailureTest.ExpectFatalFailure (expecting 1 failure) @@ -504,6 +642,10 @@ Expected: 1 fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -512,6 +654,10 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -520,6 +666,10 @@ Expected: 1 fatal failure containing "Some other fatal failure expected." gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectFatalFailure [ RUN ] ExpectFailureTest.ExpectNonFatalFailure @@ -529,6 +679,10 @@ Expected: 1 non-fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -537,6 +691,10 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -545,6 +703,10 @@ Expected: 1 non-fatal failure containing "Some other non-fatal failure." gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectNonFatalFailure [ RUN ] ExpectFailureTest.ExpectFatalFailureOnAllThreads @@ -554,6 +716,10 @@ Expected: 1 fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -562,6 +728,10 @@ Expected: 1 fatal failure gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -570,6 +740,10 @@ Expected: 1 fatal failure containing "Some other fatal failure expected." gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads [ RUN ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads @@ -579,6 +753,10 @@ Expected: 1 non-fatal failure Actual: gtest_output_test_.cc:#: Success: Succeeded +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -587,6 +765,10 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Fatal failure: Failed Expected fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) (expecting 1 failure) gtest.cc:#: Failure @@ -595,6 +777,10 @@ Expected: 1 non-fatal failure containing "Some other non-fatal failure." gtest_output_test_.cc:#: Non-fatal failure: Failed Expected non-fatal failure. +Stack trace: (omitted) + + +Stack trace: (omitted) [ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads [----------] 2 tests from ExpectFailureWithThreadsTest @@ -603,18 +789,26 @@ Expected non-fatal failure. gtest_output_test_.cc:#: Failure Failed Expected fatal failure. +Stack trace: (omitted) + gtest.cc:#: Failure Expected: 1 fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFailureWithThreadsTest.ExpectFatalFailure [ RUN ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure (expecting 2 failures) gtest_output_test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + gtest.cc:#: Failure Expected: 1 non-fatal failure Actual: 0 failures +Stack trace: (omitted) + [ FAILED ] ExpectFailureWithThreadsTest.ExpectNonFatalFailure [----------] 1 test from ScopedFakeTestPartResultReporterTest [ RUN ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread @@ -622,9 +816,13 @@ Expected: 1 non-fatal failure gtest_output_test_.cc:#: Failure Failed Expected fatal failure. +Stack trace: (omitted) + gtest_output_test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + [ FAILED ] ScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread [----------] 1 test from PrintingFailingParams/FailingParamTest [ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 @@ -633,6 +831,8 @@ Expected equality of these values: 1 GetParam() Which is: 2 +Stack trace: (omitted) + [ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [----------] 2 tests from PrintingStrings/ParamTest [ RUN ] PrintingStrings/ParamTest.Success/a @@ -644,16 +844,22 @@ Expected equality of these values: GetParam() Which is: "a" Expected failure +Stack trace: (omitted) + [ FAILED ] PrintingStrings/ParamTest.Failure/a, where GetParam() = "a" [----------] Global test environment tear-down BarEnvironment::TearDown() called. gtest_output_test_.cc:#: Failure Failed Expected non-fatal failure. +Stack trace: (omitted) + FooEnvironment::TearDown() called. gtest_output_test_.cc:#: Failure Failed Expected fatal failure. +Stack trace: (omitted) + [==========] 68 tests from 30 test cases ran. [ PASSED ] 22 tests. [ FAILED ] 46 tests, listed below: @@ -693,7 +899,7 @@ Expected fatal failure. [ FAILED ] ExpectFatalFailureTest.FailsWhenStatementThrows [ FAILED ] TypedTest/0.Failure, where TypeParam = int [ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char -[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned +[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int [ FAILED ] ExpectFailureTest.ExpectFatalFailure [ FAILED ] ExpectFailureTest.ExpectNonFatalFailure [ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads @@ -718,6 +924,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInSubroutine (? ms) [ RUN ] FatalFailureTest.FatalFailureInNestedSubroutine (expecting a failure that x should be 1) @@ -726,6 +934,8 @@ Expected equality of these values: 1 x Which is: 2 +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms) [ RUN ] FatalFailureTest.NonfatalFailureInSubroutine (expecting a failure on false) @@ -733,6 +943,8 @@ gtest_output_test_.cc:#: Failure Value of: false Actual: false Expected: true +Stack trace: (omitted) + [ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine (? ms) [----------] 3 tests from FatalFailureTest (? ms total) @@ -743,10 +955,14 @@ i == 0 i == 1 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 9 +Stack trace: (omitted) + i == 2 i == 3 gtest_output_test_.cc:#: Failure Expected: (3) >= (a[i]), actual: 3 vs 6 +Stack trace: (omitted) + [ FAILED ] LoggingTest.InterleavingLoggingAndAssertions (? ms) [----------] 1 test from LoggingTest (? ms total) diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py index 6ffb6e3..faedd4e 100755 --- a/googletest/test/gtest_xml_output_unittest.py +++ b/googletest/test/gtest_xml_output_unittest.py @@ -47,17 +47,22 @@ GTEST_OUTPUT_FLAG = '--gtest_output' GTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml' GTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_' +# The flag indicating stacktraces are not supported +NO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support' + # The environment variables for test sharding. TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' SHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE' -SUPPORTS_STACK_TRACES = False +SUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv if SUPPORTS_STACK_TRACES: STACK_TRACE_TEMPLATE = '\nStack trace:\n*' else: STACK_TRACE_TEMPLATE = '' + # unittest.main() can't handle unknown flags + sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG) EXPECTED_NON_EMPTY_XML = """ -- cgit v0.12 From d772e2039b2dd4ebd137659e8d6297e6cf04697e Mon Sep 17 00:00:00 2001 From: Derek Mauro Date: Tue, 10 Jul 2018 15:39:23 -0400 Subject: Pass the --no_stacktrace_support argument to the CMake tests This does the same thing to the CMake tests that is done to the Bazel tests, and now makes the CMake tests pass. --- googletest/CMakeLists.txt | 4 ++-- googletest/cmake/internal_utils.cmake | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index b09c46e..2e412d7 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -284,7 +284,7 @@ if (gtest_build_tests) py_test(gtest_list_tests_unittest) cxx_executable(gtest_output_test_ test gtest) - py_test(gtest_output_test) + py_test(gtest_output_test --no_stacktrace_support) cxx_executable(gtest_shuffle_test_ test gtest) py_test(gtest_shuffle_test) @@ -307,6 +307,6 @@ if (gtest_build_tests) py_test(gtest_json_outfiles_test) cxx_executable(gtest_xml_output_unittest_ test gtest) - py_test(gtest_xml_output_unittest) + py_test(gtest_xml_output_unittest --no_stacktrace_support) py_test(gtest_json_output_unittest) endif() diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index 6448918..be7af38 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -257,14 +257,14 @@ function(py_test name) add_test( NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$) + --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$ ${ARGN}) else (CMAKE_CONFIGURATION_TYPES) # Single-configuration build generators like Makefile generators # don't have subdirs below CMAKE_CURRENT_BINARY_DIR. add_test( NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR}) + --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN}) endif (CMAKE_CONFIGURATION_TYPES) else (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1) # ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can @@ -274,7 +274,7 @@ function(py_test name) add_test( ${name} ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py - --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE}) + --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE} ${ARGN}) endif (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1) endif(PYTHONINTERP_FOUND) endfunction() -- cgit v0.12 From 50daf299c2783647460797ef6a9933c01570648f Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 10 Jul 2018 17:14:49 -0400 Subject: Docs sync [ci skip] --- googletest/docs/primer.md | 652 ++++++++++++++++++++++++--------------------- googletest/docs/samples.md | 34 ++- 2 files changed, 373 insertions(+), 313 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 52b99f9..6c33ebb 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -1,27 +1,48 @@ - - -# Introduction: Why Google C++ Testing Framework? # - -_Google C++ Testing Framework_ helps you write better C++ tests. - -No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, -Google Test can help you. - -So what makes a good test, and how does Google C++ Testing Framework fit in? We believe: - 1. Tests should be _independent_ and _repeatable_. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging. - 1. Tests should be well _organized_ and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base. - 1. Tests should be _portable_ and _reusable_. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.) - 1. When tests fail, they should provide as much _information_ about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle. - 1. The testing framework should liberate test writers from housekeeping chores and let them focus on the test _content_. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them. - 1. Tests should be _fast_. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other. - -Since Google C++ Testing Framework is based on the popular xUnit -architecture, you'll feel right at home if you've used JUnit or PyUnit before. -If not, it will take you about 10 minutes to learn the basics and get started. -So let's go! - -_Note:_ We sometimes refer to Google C++ Testing Framework informally -as _Google Test_. +# Googletest Primer + +## Introduction: Why googletest? + +*googletest* helps you write better C++ tests. + +googletest is a testing framework developed by the [Testing +Technology](http://engdoc/eng/testing/TT/) team with Google's specific +requirements and constraints in mind. No matter whether you work on Linux, +Windows, or a Mac, if you write C++ code, googletest can help you. And it +supports *any* kind of tests, not just unit tests. + +So what makes a good test, and how does googletest fit in? We believe: + +1. Tests should be *independent* and *repeatable*. It's a pain to debug a test + that succeeds or fails as a result of other tests. googletest isolates the + tests by running each of them on a different object. When a test fails, + googletest allows you to run it in isolation for quick debugging. +1. Tests should be well *organized* and reflect the structure of the tested + code. googletest groups related tests into test cases that can share data + and subroutines. This common pattern is easy to recognize and makes tests + easy to maintain. Such consistency is especially helpful when people switch + projects and start to work on a new code base. +1. Tests should be *portable* and *reusable*. Google has a lot of code that is + platform-neutral, its tests should also be platform-neutral. googletest + works on different OSes, with different compilers (gcc, icc, and MSVC), with + or without exceptions, so googletest tests can easily work with a variety of + configurations. +1. When tests fail, they should provide as much *information* about the problem + as possible. googletest doesn't stop at the first test failure. Instead, it + only stops the current test and continues with the next. You can also set up + tests that report non-fatal failures after which the current test continues. + Thus, you can detect and fix multiple bugs in a single run-edit-compile + cycle. +1. The testing framework should liberate test writers from housekeeping chores + and let them focus on the test *content*. googletest automatically keeps + track of all tests defined, and doesn't require the user to enumerate them + in order to run them. +1. Tests should be *fast*. With googletest, you can reuse shared resources + across tests and pay for the set-up/tear-down only once, without making + tests depend on each other. + +Since googletest is based on the popular xUnit architecture, you'll feel right +at home if you've used JUnit or PyUnit before. If not, it will take you about 10 +minutes to learn the basics and get started. So let's go! # Beware of the nomenclature # @@ -29,104 +50,77 @@ _Note:_ There might be some confusion of idea due to different definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these. -Historically, the Google C++ Testing Framework started to use the term -_Test Case_ for grouping related tests, whereas current publications -including the International Software Testing Qualifications Board -([ISTQB](http://www.istqb.org/)) and various textbooks on Software -Quality use the term _[Test +Historically, googletest started to use the term _Test Case_ for grouping +related tests, whereas current publications including the International Software +Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) and various +textbooks on Software Quality use the term _[Test Suite](http://glossary.istqb.org/search/test%20suite)_ for this. -The related term _Test_, as it is used in the Google C++ Testing -Framework, is corresponding to the term _[Test -Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB and -others. +The related term _Test_, as it is used in the googletest, is corresponding to +the term _[Test Case](http://glossary.istqb.org/search/test%20case)_ of ISTQB +and others. The term _Test_ is commonly of broad enough sense, including ISTQB's definition of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as used in Google Test is of contradictory sense and thus confusing. -Unfortunately replacing the term _Test Case_ by _Test Suite_ throughout -the Google C++ Testing Framework is not easy without breaking dependent -projects, as `TestCase` is part of the public API at various places. +Unfortunately replacing the term _Test Case_ by _Test Suite_ throughout the +googletest is not easy without breaking dependent projects, as `TestCase` is +part of the public API at various places. So for the time being, please be aware of the different definitions of the terms: -Meaning | Google Test Term | [ISTQB](http://www.istqb.org/) Term -------- | ---------------- | ----------------------------------- -Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) -A set of several tests related to one component | [Test Case](#basic-concepts) | [Test Suite](http://glossary.istqb.org/search/test%20suite) - -# Setting up a New Test Project # - -To write a test program using Google Test, you need to compile Google -Test into a library and link your test with it. We provide build -files for some popular build systems: `msvc/` for Visual Studio, -`xcode/` for Mac Xcode, `make/` for GNU make, `codegear/` for Borland -C++ Builder, and the autotools script (deprecated) and -`CMakeLists.txt` for CMake (recommended) in the Google Test root -directory. If your build system is not on this list, you can take a -look at `make/Makefile` to learn how Google Test should be compiled -(basically you want to compile `src/gtest-all.cc` with `GTEST_ROOT` -and `GTEST_ROOT/include` in the header search path, where `GTEST_ROOT` -is the Google Test root directory). - -Once you are able to compile the Google Test library, you should -create a project or build target for your test program. Make sure you -have `GTEST_ROOT/include` in the header search path so that the -compiler can find `"gtest/gtest.h"` when compiling your test. Set up -your test project to link with the Google Test library (for example, -in Visual Studio, this is done by adding a dependency on -`gtest.vcproj`). - -If you still have questions, take a look at how Google Test's own -tests are built and use them as examples. - -# Basic Concepts # - -When using Google Test, you start by writing _assertions_, which are statements -that check whether a condition is true. An assertion's result can be _success_, -_nonfatal failure_, or _fatal failure_. If a fatal failure occurs, it aborts -the current function; otherwise the program continues normally. - -_Tests_ use assertions to verify the tested code's behavior. If a test crashes -or has a failed assertion, then it _fails_; otherwise it _succeeds_. - -A _test case_ contains one or many tests. You should group your tests into test +Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term +:----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :---------------------------------- +Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) +A set of several tests related to one component | [TestCase](https://g3doc.corp.google.com/third_party/googletest/googletest/g3doc/primer.md#basic-concepts) | [TestSuite](http://glossary.istqb.org/search/test%20suite) + +## Basic Concepts + +When using googletest, you start by writing *assertions*, which are statements +that check whether a condition is true. An assertion's result can be *success*, +*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the +current function; otherwise the program continues normally. + +*Tests* use assertions to verify the tested code's behavior. If a test crashes +or has a failed assertion, then it *fails*; otherwise it *succeeds*. + +A *test case* contains one or many tests. You should group your tests into test cases that reflect the structure of the tested code. When multiple tests in a test case need to share common objects and subroutines, you can put them into a -_test fixture_ class. +*test fixture* class. -A _test program_ can contain multiple test cases. +A *test program* can contain multiple test cases. We'll now explain how to write a test program, starting at the individual assertion level and building up to tests and test cases. -# Assertions # +## Assertions -Google Test assertions are macros that resemble function calls. You test a -class or function by making assertions about its behavior. When an assertion -fails, Google Test prints the assertion's source file and line number location, -along with a failure message. You may also supply a custom failure message -which will be appended to Google Test's message. +googletest assertions are macros that resemble function calls. You test a class +or function by making assertions about its behavior. When an assertion fails, +googletest prints the assertion's source file and line number location, along +with a failure message. You may also supply a custom failure message which will +be appended to googletest's message. -The assertions come in pairs that test the same thing but have different -effects on the current function. `ASSERT_*` versions generate fatal failures -when they fail, and **abort the current function**. `EXPECT_*` versions generate -nonfatal failures, which don't abort the current function. Usually `EXPECT_*` -are preferred, as they allow more than one failures to be reported in a test. -However, you should use `ASSERT_*` if it doesn't make sense to continue when -the assertion in question fails. +The assertions come in pairs that test the same thing but have different effects +on the current function. `ASSERT_*` versions generate fatal failures when they +fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal +failures, which don't abort the current function. Usually `EXPECT_*` are +preferred, as they allow more than one failure to be reported in a test. +However, you should use `ASSERT_*` if it doesn't make sense to continue when the +assertion in question fails. Since a failed `ASSERT_*` returns from the current function immediately, possibly skipping clean-up code that comes after it, it may cause a space leak. -Depending on the nature of the leak, it may or may not be worth fixing - so -keep this in mind if you get a heap checker error in addition to assertion -errors. +Depending on the nature of the leak, it may or may not be worth fixing - so keep +this in mind if you get a heap checker error in addition to assertion errors. To provide a custom failure message, simply stream it into the macro using the `<<` operator, or a sequence of such operators. An example: -``` + +```c++ ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; for (int i = 0; i < x.size(); ++i) { @@ -139,50 +133,53 @@ macro--in particular, C strings and `string` objects. If a wide string (`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an assertion, it will be translated to UTF-8 when printed. -## Basic Assertions ## +### Basic Assertions These assertions do basic true/false condition testing. -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_TRUE(`_condition_`)`; | `EXPECT_TRUE(`_condition_`)`; | _condition_ is true | -| `ASSERT_FALSE(`_condition_`)`; | `EXPECT_FALSE(`_condition_`)`; | _condition_ is false | +Fatal assertion | Nonfatal assertion | Verifies +-------------------------- | -------------------------- | -------------------- +`ASSERT_TRUE(condition);` | `EXPECT_TRUE(condition);` | `condition` is true +`ASSERT_FALSE(condition);` | `EXPECT_FALSE(condition);` | `condition` is false -Remember, when they fail, `ASSERT_*` yields a fatal failure and -returns from the current function, while `EXPECT_*` yields a nonfatal -failure, allowing the function to continue running. In either case, an -assertion failure means its containing test fails. +Remember, when they fail, `ASSERT_*` yields a fatal failure and returns from the +current function, while `EXPECT_*` yields a nonfatal failure, allowing the +function to continue running. In either case, an assertion failure means its +containing test fails. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -## Binary Comparison ## +### Binary Comparison This section describes assertions that compare two values. -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -|`ASSERT_EQ(`_val1_`, `_val2_`);`|`EXPECT_EQ(`_val1_`, `_val2_`);`| _val1_ `==` _val2_ | -|`ASSERT_NE(`_val1_`, `_val2_`);`|`EXPECT_NE(`_val1_`, `_val2_`);`| _val1_ `!=` _val2_ | -|`ASSERT_LT(`_val1_`, `_val2_`);`|`EXPECT_LT(`_val1_`, `_val2_`);`| _val1_ `<` _val2_ | -|`ASSERT_LE(`_val1_`, `_val2_`);`|`EXPECT_LE(`_val1_`, `_val2_`);`| _val1_ `<=` _val2_ | -|`ASSERT_GT(`_val1_`, `_val2_`);`|`EXPECT_GT(`_val1_`, `_val2_`);`| _val1_ `>` _val2_ | -|`ASSERT_GE(`_val1_`, `_val2_`);`|`EXPECT_GE(`_val1_`, `_val2_`);`| _val1_ `>=` _val2_ | - -In the event of a failure, Google Test prints both _val1_ and _val2_. - -Value arguments must be comparable by the assertion's comparison -operator or you'll get a compiler error. We used to require the -arguments to support the `<<` operator for streaming to an `ostream`, -but it's no longer necessary since v1.6.0 (if `<<` is supported, it -will be called to print the arguments when the assertion fails; -otherwise Google Test will attempt to print them in the best way it -can. For more details and how to customize the printing of the -arguments, see this Google Mock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-how-to-print-your-values).). +Fatal assertion | Nonfatal assertion | Verifies +------------------------ | ------------------------ | -------------- +`ASSERT_EQ(val1, val2);` | `EXPECT_EQ(val1, val2);` | `val1 == val2` +`ASSERT_NE(val1, val2);` | `EXPECT_NE(val1, val2);` | `val1 != val2` +`ASSERT_LT(val1, val2);` | `EXPECT_LT(val1, val2);` | `val1 < val2` +`ASSERT_LE(val1, val2);` | `EXPECT_LE(val1, val2);` | `val1 <= val2` +`ASSERT_GT(val1, val2);` | `EXPECT_GT(val1, val2);` | `val1 > val2` +`ASSERT_GE(val1, val2);` | `EXPECT_GE(val1, val2);` | `val1 >= val2` + +Value arguments must be comparable by the assertion's comparison operator or +you'll get a compiler error. We used to require the arguments to support the +`<<` operator for streaming to an `ostream`, but it's no longer necessary. If +`<<` is supported, it will be called to print the arguments when the assertion +fails; otherwise googletest will attempt to print them in the best way it can. +For more details and how to customize the printing of the arguments, see +gMock [recipe](../../googlemock/docs/CookBook.md#teaching-google-mock-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. `==`, `<`, etc). If the corresponding -operator is defined, prefer using the `ASSERT_*()` macros because they will -print out not only the result of the comparison, but the two operands as well. +corresponding comparison operator (e.g. `==`, `<`, etc). Since this is +discouraged by the Google [C++ Style +Guide](https://google.github.io/styleguide/cppguide.html#Operator_Overloading), +you may need to use `ASSERT_TRUE()` or `EXPECT_TRUE()` to assert the equality of +two objects of a user-defined type. + +However, when possible, `ASSERT_EQ(actual, expected)` is preferred to +`ASSERT_TRUE(actual == expected)`, since it tells you `actual` and `expected`'s +values on failure. Arguments are always evaluated exactly once. Therefore, it's OK for the arguments to have side effects. However, as with any ordinary C/C++ function, @@ -193,117 +190,153 @@ evaluation order. `ASSERT_EQ()` does pointer equality on pointers. If used on two C strings, it tests if they are in the same memory location, not if they have the same value. Therefore, if you want to compare C strings (e.g. `const char*`) by value, use -`ASSERT_STREQ()` , which will be described later on. In particular, to assert -that a C string is `NULL`, use `ASSERT_STREQ(NULL, c_string)` . However, to -compare two `string` objects, you should use `ASSERT_EQ`. +`ASSERT_STREQ()`, which will be described later on. In particular, to assert +that a C string is `NULL`, use `ASSERT_STREQ(c_string, NULL)`. Consider use +`ASSERT_EQ(c_string, nullptr)` if c++11 is supported. To compare two `string` +objects, you should use `ASSERT_EQ`. + +When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)` +instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is +typed while `NULL` is not. See [FAQ](faq#Why_does_googletest_support_EXPECT_EQ) +for more details. + +If you're working with floating point numbers, you may want to use the floating +point variations of some of these macros in order to avoid problems caused by +rounding. See [Advanced googletest Topics](advanced) for details. Macros in this section work with both narrow and wide string objects (`string` and `wstring`). -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -_Historical note_: Before February 2016 `*_EQ` had a convention of calling it as -`ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. -Now `*_EQ` treats both parameters in the same way. +**Historical note**: Before February 2016 `*_EQ` had a convention of calling it +as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now +`*_EQ` treats both parameters in the same way. -## String Comparison ## +### String Comparison The assertions in this group compare two **C strings**. If you want to compare two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_STREQ(`_str1_`, `_str2_`);` | `EXPECT_STREQ(`_str1_`, `_str2_`);` | the two C strings have the same content | -| `ASSERT_STRNE(`_str1_`, `_str2_`);` | `EXPECT_STRNE(`_str1_`, `_str2_`);` | the two C strings have different content | -| `ASSERT_STRCASEEQ(`_str1_`, `_str2_`);`| `EXPECT_STRCASEEQ(`_str1_`, `_str2_`);` | the two C strings have the same content, ignoring case | -| `ASSERT_STRCASENE(`_str1_`, `_str2_`);`| `EXPECT_STRCASENE(`_str1_`, `_str2_`);` | the two C strings have different content, ignoring case | - -Note that "CASE" in an assertion name means that case is ignored. +| Fatal assertion | Nonfatal assertion | Verifies | +| ----------------------- | ----------------------- | ---------------------- | +| `ASSERT_STREQ(str1, | `EXPECT_STREQ(str1, | the two C strings have | +: str2);` : str2);` : the same content : +| `ASSERT_STRNE(str1, | `EXPECT_STRNE(str1, | the two C strings have | +: str2);` : str2);` : different contents : +| `ASSERT_STRCASEEQ(str1, | `EXPECT_STRCASEEQ(str1, | the two C strings have | +: str2);` : str2);` : the same content, : +: : : ignoring case : +| `ASSERT_STRCASENE(str1, | `EXPECT_STRCASENE(str1, | the two C strings have | +: str2);` : str2);` : different contents, : +: : : ignoring case : -`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a -comparison of two wide strings fails, their values will be printed as UTF-8 -narrow strings. +Note that "CASE" in an assertion name means that case is ignored. A `NULL` +pointer and an empty string are considered *different*. -A `NULL` pointer and an empty string are considered _different_. +`*STREQ*` and `*STRNE*` also accept wide C strings (`wchar_t*`). If a comparison +of two wide strings fails, their values will be printed as UTF-8 narrow strings. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -See also: For more string comparison tricks (substring, prefix, suffix, and -regular expression matching, for example), see the [Advanced Google Test Guide](advanced.md). +**See also**: For more string comparison tricks (substring, prefix, suffix, and +regular expression matching, for example), see +[this](https://github.com/google/googletest/blob/master/googletest/docs/advanced.md) +in the Advanced googletest Guide. -# Simple Tests # +## Simple Tests To create a test: - 1. Use the `TEST()` macro to define and name a test function, These are ordinary C++ functions that don't return a value. - 1. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values. - 1. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds. -``` -TEST(testCaseName, testName) { - ... test body ... +1. Use the `TEST()` macro to define and name a test function, These are + ordinary C++ functions that don't return a value. +1. In this function, along with any valid C++ statements you want to include, + use the various googletest assertions to check values. +1. The test's result is determined by the assertions; if any assertion in the + test fails (either fatally or non-fatally), or if the test crashes, the + entire test fails. Otherwise, it succeeds. + +```c++ +TEST(TestCaseName, TestName) { + ... test body ... } ``` - -`TEST()` arguments go from general to specific. The _first_ argument is the -name of the test case, and the _second_ argument is the test's name within the -test case. Both names must be valid C++ identifiers, and they should not contain underscore (`_`). A test's _full name_ consists of its containing test case and its -individual name. Tests from different test cases can have the same individual -name. +`TEST()` arguments go from general to specific. The *first* argument is the name +of the test case, and the *second* argument is the test's name within the test +case. Both names must be valid C++ identifiers, and they should not contain +underscore (`_`). A test's *full name* consists of its containing test case and +its individual name. Tests from different test cases can have the same +individual name. For example, let's take a simple integer function: -``` -int Factorial(int n); // Returns the factorial of n + +```c++ +int Factorial(int n); // Returns the factorial of n ``` A test case for this function might look like: -``` + +```c++ // Tests factorial of 0. TEST(FactorialTest, HandlesZeroInput) { - EXPECT_EQ(1, Factorial(0)); + EXPECT_EQ(Factorial(0), 1); } // Tests factorial of positive numbers. TEST(FactorialTest, HandlesPositiveInput) { - EXPECT_EQ(1, Factorial(1)); - EXPECT_EQ(2, Factorial(2)); - EXPECT_EQ(6, Factorial(3)); - EXPECT_EQ(40320, Factorial(8)); + EXPECT_EQ(Factorial(1), 1); + EXPECT_EQ(Factorial(2), 2); + EXPECT_EQ(Factorial(3), 6); + EXPECT_EQ(Factorial(8), 40320); } ``` -Google Test groups the test results by test cases, so logically-related tests +googletest groups the test results by test cases, so logically-related tests should be in the same test case; in other words, the first argument to their `TEST()` should be the same. In the above example, we have two tests, -`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test -case `FactorialTest`. +`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test case +`FactorialTest`. -_Availability_: Linux, Windows, Mac. +When naming your test cases and tests, you should follow the same convention as +for [naming functions and +classes](https://google.github.io/styleguide/cppguide.html#Function_Names). -# Test Fixtures: Using the Same Data Configuration for Multiple Tests # +**Availability**: Linux, Windows, Mac. -If you find yourself writing two or more tests that operate on similar data, -you can use a _test fixture_. It allows you to reuse the same configuration of +## Test Fixtures: Using the Same Data Configuration for Multiple Tests + +If you find yourself writing two or more tests that operate on similar data, you +can use a *test fixture*. It allows you to reuse the same configuration of objects for several different tests. -To create a fixture, just: - 1. Derive a class from `::testing::Test` . Start its body with `protected:` or `public:` as we'll want to access fixture members from sub-classes. - 1. Inside the class, declare any objects you plan to use. - 1. If necessary, write a default constructor or `SetUp()` function to prepare the objects for each test. A common mistake is to spell `SetUp()` as `Setup()` with a small `u` - don't let that happen to you. - 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read this [FAQ entry](faq.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function). - 1. If needed, define subroutines for your tests to share. +To create a fixture: + +1. Derive a class from `::testing::Test` . Start its body with `protected:` as + we'll want to access fixture members from sub-classes. +1. Inside the class, declare any objects you plan to use. +1. If necessary, write a default constructor or `SetUp()` function to prepare + the objects for each test. A common mistake is to spell `SetUp()` as + **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you + spelled it correctly +1. If necessary, write a destructor or `TearDown()` function to release any + resources you allocated in `SetUp()` . To learn when you should use the + constructor/destructor and when you should use `SetUp()/TearDown()`, read + this [FAQ](faq#CtorVsSetUp) entry. +1. If needed, define subroutines for your tests to share. When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to access objects and subroutines in the test fixture: -``` -TEST_F(test_case_name, test_name) { - ... test body ... + +```c++ +TEST_F(TestCaseName, TestName) { + ... test body ... } ``` -Like `TEST()`, the first argument is the test case name, but for `TEST_F()` -this must be the name of the test fixture class. You've probably guessed: `_F` -is for fixture. +Like `TEST()`, the first argument is the test case name, but for `TEST_F()` this +must be the name of the test fixture class. You've probably guessed: `_F` is for +fixture. Unfortunately, the C++ macro system does not allow us to create a single macro that can handle both types of tests. Using the wrong macro causes a compiler @@ -313,22 +346,24 @@ Also, you must first define a test fixture class before using it in a `TEST_F()`, or you'll get the compiler error "`virtual outside class declaration`". -For each test defined with `TEST_F()`, Google Test will: - 1. Create a _fresh_ test fixture at runtime - 1. Immediately initialize it via `SetUp()` - 1. Run the test - 1. Clean up by calling `TearDown()` - 1. Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests. +For each test defined with `TEST_F()` , googletest will create a *fresh* test +fixture at runtime, immediately initialize it via `SetUp()` , run the test, +clean up by calling `TearDown()` , and then delete the test fixture. Note that +different tests in the same test case have different test fixture objects, and +googletest always deletes a test fixture before it creates the next one. +googletest does **not** reuse the same test fixture for multiple tests. Any +changes one test makes to the fixture do not affect other tests. -As an example, let's write tests for a FIFO queue class named `Queue`, which -has the following interface: -``` -template // E is the element type. +As an example, let's write tests for a FIFO queue class named `Queue`, which has +the following interface: + +```c++ +template // E is the element type. class Queue { public: Queue(); void Enqueue(const E& element); - E* Dequeue(); // Returns NULL if the queue is empty. + E* Dequeue(); // Returns NULL if the queue is empty. size_t size() const; ... }; @@ -336,16 +371,17 @@ class Queue { First, define a fixture class. By convention, you should give it the name `FooTest` where `Foo` is the class being tested. -``` + +```c++ class QueueTest : public ::testing::Test { protected: - virtual void SetUp() { - q1_.Enqueue(1); - q2_.Enqueue(2); - q2_.Enqueue(3); + void SetUp() override { + q1_.Enqueue(1); + q2_.Enqueue(2); + q2_.Enqueue(3); } - // virtual void TearDown() {} + // void TearDown() override {} Queue q0_; Queue q1_; @@ -357,85 +393,101 @@ In this case, `TearDown()` is not needed since we don't have to clean up after each test, other than what's already done by the destructor. Now we'll write tests using `TEST_F()` and this fixture. -``` + +```c++ TEST_F(QueueTest, IsEmptyInitially) { - EXPECT_EQ(0, q0_.size()); + EXPECT_EQ(q0_.size(), 0); } TEST_F(QueueTest, DequeueWorks) { int* n = q0_.Dequeue(); - EXPECT_EQ(NULL, n); + EXPECT_EQ(n, nullptr); n = q1_.Dequeue(); - ASSERT_TRUE(n != NULL); - EXPECT_EQ(1, *n); - EXPECT_EQ(0, q1_.size()); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 1); + EXPECT_EQ(q1_.size(), 0); delete n; n = q2_.Dequeue(); - ASSERT_TRUE(n != NULL); - EXPECT_EQ(2, *n); - EXPECT_EQ(1, q2_.size()); + ASSERT_NE(n, nullptr); + EXPECT_EQ(*n, 2); + EXPECT_EQ(q2_.size(), 1); delete n; } ``` The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is -to use `EXPECT_*` when you want the test to continue to reveal more errors -after the assertion failure, and use `ASSERT_*` when continuing after failure -doesn't make sense. For example, the second assertion in the `Dequeue` test is -`ASSERT_TRUE(n != NULL)`, as we need to dereference the pointer `n` later, -which would lead to a segfault when `n` is `NULL`. +to use `EXPECT_*` when you want the test to continue to reveal more errors after +the assertion failure, and use `ASSERT_*` when continuing after failure doesn't +make sense. For example, the second assertion in the `Dequeue` test is +=ASSERT_NE(nullptr, n)=, as we need to dereference the pointer `n` later, which +would lead to a segfault when `n` is `NULL`. When these tests run, the following happens: - 1. Google Test constructs a `QueueTest` object (let's call it `t1` ). - 1. `t1.SetUp()` initializes `t1` . - 1. The first test ( `IsEmptyInitially` ) runs on `t1` . - 1. `t1.TearDown()` cleans up after the test finishes. - 1. `t1` is destructed. - 1. The above steps are repeated on another `QueueTest` object, this time running the `DequeueWorks` test. -_Availability_: Linux, Windows, Mac. +1. googletest constructs a `QueueTest` object (let's call it `t1` ). +1. `t1.SetUp()` initializes `t1` . +1. The first test ( `IsEmptyInitially` ) runs on `t1` . +1. `t1.TearDown()` cleans up after the test finishes. +1. `t1` is destructed. +1. The above steps are repeated on another `QueueTest` object, this time + running the `DequeueWorks` test. -_Note_: Google Test automatically saves all _Google Test_ flags when a test -object is constructed, and restores them when it is destructed. +**Availability**: Linux, Windows, Mac. -# Invoking the Tests # +## Invoking the Tests -`TEST()` and `TEST_F()` implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them. +`TEST()` and `TEST_F()` implicitly register their tests with googletest. So, +unlike with many other C++ testing frameworks, you don't have to re-list all +your defined tests in order to run them. -After defining your tests, you can run them with `RUN_ALL_TESTS()` , which returns `0` if all the tests are successful, or `1` otherwise. Note that `RUN_ALL_TESTS()` runs _all tests_ in your link unit -- they can be from different test cases, or even different source files. +After defining your tests, you can run them with `RUN_ALL_TESTS()` , which +returns `0` if all the tests are successful, or `1` otherwise. Note that +`RUN_ALL_TESTS()` runs *all tests* in your link unit -- they can be from +different test cases, or even different source files. When invoked, the `RUN_ALL_TESTS()` macro: - 1. Saves the state of all Google Test flags. - 1. Creates a test fixture object for the first test. - 1. Initializes it via `SetUp()`. - 1. Runs the test on the fixture object. - 1. Cleans up the fixture via `TearDown()`. - 1. Deletes the fixture. - 1. Restores the state of all Google Test flags. - 1. Repeats the above steps for the next test, until all tests have run. -In addition, if the test fixture's constructor generates a fatal failure in -step 2, there is no point for step 3 - 5 and they are thus skipped. Similarly, -if step 3 generates a fatal failure, step 4 will be skipped. +1. Saves the state of all googletest flags + +* Creates a test fixture object for the first test. + +* Initializes it via `SetUp()`. + +* Runs the test on the fixture object. -_Important_: You must not ignore the return value of `RUN_ALL_TESTS()`, or `gcc` -will give you a compiler error. The rationale for this design is that the -automated testing service determines whether a test has passed based on its -exit code, not on its stdout/stderr output; thus your `main()` function must -return the value of `RUN_ALL_TESTS()`. +* Cleans up the fixture via `TearDown()`. -Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than once -conflicts with some advanced Google Test features (e.g. thread-safe death -tests) and thus is not supported. +* Deletes the fixture. -_Availability_: Linux, Windows, Mac. +1. Restores the state of all googletest flags -# Writing the main() Function # +* Repeats the above steps for the next test, until all tests have run. +If a fatal failure happens the subsequent steps will be skipped. + +> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or +> you will get a compiler error. The rationale for this design is that the +> automated testing service determines whether a test has passed based on its +> exit code, not on its stdout/stderr output; thus your `main()` function must +> return the value of `RUN_ALL_TESTS()`. +> +> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than +> once conflicts with some advanced googletest features (e.g. thread-safe [death +> tests](advanced#death-tests)) and thus is not supported. + +**Availability**: Linux, Windows, Mac. + +## Writing the main() Function + +In `google3`, the simplest approach is to use the default main() function +provided by linking in `"//testing/base/public:gtest_main"`. If that doesn't +cover what you need, you should write your own main() function, which should +return the value of `RUN_ALL_TESTS()`. Link to `"//testing/base/public:gunit"`. You can start from this boilerplate: -``` + +```c++ #include "this/package/foo.h" #include "gtest/gtest.h" @@ -448,24 +500,24 @@ class FooTest : public ::testing::Test { // is empty. FooTest() { - // You can do set-up work for each test here. + // You can do set-up work for each test here. } - virtual ~FooTest() { - // You can do clean-up work that doesn't throw exceptions here. + ~FooTest() override { + // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: - virtual void SetUp() { - // Code here will be called immediately after the constructor (right - // before each test). + void SetUp() override { + // Code here will be called immediately after the constructor (right + // before each test). } - virtual void TearDown() { - // Code here will be called immediately after each test (right - // before the destructor). + void TearDown() override { + // Code here will be called immediately after each test (right + // before the destructor). } // Objects declared here can be used by all tests in the test case for Foo. @@ -473,10 +525,10 @@ class FooTest : public ::testing::Test { // Tests that the Foo::Bar() method does Abc. TEST_F(FooTest, MethodBarDoesAbc) { - const string input_filepath = "this/package/testdata/myinputfile.dat"; - const string output_filepath = "this/package/testdata/myoutputfile.dat"; + const std::string input_filepath = "this/package/testdata/myinputfile.dat"; + const std::string output_filepath = "this/package/testdata/myoutputfile.dat"; Foo f; - EXPECT_EQ(0, f.Bar(input_filepath, output_filepath)); + EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0); } // Tests that Foo does Xyz. @@ -492,45 +544,45 @@ int main(int argc, char **argv) { } ``` -The `::testing::InitGoogleTest()` function parses the command line for Google -Test flags, and removes all recognized flags. This allows the user to control a -test program's behavior via various flags, which we'll cover in [AdvancedGuide](advanced.md). -You must call this function before calling `RUN_ALL_TESTS()`, or the flags -won't be properly initialized. +The `::testing::InitGoogleTest()` function parses the command line for +googletest flags, and removes all recognized flags. This allows the user to +control a test program's behavior via various flags, which we'll cover in +[AdvancedGuide](advanced.md). You **must** call this function before calling +`RUN_ALL_TESTS()`, or the flags won't be properly initialized. On Windows, `InitGoogleTest()` also works with wide strings, so it can be used in programs compiled in `UNICODE` mode as well. -But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest\_main library and you are good to go. +But maybe you think that writing all those main() functions is too much work? We +agree with you completely and that's why Google Test provides a basic +implementation of main(). If it fits your needs, then just link your test with +gtest\_main library and you are good to go. -## Important note for Visual C++ users ## -If you put your tests into a library and your `main()` function is in a different library or in your .exe file, those tests will not run. The reason is a [bug](https://connect.microsoft.com/feedback/viewfeedback.aspx?FeedbackID=244410&siteid=210) in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function: -``` -__declspec(dllexport) int PullInMyLibrary() { return 0; } -``` -If you put your tests in a static library (not DLL) then `__declspec(dllexport)` is not required. Now, in your main program, write a code that invokes that function: -``` -int PullInMyLibrary(); -static int dummy = PullInMyLibrary(); -``` -This will keep your tests referenced and will make them register themselves at startup. +NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. + +## Creating and Building Test Programs -In addition, if you define your tests in a static library, add `/OPT:NOREF` to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to `Keep Unreferenced Data (/OPT:NOREF)`. This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable. +Now that we've learned how to write a test program, we need to tell the build +system to build it. The exact steps differ from one OS to another. -There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you _must_ change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries! +If you work on Linux, follow the instructions [here](howto_cpp#LinuxTarget). -# Where to Go from Here # +If you work on the Mac, follow the instructions [here](howto_cpp_mac). -Congratulations! You've learned the Google Test basics. You can start writing -and running Google Test tests, read some [samples](samples.md), or continue with -[AdvancedGuide](advanced.md), which describes many more useful Google Test features. +If you work on Windows, consult existing test programs in your project, as the +syntax for a test program build target may differ slightly from project to +project. When compiling googletest and your tests, please do **not** use the +`/Wp64` MSVC flag. It is broken and +[deprecated](http://msdn.microsoft.com/en-us/library/yt4xw8fh.aspx) by +Microsoft. We don't guarantee that googletest will compile warning-free with +that flag (as it's often technically infeasible given the flag's broken nature). -# Known Limitations # +## Known Limitations -Google Test is designed to be thread-safe. The implementation is -thread-safe on systems where the `pthreads` library is available. It -is currently _unsafe_ to use Google Test assertions from two threads -concurrently on other systems (e.g. Windows). In most tests this is -not an issue as usually the assertions are done in the main thread. If -you want to help, you can volunteer to implement the necessary -synchronization primitives in `gtest-port.h` for your platform. +* Google Test is designed to be thread-safe. The implementation is thread-safe + on systems where the `pthreads` library is available. It is currently + _unsafe_ to use Google Test assertions from two threads concurrently on + other systems (e.g. Windows). In most tests this is not an issue as usually + the assertions are done in the main thread. If you want to help, you can + volunteer to implement the necessary synchronization primitives in + `gtest-port.h` for your platform. diff --git a/googletest/docs/samples.md b/googletest/docs/samples.md index f21d200..18dcca3 100644 --- a/googletest/docs/samples.md +++ b/googletest/docs/samples.md @@ -1,14 +1,22 @@ -If you're like us, you'd like to look at some Google Test sample code. The -[samples folder](../samples) has a number of well-commented samples showing how to use a -variety of Google Test features. +# Googletest Samples {#samples} - * [Sample #1](../samples/sample1_unittest.cc) shows the basic steps of using Google Test to test C++ functions. - * [Sample #2](../samples/sample2_unittest.cc) shows a more complex unit test for a class with multiple member functions. - * [Sample #3](../samples/sample3_unittest.cc) uses a test fixture. - * [Sample #4](../samples/sample4_unittest.cc) is another basic example of using Google Test. - * [Sample #5](../samples/sample5_unittest.cc) teaches how to reuse a test fixture in multiple test cases by deriving sub-fixtures from it. - * [Sample #6](../samples/sample6_unittest.cc) demonstrates type-parameterized tests. - * [Sample #7](../samples/sample7_unittest.cc) teaches the basics of value-parameterized tests. - * [Sample #8](../samples/sample8_unittest.cc) shows using `Combine()` in value-parameterized tests. - * [Sample #9](../samples/sample9_unittest.cc) shows use of the listener API to modify Google Test's console output and the use of its reflection API to inspect test results. - * [Sample #10](../samples/sample10_unittest.cc) shows use of the listener API to implement a primitive memory leak checker. +If you're like us, you'd like to look at [googletest +samples.](https://github.com/google/googletest/tree/master/googletest/samples) +The sample directory has a number of well-commented samples showing how to use a +variety of googletest features. + +* Sample #1 shows the basic steps of using googletest to test C++ functions. +* Sample #2 shows a more complex unit test for a class with multiple member + functions. +* Sample #3 uses a test fixture. +* Sample #4 teaches you how to use googletest and `googletest.h` together to + get the best of both libraries. +* Sample #5 puts shared testing logic in a base test fixture, and reuses it in + derived fixtures. +* Sample #6 demonstrates type-parameterized tests. +* Sample #7 teaches the basics of value-parameterized tests. +* Sample #8 shows using `Combine()` in value-parameterized tests. +* Sample #9 shows use of the listener API to modify Google Test's console + output and the use of its reflection API to inspect test results. +* Sample #10 shows use of the listener API to implement a primitive memory + leak checker. -- cgit v0.12 From 4f9194286ca745f94225f43c1473d05c5702093c Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 10 Jul 2018 17:30:28 -0400 Subject: Fix heading [skip ci] --- googletest/docs/primer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 6c33ebb..615727e 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -44,7 +44,7 @@ Since googletest is based on the popular xUnit architecture, you'll feel right at home if you've used JUnit or PyUnit before. If not, it will take you about 10 minutes to learn the basics and get started. So let's go! -# Beware of the nomenclature # +## Beware of the nomenclature _Note:_ There might be some confusion of idea due to different definitions of the terms _Test_, _Test Case_ and _Test Suite_, so beware -- cgit v0.12 From 93bfdde0eeac83fb51b856dc4dc9c38c408b0ee0 Mon Sep 17 00:00:00 2001 From: Adrian Moran Date: Wed, 11 Jul 2018 14:59:01 +0200 Subject: Fix issue #1654. Signed-off-by: Adrian Moran --- googlemock/test/gmock_ex_test.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 3afed86..8c83890 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -37,7 +37,9 @@ namespace { using testing::HasSubstr; +#if GTEST_HAS_EXCEPTIONS using testing::internal::GoogleTestFailureException; +#endif // A type that cannot be default constructed. class NonDefaultConstructible { -- cgit v0.12 From 74cccf494a11bc5424a9b228cfdf7f6f1e21d30e Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 11 Jul 2018 09:38:47 -0400 Subject: formatting, [ci skip] --- googletest/docs/primer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 615727e..cbc9405 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -461,7 +461,7 @@ When invoked, the `RUN_ALL_TESTS()` macro: * Deletes the fixture. -1. Restores the state of all googletest flags +* Restores the state of all googletest flags * Repeats the above steps for the next test, until all tests have run. -- cgit v0.12 From 36066cfecf79267bdf46ff82ca6c3b052f8f633c Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 11 Jul 2018 09:42:48 -0400 Subject: more formatting [skip ci] --- googletest/docs/primer.md | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index cbc9405..9949658 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -560,23 +560,6 @@ gtest\_main library and you are good to go. NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. -## Creating and Building Test Programs - -Now that we've learned how to write a test program, we need to tell the build -system to build it. The exact steps differ from one OS to another. - -If you work on Linux, follow the instructions [here](howto_cpp#LinuxTarget). - -If you work on the Mac, follow the instructions [here](howto_cpp_mac). - -If you work on Windows, consult existing test programs in your project, as the -syntax for a test program build target may differ slightly from project to -project. When compiling googletest and your tests, please do **not** use the -`/Wp64` MSVC flag. It is broken and -[deprecated](http://msdn.microsoft.com/en-us/library/yt4xw8fh.aspx) by -Microsoft. We don't guarantee that googletest will compile warning-free with -that flag (as it's often technically infeasible given the flag's broken nature). - ## Known Limitations * Google Test is designed to be thread-safe. The implementation is thread-safe -- cgit v0.12 From 0acdf796420e4562ef7399b8610d23eda3256a5a Mon Sep 17 00:00:00 2001 From: Adrian Moran Date: Thu, 12 Jul 2018 15:10:08 +0200 Subject: Avoid full test in no exceptions are enabled. Signed-off-by: Adrian Moran --- googlemock/test/gmock_ex_test.cc | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 8c83890..5a299da 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -31,15 +31,14 @@ // Tests Google Mock's functionality that depends on exceptions. +#if GTEST_HAS_EXCEPTIONS #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using testing::HasSubstr; -#if GTEST_HAS_EXCEPTIONS using testing::internal::GoogleTestFailureException; -#endif // A type that cannot be default constructed. class NonDefaultConstructible { @@ -54,7 +53,6 @@ class MockFoo { MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible()); }; -#if GTEST_HAS_EXCEPTIONS TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { MockFoo mock; @@ -78,6 +76,5 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } -#endif - } // unnamed namespace +#endif -- cgit v0.12 From 6c7878a151f05d64f675b800b054c5fc43f3dd6d Mon Sep 17 00:00:00 2001 From: Derek Mauro Date: Thu, 12 Jul 2018 13:46:50 -0400 Subject: Adds the UniversalPrinter for absl::variant. --- BUILD.bazel | 36 ++++++++++++++++--------------- googletest/include/gtest/gtest-printers.h | 23 ++++++++++++++++++++ 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index 6d82829..f6dccd3 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -38,7 +38,7 @@ licenses(["notice"]) config_setting( name = "windows", - values = { "cpu": "x64_windows" }, + values = {"cpu": "x64_windows"}, ) config_setting( @@ -51,7 +51,6 @@ config_setting( values = {"define": "absl=1"}, ) - # Google Test including Google Mock cc_library( name = "gtest", @@ -70,7 +69,7 @@ cc_library( "googlemock/src/gmock_main.cc", ], ), - hdrs =glob([ + hdrs = glob([ "googletest/include/gtest/*.h", "googlemock/include/gmock/*.h", ]), @@ -81,6 +80,14 @@ cc_library( "//conditions:default": ["-pthread"], }, ), + defines = select( + { + ":has_absl": [ + "GTEST_HAS_ABSL=1", + ], + "//conditions:default": [], + }, + ), includes = [ "googlemock", "googlemock/include", @@ -94,21 +101,16 @@ cc_library( "-pthread", ], }), - defines = select ({ - ":has_absl": [ - "GTEST_HAS_ABSL=1", - ], - "//conditions:default": [], - } + deps = select( + { + ":has_absl": [ + "@com_google_absl//absl/types:optional", + "@com_google_absl//absl/types:variant", + "@com_google_absl//absl/strings", + ], + "//conditions:default": [], + }, ), - deps = select ({ - ":has_absl": [ - "@com_google_absl//absl/types:optional", - "@com_google_absl//absl/strings" - ], - "//conditions:default": [], - } - ) ) cc_library( diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 373946b..66d54b9 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -114,6 +114,7 @@ #if GTEST_HAS_ABSL #include "absl/strings/string_view.h" #include "absl/types/optional.h" +#include "absl/types/variant.h" #endif // GTEST_HAS_ABSL namespace testing { @@ -787,6 +788,28 @@ class UniversalPrinter<::absl::optional> { } }; +// Printer for absl::variant + +template +class UniversalPrinter<::absl::variant> { + public: + static void Print(const ::absl::variant& value, ::std::ostream* os) { + *os << '('; + absl::visit(Visitor{os}, value); + *os << ')'; + } + + private: + struct Visitor { + template + void operator()(const U& u) const { + *os << "'" << GetTypeName() << "' with value "; + UniversalPrint(u, os); + } + ::std::ostream* os; + }; +}; + #endif // GTEST_HAS_ABSL // UniversalPrintArray(begin, len, os) prints an array of 'len' -- cgit v0.12 From cbd07191f4b7a3498fd0d1d7c58c4c39cccb8fb8 Mon Sep 17 00:00:00 2001 From: Adrian Moran Date: Fri, 13 Jul 2018 08:53:03 +0200 Subject: Put ifdef guard after the includes. Signed-off-by: Adrian Moran --- googlemock/test/gmock_ex_test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 5a299da..99268b3 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -31,10 +31,10 @@ // Tests Google Mock's functionality that depends on exceptions. -#if GTEST_HAS_EXCEPTIONS #include "gmock/gmock.h" #include "gtest/gtest.h" +#if GTEST_HAS_EXCEPTIONS namespace { using testing::HasSubstr; -- cgit v0.12 From 021c308069cce3751c8620c922c7a226836044b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20M=C5=82okosiewicz?= Date: Tue, 17 Jul 2018 00:49:31 +0200 Subject: Fix broken links to FAQ in primer.md --- googletest/docs/primer.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 9949658..15f2b08 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -197,7 +197,7 @@ objects, you should use `ASSERT_EQ`. When doing pointer comparisons use `*_EQ(ptr, nullptr)` and `*_NE(ptr, nullptr)` instead of `*_EQ(ptr, NULL)` and `*_NE(ptr, NULL)`. This is because `nullptr` is -typed while `NULL` is not. See [FAQ](faq#Why_does_googletest_support_EXPECT_EQ) +typed while `NULL` is not. See [FAQ](faq.md#why-does-google-test-support-expect_eqnull-ptr-and-assert_eqnull-ptr-but-not-expect_nenull-ptr-and-assert_nenull-ptr) for more details. If you're working with floating point numbers, you may want to use the floating @@ -322,7 +322,7 @@ To create a fixture: 1. If necessary, write a destructor or `TearDown()` function to release any resources you allocated in `SetUp()` . To learn when you should use the constructor/destructor and when you should use `SetUp()/TearDown()`, read - this [FAQ](faq#CtorVsSetUp) entry. + this [FAQ](faq.md#should-i-use-the-constructordestructor-of-the-test-fixture-or-the-set-uptear-down-function) entry. 1. If needed, define subroutines for your tests to share. When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to -- cgit v0.12 From 65a49a73f0e7c059ad67d768c860bb296383fd56 Mon Sep 17 00:00:00 2001 From: duxiuxing Date: Tue, 17 Jul 2018 15:46:47 +0800 Subject: Fix warning C4819: The file contains a character that cannot be represented in the current code page (936). Save the file in Unicode format to prevent data loss --- .../gmock/gmock-generated-function-mockers.h | 4 +-- googlemock/include/gmock/gmock-spec-builders.h | 36 +++++++++++----------- .../include/gmock/internal/gmock-internal-utils.h | 2 +- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index 126c48c..d5417106 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -352,7 +352,7 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. @@ -363,7 +363,7 @@ class FunctionMocker : public // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( // const WithoutMatchers&, const Function*) const { diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index cf1e7e2..090cff4 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -1854,22 +1854,22 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT // parameter. This technique may only be used for non-overloaded methods. // // // These are the same: -// ON_CALL(mock, NoArgsMethod()).WillByDefault(…); -// ON_CALL(mock, NoArgsMethod).WillByDefault(…); +// ON_CALL(mock, NoArgsMethod()).WillByDefault(...); +// ON_CALL(mock, NoArgsMethod).WillByDefault(...); // // // As are these: -// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(…); -// ON_CALL(mock, TwoArgsMethod).WillByDefault(…); +// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...); +// ON_CALL(mock, TwoArgsMethod).WillByDefault(...); // // // Can also specify args if you want, of course: -// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(…); +// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...); // // // Overloads work as long as you specify parameters: -// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(…); -// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(…); +// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...); +// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...); // // // Oops! Which overload did you want? -// ON_CALL(mock, OverloadedMethod).WillByDefault(…); +// ON_CALL(mock, OverloadedMethod).WillByDefault(...); // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous // // How this works: The mock class uses two overloads of the gmock_Method @@ -1877,28 +1877,28 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT // In the matcher list form, the macro expands to: // // // This statement: -// ON_CALL(mock, TwoArgsMethod(_, 45))… +// ON_CALL(mock, TwoArgsMethod(_, 45))... // -// // …expands to: -// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)… +// // ...expands to: +// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)... // |-------------v---------------||------------v-------------| // invokes first overload swallowed by operator() // -// // …which is essentially: -// mock.gmock_TwoArgsMethod(_, 45)… +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, 45)... // // Whereas the form without a matcher list: // // // This statement: -// ON_CALL(mock, TwoArgsMethod)… +// ON_CALL(mock, TwoArgsMethod)... // -// // …expands to: -// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)… +// // ...expands to: +// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)... // |-----------------------v--------------------------| // invokes second overload // -// // …which is essentially: -// mock.gmock_TwoArgsMethod(_, _)… +// // ...which is essentially: +// mock.gmock_TwoArgsMethod(_, _)... // // The WithoutMatchers() argument is used to disambiguate overloads and to // block the caller from accidentally invoking the second overload directly. The diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index 4751788..c5841ab 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -348,7 +348,7 @@ GTEST_API_ void Log(LogSeverity severity, const std::string& message, // correct overload. This must not be instantiable, to prevent client code from // accidentally resolving to the overload; for example: // -// ON_CALL(mock, Method({}, nullptr))… +// ON_CALL(mock, Method({}, nullptr))... // class WithoutMatchers { private: -- cgit v0.12 From a091b753325322d329dc89262bfe5ad0ab20f1bf Mon Sep 17 00:00:00 2001 From: Syohei YOSHIDA Date: Tue, 17 Jul 2018 18:39:29 +0900 Subject: Ignore .DS_Store file --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index b294d3b..16c56e6 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,6 @@ googletest/m4/lt~obsolete.m4 # Ignore generated directories. googlemock/fused-src/ googletest/fused-src/ + +# macOS files +.DS_Store -- cgit v0.12 From 5437926b2213b1c45c2f34bd858734de90e5fffd Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Tue, 17 Jul 2018 17:47:25 -0400 Subject: Docs sync --- googletest/docs/advanced.md | 2546 ++++++++++++++++++++++--------------------- googletest/docs/faq.md | 1081 +++++++----------- googletest/docs/primer.md | 4 + 3 files changed, 1716 insertions(+), 1915 deletions(-) diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 73b7954..6883784 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -1,67 +1,77 @@ +# Advanced googletest Topics -Now that you have read [Primer](primer.md) and learned how to write tests -using Google Test, it's time to learn some new tricks. This document -will show you more assertions as well as how to construct complex -failure messages, propagate fatal failures, reuse and speed up your -test fixtures, and use various flags with your tests. +## Introduction -# More Assertions # +Now that you have read the [googletest Primer](primer) and learned how to write +tests using googletest, it's time to learn some new tricks. This document will +show you more assertions as well as how to construct complex failure messages, +propagate fatal failures, reuse and speed up your test fixtures, and use various +flags with your tests. + +## More Assertions This section covers some less frequently used, but still significant, assertions. -## Explicit Success and Failure ## +### Explicit Success and Failure -These three assertions do not actually test a value or expression. Instead, -they generate a success or failure directly. Like the macros that actually -perform a test, you may stream a custom failure message into them. +These three assertions do not actually test a value or expression. Instead, they +generate a success or failure directly. Like the macros that actually perform a +test, you may stream a custom failure message into them. -| `SUCCEED();` | -|:-------------| +```c++ +SUCCEED(); +``` -Generates a success. This does NOT make the overall test succeed. A test is +Generates a success. This does **NOT** make the overall test succeed. A test is considered successful only if none of its assertions fail during its execution. -Note: `SUCCEED()` is purely documentary and currently doesn't generate any -user-visible output. However, we may add `SUCCEED()` messages to Google Test's +NOTE: `SUCCEED()` is purely documentary and currently doesn't generate any +user-visible output. However, we may add `SUCCEED()` messages to googletest's output in the future. -| `FAIL();` | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` | -|:-----------|:-----------------|:------------------------------------------------------| +```c++ +FAIL(); +ADD_FAILURE(); +ADD_FAILURE_AT("file_path", line_number); +``` -`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal -failure. These are useful when control flow, rather than a Boolean expression, -determines the test's success or failure. For example, you might want to write -something like: +`FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` +generate a nonfatal failure. These are useful when control flow, rather than a +Boolean expression, determines the test's success or failure. For example, you +might want to write something like: -``` +```c++ switch(expression) { - case 1: ... some checks ... - case 2: ... some other checks - ... - default: FAIL() << "We shouldn't get here."; + case 1: + ... some checks ... + case 2: + ... some other checks ... + default: + FAIL() << "We shouldn't get here."; } ``` -Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information. +NOTE: you can only use `FAIL()` in functions that return `void`. See the +[Assertion Placement section](#assertion-placement) for more information. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -## Exception Assertions ## +### Exception Assertions -These are for verifying that a piece of code throws (or does not -throw) an exception of the given type: +These are for verifying that a piece of code throws (or does not throw) an +exception of the given type: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type | -| `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type | -| `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception | +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------------ | ------------------------------------------ | -------- +`ASSERT_THROW(statement, exception_type);` | `EXPECT_THROW(statement, exception_type);` | `statement` throws an exception of the given type +`ASSERT_ANY_THROW(statement);` | `EXPECT_ANY_THROW(statement);` | `statement` throws an exception of any type +`ASSERT_NO_THROW(statement);` | `EXPECT_NO_THROW(statement);` | `statement` doesn't throw any exception Examples: -``` +```c++ ASSERT_THROW(Foo(5), bar_exception); EXPECT_NO_THROW({ @@ -70,79 +80,96 @@ EXPECT_NO_THROW({ }); ``` -_Availability_: Linux, Windows, Mac; since version 1.1.0. +**Availability**: Linux, Windows, Mac; requires exceptions to be enabled in the +build environment (note that `google3` **disables** exceptions). -## Predicate Assertions for Better Error Messages ## +### Predicate Assertions for Better Error Messages -Even though Google Test has a rich set of assertions, they can never be -complete, as it's impossible (nor a good idea) to anticipate all the scenarios -a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` -to check a complex expression, for lack of a better macro. This has the problem -of not showing you the values of the parts of the expression, making it hard to +Even though googletest has a rich set of assertions, they can never be complete, +as it's impossible (nor a good idea) to anticipate all scenarios a user might +run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a +complex expression, for lack of a better macro. This has the problem of not +showing you the values of the parts of the expression, making it hard to understand what went wrong. As a workaround, some users choose to construct the failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this is awkward especially when the expression has side-effects or is expensive to evaluate. -Google Test gives you three different options to solve this problem: +googletest gives you three different options to solve this problem: -### Using an Existing Boolean Function ### +#### Using an Existing Boolean Function -If you already have a function or a functor that returns `bool` (or a type -that can be implicitly converted to `bool`), you can use it in a _predicate -assertion_ to get the function arguments printed for free: +If you already have a function or functor that returns `bool` (or a type that +can be implicitly converted to `bool`), you can use it in a *predicate +assertion* to get the function arguments printed for free: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true | -| `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true | -| ... | ... | ... | +| Fatal assertion | Nonfatal assertion | Verifies | +| -------------------- | -------------------- | --------------------------- | +| `ASSERT_PRED1(pred1, | `EXPECT_PRED1(pred1, | `pred1(val1)` is true | +: val1);` : val1);` : : +| `ASSERT_PRED2(pred2, | `EXPECT_PRED2(pred2, | `pred2(val1, val2)` is true | +: val1, val2);` : val1, val2);` : : +| `...` | `...` | ... | -In the above, _predn_ is an _n_-ary predicate function or functor, where -_val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds -if the predicate returns `true` when applied to the given arguments, and fails +In the above, `predn` is an `n`-ary predicate function or functor, where `val1`, +`val2`, ..., and `valn` are its arguments. The assertion succeeds if the +predicate returns `true` when applied to the given arguments, and fails otherwise. When the assertion fails, it prints the value of each argument. In either case, the arguments are evaluated exactly once. Here's an example. Given -``` +```c++ // Returns true iff m and n have no common divisors except 1. bool MutuallyPrime(int m, int n) { ... } + const int a = 3; const int b = 4; const int c = 10; ``` -the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the -assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message +the assertion + +```c++ + EXPECT_PRED2(MutuallyPrime, a, b); +``` + +will succeed, while the assertion + +```c++ + EXPECT_PRED2(MutuallyPrime, b, c); +``` -
-!MutuallyPrime(b, c) is false, where
-b is 4
-c is 10
-
+will fail with the message -**Notes:** +```none +MutuallyPrime(b, c) is false, where +b is 4 +c is 10 +``` - 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](faq.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. - 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. +> NOTE: +> +> 1. If you see a compiler error "no matching function to call" when using +> `ASSERT_PRED*` or `EXPECT_PRED*`, please see +> [this](faq#OverloadedPredicate) for how to resolve it. +> 1. Currently we only provide predicate assertions of arity <= 5. If you need +> a higher-arity assertion, let [us](http://g/opensource-gtest) know. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Using a Function That Returns an AssertionResult ### +#### Using a Function That Returns an AssertionResult -While `EXPECT_PRED*()` and friends are handy for a quick job, the -syntax is not satisfactory: you have to use different macros for -different arities, and it feels more like Lisp than C++. The -`::testing::AssertionResult` class solves this problem. +While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not +satisfactory: you have to use different macros for different arities, and it +feels more like Lisp than C++. The `::testing::AssertionResult` class solves +this problem. -An `AssertionResult` object represents the result of an assertion -(whether it's a success or a failure, and an associated message). You -can create an `AssertionResult` using one of these factory -functions: +An `AssertionResult` object represents the result of an assertion (whether it's +a success or a failure, and an associated message). You can create an +`AssertionResult` using one of these factory functions: -``` +```c++ namespace testing { // Returns an AssertionResult object to indicate that an assertion has @@ -156,26 +183,25 @@ AssertionResult AssertionFailure(); } ``` -You can then use the `<<` operator to stream messages to the -`AssertionResult` object. +You can then use the `<<` operator to stream messages to the `AssertionResult` +object. -To provide more readable messages in Boolean assertions -(e.g. `EXPECT_TRUE()`), write a predicate function that returns -`AssertionResult` instead of `bool`. For example, if you define -`IsEven()` as: +To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), +write a predicate function that returns `AssertionResult` instead of `bool`. For +example, if you define `IsEven()` as: -``` +```c++ ::testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) - return ::testing::AssertionSuccess(); + return ::testing::AssertionSuccess(); else - return ::testing::AssertionFailure() << n << " is odd"; + return ::testing::AssertionFailure() << n << " is odd"; } ``` instead of: -``` +```c++ bool IsEven(int n) { return (n % 2) == 0; } @@ -183,77 +209,83 @@ bool IsEven(int n) { the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: -
-Value of: IsEven(Fib(4))
-Actual: false (*3 is odd*)
-Expected: true
-
+```none +Value of: IsEven(Fib(4)) + Actual: false (3 is odd) +Expected: true +``` instead of a more opaque -
-Value of: IsEven(Fib(4))
-Actual: false
-Expected: true
-
+```none +Value of: IsEven(Fib(4)) + Actual: false +Expected: true +``` -If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` -as well, and are fine with making the predicate slower in the success -case, you can supply a success message: +If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well +(one third of Boolean assertions in the Google code base are negative ones), and +are fine with making the predicate slower in the success case, you can supply a +success message: -``` +```c++ ::testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) - return ::testing::AssertionSuccess() << n << " is even"; + return ::testing::AssertionSuccess() << n << " is even"; else - return ::testing::AssertionFailure() << n << " is odd"; + return ::testing::AssertionFailure() << n << " is odd"; } ``` Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print -
-Value of: IsEven(Fib(6))
-Actual: true (8 is even)
-Expected: false
-
+```none + Value of: IsEven(Fib(6)) + Actual: true (8 is even) + Expected: false +``` -_Availability_: Linux, Windows, Mac; since version 1.4.1. +**Availability**: Linux, Windows, Mac. -### Using a Predicate-Formatter ### +#### Using a Predicate-Formatter If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and `(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your predicate do not support streaming to `ostream`, you can instead use the -following _predicate-formatter assertions_ to _fully_ customize how the -message is formatted: - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful | -| `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful | -| `...` | `...` | `...` | +following *predicate-formatter assertions* to *fully* customize how the message +is formatted: -The difference between this and the previous two groups of macros is that instead of -a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_ -(_pred\_formatn_), which is a function or functor with the signature: +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------------------ | ------------------------------------------------ | -------- +`ASSERT_PRED_FORMAT1(pred_format1, val1);` | `EXPECT_PRED_FORMAT1(pred_format1, val1);` | `pred_format1(val1)` is successful +`ASSERT_PRED_FORMAT2(pred_format2, val1, val2);` | `EXPECT_PRED_FORMAT2(pred_format2, val1, val2);` | `pred_format2(val1, val2)` is successful +`...` | `...` | ... -`::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);` +The difference between this and the previous group of macros is that instead of +a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a *predicate-formatter* +(`pred_formatn`), which is a function or functor with the signature: -where _val1_, _val2_, ..., and _valn_ are the values of the predicate -arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding -expressions as they appear in the source code. The types `T1`, `T2`, ..., and -`Tn` can be either value types or reference types. For example, if an -argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`, -whichever is appropriate. +```c++ +::testing::AssertionResult PredicateFormattern(const char* expr1, + const char* expr2, + ... + const char* exprn, + T1 val1, + T2 val2, + ... + Tn valn); +``` -A predicate-formatter returns a `::testing::AssertionResult` object to indicate -whether the assertion has succeeded or not. The only way to create such an -object is to call one of these factory functions: +where `val1`, `val2`, ..., and `valn` are the values of the predicate arguments, +and `expr1`, `expr2`, ..., and `exprn` are the corresponding expressions as they +appear in the source code. The types `T1`, `T2`, ..., and `Tn` can be either +value types or reference types. For example, if an argument has type `Foo`, you +can declare it as either `Foo` or `const Foo&`, whichever is appropriate. -As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`: +As an example, let's improve the failure message in `MutuallyPrime()`, which was +used with `EXPECT_PRED2()`: -``` +```c++ // Returns the smallest prime common divisor of m and n, // or 1 when m and n are mutually prime. int SmallestPrimeCommonDivisor(int m, int n) { ... } @@ -263,167 +295,260 @@ int SmallestPrimeCommonDivisor(int m, int n) { ... } const char* n_expr, int m, int n) { - if (MutuallyPrime(m, n)) - return ::testing::AssertionSuccess(); + if (MutuallyPrime(m, n)) return ::testing::AssertionSuccess(); - return ::testing::AssertionFailure() - << m_expr << " and " << n_expr << " (" << m << " and " << n - << ") are not mutually prime, " << "as they have a common divisor " - << SmallestPrimeCommonDivisor(m, n); + return ::testing::AssertionFailure() << m_expr << " and " << n_expr + << " (" << m << " and " << n << ") are not mutually prime, " + << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); } ``` With this predicate-formatter, we can use -``` -EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); +```c++ + EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); ``` to generate the message -
-b and c (4 and 10) are not mutually prime, as they have a common divisor 2.
-
+```none +b and c (4 and 10) are not mutually prime, as they have a common divisor 2. +``` -As you may have realized, many of the assertions we introduced earlier are -special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are +As you may have realized, many of the built-in assertions we introduced earlier +are special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. -_Availability_: Linux, Windows, Mac. - +**Availability**: Linux, Windows, Mac. -## Floating-Point Comparison ## +### Floating-Point Comparison -Comparing floating-point numbers is tricky. Due to round-off errors, it is -very unlikely that two floating-points will match exactly. Therefore, -`ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points -can have a wide value range, no single fixed error bound works. It's better to -compare by a fixed relative error bound, except for values close to 0 due to -the loss of precision there. +Comparing floating-point numbers is tricky. Due to round-off errors, it is very +unlikely that two floating-points will match exactly. Therefore, `ASSERT_EQ` 's +naive comparison usually doesn't work. And since floating-points can have a wide +value range, no single fixed error bound works. It's better to compare by a +fixed relative error bound, except for values close to 0 due to the loss of +precision there. In general, for floating-point comparison to make sense, the user needs to carefully choose the error bound. If they don't want or care to, comparing in -terms of Units in the Last Place (ULPs) is a good default, and Google Test +terms of Units in the Last Place (ULPs) is a good default, and googletest provides assertions to do this. Full details about ULPs are quite long; if you want to learn more, see -[this article on float comparison](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). +[here](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). + +#### Floating-Point Macros -### Floating-Point Macros ### +| Fatal assertion | Nonfatal assertion | Verifies | +| ----------------------- | ----------------------- | ----------------------- | +| `ASSERT_FLOAT_EQ(val1, | `EXPECT_FLOAT_EQ(val1, | the two `float` values | +: val2);` : val2);` : are almost equal : +| `ASSERT_DOUBLE_EQ(val1, | `EXPECT_DOUBLE_EQ(val1, | the two `double` values | +: val2);` : val2);` : are almost equal : -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_FLOAT_EQ(`_val1, val2_`);` | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal | -| `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal | +By "almost equal" we mean the values are within 4 ULP's from each other. -By "almost equal", we mean the two values are within 4 ULP's from each -other. +NOTE: `CHECK_DOUBLE_EQ()` in `base/logging.h` uses a fixed absolute error bound, +so its result may differ from that of the googletest macros. That macro is +unsafe and has been deprecated. Please don't use it any more. The following assertions allow you to choose the acceptable error bound: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error | +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------ | ------------------------ | ------------------------- | +| `ASSERT_NEAR(val1, | `EXPECT_NEAR(val1, val2, | the difference between | +: val2, abs_error);` : abs_error);` : `val1` and `val2` doesn't : +: : : exceed the given absolute : +: : : error : -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Floating-Point Predicate-Format Functions ### +#### Floating-Point Predicate-Format Functions -Some floating-point operations are useful, but not that often used. In order -to avoid an explosion of new macros, we provide them as predicate-format -functions that can be used in predicate assertion macros (e.g. -`EXPECT_PRED_FORMAT2`, etc). +Some floating-point operations are useful, but not that often used. In order to +avoid an explosion of new macros, we provide them as predicate-format functions +that can be used in predicate assertion macros (e.g. `EXPECT_PRED_FORMAT2`, +etc). -``` +```c++ EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); ``` -Verifies that _val1_ is less than, or almost equal to, _val2_. You can -replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. +Verifies that `val1` is less than, or almost equal to, `val2`. You can replace +`EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. -_Availability_: Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. + +### Asserting Using gMock Matchers + +Google-developed C++ mocking framework [gMock](http://go/gmock) comes with a +library of matchers for validating arguments passed to mock objects. A gMock +*matcher* is basically a predicate that knows how to describe itself. It can be +used in these assertion macros: + +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------- | ------------------------------ | --------------------- | +| `ASSERT_THAT(value, | `EXPECT_THAT(value, matcher);` | value matches matcher | +: matcher);` : : : -## Windows HRESULT assertions ## +For example, `StartsWith(prefix)` is a matcher that matches a string starting +with `prefix`, and you can write: + +```c++ +using ::testing::StartsWith; +... + // Verifies that Foo() returns a string starting with "Hello". + EXPECT_THAT(Foo(), StartsWith("Hello")); +``` + +Read this [recipe](http://go/gmockguide#using-matchers-in-gunit-assertions) in +the gMock Cookbook for more details. + +gMock has a rich set of matchers. You can do many things googletest cannot do +alone with them. For a list of matchers gMock provides, read +[this](http://go/gmockguide#using-matchers). Especially useful among them are +some [protocol buffer matchers](http://go/protomatchers). It's easy to write +your [own matchers](http://go/gmockguide#NewMatchers) too. + +For example, you can use gMock's +[EqualsProto](http://cs/#piper///depot/google3/testing/base/public/gmock_utils/protocol-buffer-matchers.h) +to compare protos in your tests: + +```c++ +#include "testing/base/public/gmock.h" +using ::testing::EqualsProto; +... + EXPECT_THAT(actual_proto, EqualsProto("foo: 123 bar: 'xyz'")); + EXPECT_THAT(*actual_proto_ptr, EqualsProto(expected_proto)); +``` + +gMock is bundled with googletest, so you don't need to add any build dependency +in order to take advantage of this. Just include `"testing/base/public/gmock.h"` +and you're ready to go. + +**Availability**: Linux, Windows, and Mac. + +### More String Assertions + +(Please read the [previous](#AssertThat) section first if you haven't.) + +You can use the gMock [string matchers](http://go/gmockguide#string-matchers) +with `EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks +(sub-string, prefix, suffix, regular expression, and etc). For example, + +```c++ +using ::testing::HasSubstr; +using ::testing::MatchesRegex; +... + ASSERT_THAT(foo_string, HasSubstr("needle")); + EXPECT_THAT(bar_string, MatchesRegex("\\w*\\d+")); +``` + +**Availability**: Linux, Windows, Mac. + +If the string contains a well-formed HTML or XML document, you can check whether +its DOM tree matches an [XPath +expression](http://www.w3.org/TR/xpath/#contents): + +```c++ +// Currently still in //template/prototemplate/testing:xpath_matcher +#include "template/prototemplate/testing/xpath_matcher.h" +using prototemplate::testing::MatchesXPath; +EXPECT_THAT(html_string, MatchesXPath("//a[text()='click here']")); +``` + +**Availability**: Linux. + +### Windows HRESULT assertions These assertions test for `HRESULT` success or failure. -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` | -| `ASSERT_HRESULT_FAILED(`_expression_`);` | `EXPECT_HRESULT_FAILED(`_expression_`);` | _expression_ is a failure `HRESULT` | +Fatal assertion | Nonfatal assertion | Verifies +-------------------------------------- | -------------------------------------- | -------- +`ASSERT_HRESULT_SUCCEEDED(expression)` | `EXPECT_HRESULT_SUCCEEDED(expression)` | `expression` is a success `HRESULT` +`ASSERT_HRESULT_FAILED(expression)` | `EXPECT_HRESULT_FAILED(expression)` | `expression` is a failure `HRESULT` -The generated output contains the human-readable error message -associated with the `HRESULT` code returned by _expression_. +The generated output contains the human-readable error message associated with +the `HRESULT` code returned by `expression`. You might use them like this: -``` -CComPtr shell; +```c++ +CComPtr shell; ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); CComVariant empty; ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); ``` -_Availability_: Windows. +**Availability**: Windows. -## Type Assertions ## +### Type Assertions You can call the function -``` + +```c++ ::testing::StaticAssertTypeEq(); ``` -to assert that types `T1` and `T2` are the same. The function does -nothing if the assertion is satisfied. If the types are different, -the function call will fail to compile, and the compiler error message -will likely (depending on the compiler) show you the actual values of -`T1` and `T2`. This is mainly useful inside template code. -_Caveat:_ When used inside a member function of a class template or a -function template, `StaticAssertTypeEq()` is effective _only if_ -the function is instantiated. For example, given: -``` +to assert that types `T1` and `T2` are the same. The function does nothing if +the assertion is satisfied. If the types are different, the function call will +fail to compile, and the compiler error message will likely (depending on the +compiler) show you the actual values of `T1` and `T2`. This is mainly useful +inside template code. + +**Caveat**: When used inside a member function of a class template or a function +template, `StaticAssertTypeEq()` is effective only if the function is +instantiated. For example, given: + +```c++ template class Foo { public: void Bar() { ::testing::StaticAssertTypeEq(); } }; ``` + the code: -``` + +```c++ void Test1() { Foo foo; } ``` -will _not_ generate a compiler error, as `Foo::Bar()` is never -actually instantiated. Instead, you need: -``` + +will not generate a compiler error, as `Foo::Bar()` is never actually +instantiated. Instead, you need: + +```c++ void Test2() { Foo foo; foo.Bar(); } ``` + to cause a compiler error. -_Availability:_ Linux, Windows, Mac; since version 1.3.0. +**Availability**: Linux, Windows, Mac. -## Assertion Placement ## +### Assertion Placement -You can use assertions in any C++ function. In particular, it doesn't -have to be a method of the test fixture class. The one constraint is -that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`) -can only be used in void-returning functions. This is a consequence of -Google Test not using exceptions. By placing it in a non-void function -you'll get a confusing compile error like -`"error: void value not ignored as it ought to be"`. +You can use assertions in any C++ function. In particular, it doesn't have to be +a method of the test fixture class. The one constraint is that assertions that +generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in +void-returning functions. This is a consequence of Google's not using +exceptions. By placing it in a non-void function you'll get a confusing compile +error like `"error: void value not ignored as it ought to be"` or `"cannot +initialize return object of type 'bool' with an rvalue of type 'void'"` or +`"error: no viable conversion from 'void' to 'string'"`. -If you need to use assertions in a function that returns non-void, one option -is to make the function return the value in an out parameter instead. For +If you need to use fatal assertions in a function that returns non-void, one +option is to make the function return the value in an out parameter instead. For example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You need to make sure that `*result` contains some sensible value even when the function returns prematurely. As the function now returns `void`, you can use any assertion inside of it. -If changing the function's type is not an option, you should just use -assertions that generate non-fatal failures, such as `ADD_FAILURE*` and -`EXPECT_*`. +If changing the function's type is not an option, you should just use assertions +that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. -_Note_: Constructors and destructors are not considered void-returning -functions, according to the C++ language specification, and so you may not use -fatal assertions in them. You'll get a compilation error if you try. A simple +NOTE: Constructors and destructors are not considered void-returning functions, +according to the C++ language specification, and so you may not use fatal +assertions in them. You'll get a compilation error if you try. A simple workaround is to transfer the entire body of the constructor or destructor to a private void-returning method. However, you should be aware that a fatal assertion failure in a constructor does not terminate the current test, as your @@ -432,30 +557,37 @@ leaving your object in a partially-constructed state. Likewise, a fatal assertion failure in a destructor may leave your object in a partially-destructed state. Use assertions carefully in these situations! -# Teaching Google Test How to Print Your Values # +## Teaching googletest How to Print Your Values -When a test assertion such as `EXPECT_EQ` fails, Google Test prints the -argument values to help you debug. It does this using a -user-extensible value printer. +When a test assertion such as `EXPECT_EQ` fails, googletest prints the argument +values to help you debug. It does this using a user-extensible value printer. This printer knows how to print built-in C++ types, native arrays, STL -containers, and any type that supports the `<<` operator. For other -types, it prints the raw bytes in the value and hopes that you the -user can figure it out. +containers, and any type that supports the `<<` operator. For other types, it +prints the raw bytes in the value and hopes that you the user can figure it out. -As mentioned earlier, the printer is _extensible_. That means -you can teach it to do a better job at printing your particular type -than to dump the bytes. To do that, define `<<` for your type: +As mentioned earlier, the printer is *extensible*. That means you can teach it +to do a better job at printing your particular type than to dump the bytes. To +do that, define `<<` for your type: -``` -#include +```c++ +// Streams are allowed only for logging. Don't include this for +// any other purpose. +#include namespace foo { -class Bar { ... }; // We want Google Test to be able to print instances of this. +class Bar { // We want googletest to be able to print instances of this. +... + // Create a free inline friend function. + friend ::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { + return os << bar.DebugString(); // whatever needed to print bar to os + } +}; -// It's important that the << operator is defined in the SAME -// namespace that defines Bar. C++'s look-up rules rely on that. +// If you can't declare the function in the class it's important that the +// << operator is defined in the SAME namespace that defines Bar. C++'s look-up +// rules rely on that. ::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { return os << bar.DebugString(); // whatever needed to print bar to os } @@ -463,20 +595,28 @@ class Bar { ... }; // We want Google Test to be able to print instances of this } // namespace foo ``` -Sometimes, this might not be an option: your team may consider it bad -style to have a `<<` operator for `Bar`, or `Bar` may already have a -`<<` operator that doesn't do what you want (and you cannot change -it). If so, you can instead define a `PrintTo()` function like this: +Sometimes, this might not be an option: your team may consider it bad style to +have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that +doesn't do what you want (and you cannot change it). If so, you can instead +define a `PrintTo()` function like this: -``` -#include +```c++ +// Streams are allowed only for logging. Don't include this for +// any other purpose. +#include namespace foo { -class Bar { ... }; +class Bar { + ... + friend void PrintTo(const Bar& bar, ::std::ostream* os) { + *os << bar.DebugString(); // whatever needed to print bar to os + } +}; -// It's important that PrintTo() is defined in the SAME -// namespace that defines Bar. C++'s look-up rules rely on that. +// If you can't declare the function in the class it's important that PrintTo() +// is defined in the SAME namespace that defines Bar. C++'s look-up rules rely +// on that. void PrintTo(const Bar& bar, ::std::ostream* os) { *os << bar.DebugString(); // whatever needed to print bar to os } @@ -484,85 +624,86 @@ void PrintTo(const Bar& bar, ::std::ostream* os) { } // namespace foo ``` -If you have defined both `<<` and `PrintTo()`, the latter will be used -when Google Test is concerned. This allows you to customize how the value -appears in Google Test's output without affecting code that relies on the -behavior of its `<<` operator. +If you have defined both `<<` and `PrintTo()`, the latter will be used when +googletest is concerned. This allows you to customize how the value appears in +googletest's output without affecting code that relies on the behavior of its +`<<` operator. -If you want to print a value `x` using Google Test's value printer -yourself, just call `::testing::PrintToString(`_x_`)`, which -returns an `std::string`: +If you want to print a value `x` using googletest's value printer yourself, just +call `::testing::PrintToString(x)`, which returns an `std::string`: -``` +```c++ vector > bar_ints = GetBarIntVector(); EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) << "bar_ints = " << ::testing::PrintToString(bar_ints); ``` -# Death Tests # +## Death Tests -In many applications, there are assertions that can cause application failure -if a condition is not met. These sanity checks, which ensure that the program -is in a known good state, are there to fail at the earliest possible time after -some program state is corrupted. If the assertion checks the wrong condition, -then the program may proceed in an erroneous state, which could lead to memory -corruption, security holes, or worse. Hence it is vitally important to test -that such assertion statements work as expected. +In many applications, there are assertions that can cause application failure if +a condition is not met. These sanity checks, which ensure that the program is in +a known good state, are there to fail at the earliest possible time after some +program state is corrupted. If the assertion checks the wrong condition, then +the program may proceed in an erroneous state, which could lead to memory +corruption, security holes, or worse. Hence it is vitally important to test that +such assertion statements work as expected. Since these precondition checks cause the processes to die, we call such tests _death tests_. More generally, any test that checks that a program terminates (except by throwing an exception) in an expected fashion is also a death test. + Note that if a piece of code throws an exception, we don't consider it "death" -for the purpose of death tests, as the caller of the code could catch the exception -and avoid the crash. If you want to verify exceptions thrown by your code, -see [Exception Assertions](#exception-assertions). +for the purpose of death tests, as the caller of the code could catch the +exception and avoid the crash. If you want to verify exceptions thrown by your +code, see [Exception Assertions](#ExceptionAssertions). -If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures). +If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see +Catching Failures -## How to Write a Death Test ## +### How to Write a Death Test -Google Test has the following macros to support death tests: +googletest has the following macros to support death tests: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error | -| `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing | -| `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ | +Fatal assertion | Nonfatal assertion | Verifies +---------------------------------------------- | ---------------------------------------------- | -------- +`ASSERT_DEATH(statement, regex);` | `EXPECT_DEATH(statement, regex);` | `statement` crashes with the given error +`ASSERT_DEATH_IF_SUPPORTED(statement, regex);` | `EXPECT_DEATH_IF_SUPPORTED(statement, regex);` | if death tests are supported, verifies that `statement` crashes with the given error; otherwise verifies nothing +`ASSERT_EXIT(statement, predicate, regex);` | `EXPECT_EXIT(statement, predicate, regex);` | `statement` exits with the given error, and its exit code matches `predicate` -where _statement_ is a statement that is expected to cause the process to -die, _predicate_ is a function or function object that evaluates an integer -exit status, and _regex_ is a regular expression that the stderr output of -_statement_ is expected to match. Note that _statement_ can be _any valid -statement_ (including _compound statement_) and doesn't have to be an +where `statement` is a statement that is expected to cause the process to die, +`predicate` is a function or function object that evaluates an integer exit +status, and `regex` is a (Perl) regular expression that the stderr output of +`statement` is expected to match. Note that `statement` can be *any valid +statement* (including *compound statement*) and doesn't have to be an expression. + As usual, the `ASSERT` variants abort the current test function, while the `EXPECT` variants do not. -**Note:** We use the word "crash" here to mean that the process -terminates with a _non-zero_ exit status code. There are two -possibilities: either the process has called `exit()` or `_exit()` -with a non-zero value, or it may be killed by a signal. - -This means that if _statement_ terminates the process with a 0 exit -code, it is _not_ considered a crash by `EXPECT_DEATH`. Use -`EXPECT_EXIT` instead if this is the case, or if you want to restrict -the exit code more precisely. +> NOTE: We use the word "crash" here to mean that the process terminates with a +> *non-zero* exit status code. There are two possibilities: either the process +> has called `exit()` or `_exit()` with a non-zero value, or it may be killed by +> a signal. +> +> This means that if `*statement*` terminates the process with a 0 exit code, it +> is *not* considered a crash by `EXPECT_DEATH`. Use `EXPECT_EXIT` instead if +> this is the case, or if you want to restrict the exit code more precisely. A predicate here must accept an `int` and return a `bool`. The death test -succeeds only if the predicate returns `true`. Google Test defines a few +succeeds only if the predicate returns `true`. googletest defines a few predicates that handle the most common cases: -``` +```c++ ::testing::ExitedWithCode(exit_code) ``` This expression is `true` if the program exited normally with the given exit code. -``` +```c++ ::testing::KilledBySignal(signal_number) // Not available on Windows. ``` @@ -573,49 +714,63 @@ that verifies the process' exit code is non-zero. Note that a death test only cares about three things: - 1. does _statement_ abort or exit the process? - 1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And - 1. does the stderr output match _regex_? +1. does `statement` abort or exit the process? +2. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status + satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) + is the exit status non-zero? And +3. does the stderr output match `regex`? -In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process. +In particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it +will **not** cause the death test to fail, as googletest assertions don't abort +the process. To write a death test, simply use one of the above macros inside your test function. For example, -``` +```c++ TEST(MyDeathTest, Foo) { // This death test uses a compound statement. - ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()"); + ASSERT_DEATH({ + int n = 5; + Foo(&n); + }, "Error on line .* of Foo()"); } + TEST(MyDeathTest, NormalExit) { EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); } + TEST(MyDeathTest, KillMyself) { - EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); + EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), + "Sending myself unblockable signal"); } ``` verifies that: - * calling `Foo(5)` causes the process to die with the given error message, - * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and - * calling `KillMyself()` kills the process with signal `SIGKILL`. +* calling `Foo(5)` causes the process to die with the given error message, +* calling `NormalExit()` causes the process to print `"Success"` to stderr and + exit with exit code 0, and +* calling `KillMyself()` kills the process with signal `SIGKILL`. The test function body may contain other assertions and statements as well, if necessary. -_Important:_ We strongly recommend you to follow the convention of naming your -test case (not test) `*DeathTest` when it contains a death test, as -demonstrated in the above example. The `Death Tests And Threads` section below -explains why. +### Death Test Naming -If a test fixture class is shared by normal tests and death tests, you -can use typedef to introduce an alias for the fixture class and avoid +IMPORTANT: We strongly recommend you to follow the convention of naming your +**test case** (not test) `*DeathTest` when it contains a death test, as +demonstrated in the above example. The [Death Tests And +Threads](#death-tests-and-threads) section below explains why. + +If a test fixture class is shared by normal tests and death tests, you can use +`using` or `typedef` to introduce an alias for the fixture class and avoid duplicating its code: -``` + +```c++ class FooTest : public ::testing::Test { ... }; -typedef FooTest FooDeathTest; +using FooDeathTest = FooTest; TEST_F(FooTest, DoesThis) { // normal test @@ -626,79 +781,86 @@ TEST_F(FooDeathTest, DoesThat) { } ``` -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0). `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac + +### Regular Expression Syntax -## Regular Expression Syntax ## -On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the +On POSIX systems (e.g. Linux, Cygwin, and Mac), googletest uses the [POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) -syntax in death tests. To learn about this syntax, you may want to read this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). - -On Windows, Google Test uses its own simple regular expression -implementation. It lacks many features you can find in POSIX extended -regular expressions. For example, we don't support union (`"x|y"`), -grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count -(`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a -literal character, period (`.`), or a single `\\` escape sequence; `x` -and `y` denote regular expressions.): - -| `c` | matches any literal character `c` | -|:----|:----------------------------------| -| `\\d` | matches any decimal digit | -| `\\D` | matches any character that's not a decimal digit | -| `\\f` | matches `\f` | -| `\\n` | matches `\n` | -| `\\r` | matches `\r` | -| `\\s` | matches any ASCII whitespace, including `\n` | -| `\\S` | matches any character that's not a whitespace | -| `\\t` | matches `\t` | -| `\\v` | matches `\v` | -| `\\w` | matches any letter, `_`, or decimal digit | -| `\\W` | matches any character that `\\w` doesn't match | -| `\\c` | matches any literal character `c`, which must be a punctuation | -| `\\.` | matches the `.` character | -| `.` | matches any single character except `\n` | -| `A?` | matches 0 or 1 occurrences of `A` | -| `A*` | matches 0 or many occurrences of `A` | -| `A+` | matches 1 or many occurrences of `A` | -| `^` | matches the beginning of a string (not that of each line) | -| `$` | matches the end of a string (not that of each line) | -| `xy` | matches `x` followed by `y` | - -To help you determine which capability is available on your system, -Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX -extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses -the simple version. If you want your death tests to work in both -cases, you can either `#if` on these macros or use the more limited -syntax only. - -## How It Works ## - -Under the hood, `ASSERT_EXIT()` spawns a new process and executes the -death test statement in that process. The details of how precisely -that happens depend on the platform and the variable -`::testing::GTEST_FLAG(death_test_style)` (which is initialized from the -command-line flag `--gtest_death_test_style`). - - * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which: - * If the variable's value is `"fast"`, the death test statement is immediately executed. - * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run. - * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX. - -Other values for the variable are illegal and will cause the death test to -fail. Currently, the flag's default value is `"fast"`. However, we reserve the -right to change it in the future. Therefore, your tests should not depend on -this. - -In either case, the parent process waits for the child process to complete, and checks that - - 1. the child's exit status satisfies the predicate, and - 1. the child's stderr matches the regular expression. - -If the death test statement runs to completion without dying, the child -process will nonetheless terminate, and the assertion fails. - -## Death Tests And Threads ## +syntax. To learn about this syntax, you may want to read this +[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). + +On Windows, googletest uses its own simple regular expression implementation. It +lacks many features. For example, we don't support union (`"x|y"`), grouping +(`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among +others. Below is what we do support (`A` denotes a literal character, period +(`.`), or a single `\\ ` escape sequence; `x` and `y` denote regular +expressions.): + +Expression | Meaning +---------- | -------------------------------------------------------------- +`c` | matches any literal character `c` +`\\d` | matches any decimal digit +`\\D` | matches any character that's not a decimal digit +`\\f` | matches `\f` +`\\n` | matches `\n` +`\\r` | matches `\r` +`\\s` | matches any ASCII whitespace, including `\n` +`\\S` | matches any character that's not a whitespace +`\\t` | matches `\t` +`\\v` | matches `\v` +`\\w` | matches any letter, `_`, or decimal digit +`\\W` | matches any character that `\\w` doesn't match +`\\c` | matches any literal character `c`, which must be a punctuation +`.` | matches any single character except `\n` +`A?` | matches 0 or 1 occurrences of `A` +`A*` | matches 0 or many occurrences of `A` +`A+` | matches 1 or many occurrences of `A` +`^` | matches the beginning of a string (not that of each line) +`$` | matches the end of a string (not that of each line) +`xy` | matches `x` followed by `y` + +To help you determine which capability is available on your system, googletest +defines macros to govern which regular expression it is using. The macros are: +`GTEST_USES_PCRE=1`, or + `GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If +you want your death tests to work in all cases, you can either `#if` on these +macros or use the more limited syntax only. + +### How It Works + +Under the hood, `ASSERT_EXIT()` spawns a new process and executes the death test +statement in that process. The details of how precisely that happens depend on +the platform and the variable ::testing::GTEST_FLAG(death_test_style) (which is +initialized from the command-line flag `--gtest_death_test_style`). + +* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the + child, after which: + * If the variable's value is `"fast"`, the death test statement is + immediately executed. + * If the variable's value is `"threadsafe"`, the child process re-executes + the unit test binary just as it was originally invoked, but with some + extra flags to cause just the single death test under consideration to + be run. +* On Windows, the child is spawned using the `CreateProcess()` API, and + re-executes the binary to cause just the single death test under + consideration to be run - much like the `threadsafe` mode on POSIX. + +Other values for the variable are illegal and will cause the death test to fail. +Currently, the flag's default value is +"fast". However, we reserve +the right to change it in the future. Therefore, your tests should not depend on +this. In either case, the parent process waits for the child process to +complete, and checks that + +1. the child's exit status satisfies the predicate, and +2. the child's stderr matches the regular expression. + +If the death test statement runs to completion without dying, the child process +will nonetheless terminate, and the assertion fails. + +### Death Tests And Threads The reason for the two death test styles has to do with thread safety. Due to well-known problems with forking in the presence of threads, death tests should @@ -707,35 +869,43 @@ arrange that kind of environment. For example, statically-initialized modules may start threads before main is ever reached. Once threads have been created, it may be difficult or impossible to clean them up. -Google Test has three features intended to raise awareness of threading issues. +googletest has three features intended to raise awareness of threading issues. - 1. A warning is emitted if multiple threads are running when a death test is encountered. - 1. Test cases with a name ending in "DeathTest" are run before all other tests. - 1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. +1. A warning is emitted if multiple threads are running when a death test is + encountered. +2. Test cases with a name ending in "DeathTest" are run before all other tests. +3. It uses `clone()` instead of `fork()` to spawn the child process on Linux + (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely + to cause the child to hang when the parent process has multiple threads. It's perfectly fine to create threads inside a death test statement; they are executed in a separate process and cannot affect the parent. -## Death Test Styles ## +### Death Test Styles + The "threadsafe" death test style was introduced in order to help mitigate the risks of testing in a possibly multithreaded environment. It trades increased test execution time (potentially dramatically so) for improved thread safety. -We suggest using the faster, default "fast" style unless your test has specific -problems with it. -You can choose a particular style of death tests by setting the flag -programmatically: +The automated testing framework does not set the style flag. You can choose a +particular style of death tests by setting the flag programmatically: -``` -::testing::FLAGS_gtest_death_test_style = "threadsafe"; +```c++ +testing::FLAGS_gtest_death_test_style="threadsafe" ``` -You can do this in `main()` to set the style for all death tests in the -binary, or in individual tests. Recall that flags are saved before running each -test and restored afterwards, so you need not do that yourself. For example: +You can do this in `main()` to set the style for all death tests in the binary, +or in individual tests. Recall that flags are saved before running each test and +restored afterwards, so you need not do that yourself. For example: + +```c++ +int main(int argc, char** argv) { + InitGoogle(argv[0], &argc, &argv, true); + ::testing::FLAGS_gtest_death_test_style = "fast"; + return RUN_ALL_TESTS(); +} -``` TEST(MyDeathTest, TestOne) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; // This test is run in the "threadsafe" style: @@ -746,52 +916,51 @@ TEST(MyDeathTest, TestTwo) { // This test is run in the "fast" style: ASSERT_DEATH(ThisShouldDie(), ""); } - -int main(int argc, char** argv) { - ::testing::InitGoogleTest(&argc, argv); - ::testing::FLAGS_gtest_death_test_style = "fast"; - return RUN_ALL_TESTS(); -} ``` -## Caveats ## -The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement. -If it leaves the current function via a `return` statement or by throwing an exception, -the death test is considered to have failed. Some Google Test macros may return -from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_. +### Caveats -Since _statement_ runs in the child process, any in-memory side effect (e.g. -modifying a variable, releasing memory, etc) it causes will _not_ be observable +The `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If +it leaves the current function via a `return` statement or by throwing an +exception, the death test is considered to have failed. Some googletest macros +may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid +them in `statement`. + +Since `statement` runs in the child process, any in-memory side effect (e.g. +modifying a variable, releasing memory, etc) it causes will *not* be observable in the parent process. In particular, if you release memory in a death test, your program will fail the heap check as the parent process will never see the memory reclaimed. To solve this problem, you can - 1. try not to free memory in a death test; - 1. free the memory again in the parent process; or - 1. do not use the heap checker in your program. +1. try not to free memory in a death test; +2. free the memory again in the parent process; or +3. do not use the heap checker in your program. -Due to an implementation detail, you cannot place multiple death test -assertions on the same line; otherwise, compilation will fail with an unobvious -error message. +Due to an implementation detail, you cannot place multiple death test assertions +on the same line; otherwise, compilation will fail with an unobvious error +message. Despite the improved thread safety afforded by the "threadsafe" style of death test, thread problems such as deadlock are still possible in the presence of handlers registered with `pthread_atfork(3)`. -# Using Assertions in Sub-routines # -## Adding Traces to Assertions ## +## Using Assertions in Sub-routines + +### Adding Traces to Assertions -If a test sub-routine is called from several places, when an assertion -inside it fails, it can be hard to tell which invocation of the -sub-routine the failure is from. You can alleviate this problem using -extra logging or custom failure messages, but that usually clutters up -your tests. A better solution is to use the `SCOPED_TRACE` macro or -the `ScopedTrace` utility: +If a test sub-routine is called from several places, when an assertion inside it +fails, it can be hard to tell which invocation of the sub-routine the failure is +from. +You can alleviate this problem using extra logging or custom failure messages, +but that usually clutters up your tests. A better solution is to use the +`SCOPED_TRACE` macro or the `ScopedTrace` utility: -| `SCOPED_TRACE(`_message_`);` | `::testing::ScopedTrace trace(`_"file\_path"_`, `_line\_number_`, `_message_`);` | -|:-----------------------------|:---------------------------------------------------------------------------------| +```c++ +SCOPED_TRACE(message); +ScopedTrace trace("file_path", line_number, message); +``` where `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE` macro will cause the current file name, line number, and the given message to be @@ -801,7 +970,7 @@ will be undone when the control leaves the current lexical scope. For example, -``` +```c++ 10: void Sub1(int n) { 11: EXPECT_EQ(1, Bar(n)); 12: EXPECT_EQ(2, Bar(n + 1)); @@ -820,7 +989,7 @@ For example, could result in messages like these: -``` +```none path/to/foo_test.cc:11: Failure Value of: Bar(n) Expected: 1 @@ -834,45 +1003,56 @@ Expected: 2 Actual: 3 ``` -Without the trace, it would've been difficult to know which invocation -of `Sub1()` the two failures come from respectively. (You could add an -extra message to each assertion in `Sub1()` to indicate the value of -`n`, but that's tedious.) +Without the trace, it would've been difficult to know which invocation of +`Sub1()` the two failures come from respectively. (You could add + +an extra message to each assertion in `Sub1()` to indicate the value of `n`, but +that's tedious.) Some tips on using `SCOPED_TRACE`: - 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site. - 1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from. - 1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`. - 1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. - 1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! +1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the + beginning of a sub-routine, instead of at each call site. +2. When calling sub-routines inside a loop, make the loop iterator part of the + message in `SCOPED_TRACE` such that you can know which iteration the failure + is from. +3. Sometimes the line number of the trace point is enough for identifying the + particular invocation of a sub-routine. In this case, you don't have to + choose a unique message for `SCOPED_TRACE`. You can simply use `""`. +4. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer + scope. In this case, all active trace points will be included in the failure + messages, in reverse order they are encountered. +5. The trace dump is clickable in Emacs - hit `return` on a line number and + you'll be taken to that line in the source file! -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -## Propagating Fatal Failures ## +### Propagating Fatal Failures A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that when they fail they only abort the _current function_, not the entire test. For example, the following test will segfault: -``` + +```c++ void Subroutine() { // Generates a fatal failure and aborts the current function. ASSERT_EQ(1, 2); + // The following won't be executed. ... } TEST(FooTest, Bar) { - Subroutine(); - // The intended behavior is for the fatal failure - // in Subroutine() to abort the entire test. + Subroutine(); // The intended behavior is for the fatal failure + // in Subroutine() to abort the entire test. + // The actual behavior: the function goes on after Subroutine() returns. int* p = NULL; - *p = 3; // Segfault! + *p = 3; // Segfault! } ``` -To alleviate this, gUnit provides three different solutions. You could use +To alleviate this, googletest provides three different solutions. You could use either exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the `HasFatalFailure()` function. They are described in the following two subsections. @@ -899,26 +1079,26 @@ int main(int argc, char** argv) { This listener should be added after other listeners if you have any, otherwise they won't see failed `OnTestPartResult`. -### Asserting on Subroutines ### +#### Asserting on Subroutines -As shown above, if your test calls a subroutine that has an `ASSERT_*` -failure in it, the test will continue after the subroutine -returns. This may not be what you want. +As shown above, if your test calls a subroutine that has an `ASSERT_*` failure +in it, the test will continue after the subroutine returns. This may not be what +you want. -Often people want fatal failures to propagate like exceptions. For -that Google Test offers the following macros: +Often people want fatal failures to propagate like exceptions. For that +googletest offers the following macros: -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. | +Fatal assertion | Nonfatal assertion | Verifies +------------------------------------- | ------------------------------------- | -------- +`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread. -Only failures in the thread that executes the assertion are checked to -determine the result of this type of assertions. If _statement_ -creates new threads, failures in these threads are ignored. +Only failures in the thread that executes the assertion are checked to determine +the result of this type of assertions. If `statement` creates new threads, +failures in these threads are ignored. Examples: -``` +```c++ ASSERT_NO_FATAL_FAILURE(Foo()); int i; @@ -927,17 +1107,16 @@ EXPECT_NO_FATAL_FAILURE({ }); ``` -_Availability:_ Linux, Windows, Mac. Assertions from multiple threads -are currently not supported. +**Availability**: Linux, Windows, Mac. Assertions from multiple threads are +currently not supported on Windows. -### Checking for Failures in the Current Test ### +#### Checking for Failures in the Current Test `HasFatalFailure()` in the `::testing::Test` class returns `true` if an -assertion in the current test has suffered a fatal failure. This -allows functions to catch fatal failures in a sub-routine and return -early. +assertion in the current test has suffered a fatal failure. This allows +functions to catch fatal failures in a sub-routine and return early. -``` +```c++ class Test { public: ... @@ -945,15 +1124,15 @@ class Test { }; ``` -The typical usage, which basically simulates the behavior of a thrown -exception, is: +The typical usage, which basically simulates the behavior of a thrown exception, +is: -``` +```c++ TEST(FooTest, Bar) { Subroutine(); // Aborts if Subroutine() had a fatal failure. - if (HasFatalFailure()) - return; + if (HasFatalFailure()) return; + // The following won't be executed. ... } @@ -962,25 +1141,24 @@ TEST(FooTest, Bar) { If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test fixture, you must add the `::testing::Test::` prefix, as in: -``` -if (::testing::Test::HasFatalFailure()) - return; +```c++ +if (::testing::Test::HasFatalFailure()) return; ``` -Similarly, `HasNonfatalFailure()` returns `true` if the current test -has at least one non-fatal failure, and `HasFailure()` returns `true` -if the current test has at least one failure of either kind. +Similarly, `HasNonfatalFailure()` returns `true` if the current test has at +least one non-fatal failure, and `HasFailure()` returns `true` if the current +test has at least one failure of either kind. -_Availability:_ Linux, Windows, Mac. `HasNonfatalFailure()` and -`HasFailure()` are available since version 1.4.0. +**Availability**: Linux, Windows, Mac. -# Logging Additional Information # +## Logging Additional Information -In your test code, you can call `RecordProperty("key", value)` to log -additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output -if you specify one. For example, the test +In your test code, you can call `RecordProperty("key", value)` to log additional +information, where `value` can be either a string or an `int`. The *last* value +recorded for a key will be emitted to the [XML output](#XmlReport) if you +specify one. For example, the test -``` +```c++ TEST_F(WidgetUsageTest, MinAndMaxWidgets) { RecordProperty("MaximumWidgets", ComputeMaxUsage()); RecordProperty("MinimumWidgets", ComputeMinUsage()); @@ -989,51 +1167,63 @@ TEST_F(WidgetUsageTest, MinAndMaxWidgets) { will output XML like this: +```xml + ... + + ... ``` -... - -... -``` - -_Note_: - * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class. - * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`). - * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element. - -_Availability_: Linux, Windows, Mac. -# Sharing Resources Between Tests in the Same Test Case # +> NOTE: +> +> * `RecordProperty()` is a static member of the `Test` class. Therefore it +> needs to be prefixed with `::testing::Test::` if used outside of the +> `TEST` body and the test fixture class. +> * `*key*` must be a valid XML attribute name, and cannot conflict with the +> ones already used by googletest (`name`, `status`, `time`, `classname`, +> `type_param`, and `value_param`). +> * Calling `RecordProperty()` outside of the lifespan of a test is allowed. +> If it's called outside of a test but between a test case's +> `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed +> to the XML element for the test case. If it's called outside of all test +> cases (e.g. in a test environment), it will be attributed to the top-level +> XML element. +**Availability**: Linux, Windows, Mac. +## Sharing Resources Between Tests in the Same Test Case -Google Test creates a new test fixture object for each test in order to make +googletest creates a new test fixture object for each test in order to make tests independent and easier to debug. However, sometimes tests use resources that are expensive to set up, making the one-copy-per-test model prohibitively expensive. -If the tests don't change the resource, there's no harm in them sharing a -single resource copy. So, in addition to per-test set-up/tear-down, Google Test +If the tests don't change the resource, there's no harm in their sharing a +single resource copy. So, in addition to per-test set-up/tear-down, googletest also supports per-test-case set-up/tear-down. To use it: - 1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources. - 1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down. - -That's it! Google Test automatically calls `SetUpTestCase()` before running the -_first test_ in the `FooTest` test case (i.e. before creating the first -`FooTest` object), and calls `TearDownTestCase()` after running the _last test_ -in it (i.e. after deleting the last `FooTest` object). In between, the tests -can use the shared resources. +1. In your test fixture class (say `FooTest` ), declare as `static` some member + variables to hold the shared resources. +1. Outside your test fixture class (typically just below it), define those + member variables, optionally giving them initial values. +1. In the same test fixture class, define a `static void SetUpTestCase()` + function (remember not to spell it as **`SetupTestCase`** with a small `u`!) + to set up the shared resources and a `static void TearDownTestCase()` + function to tear them down. + +That's it! googletest automatically calls `SetUpTestCase()` before running the +*first test* in the `FooTest` test case (i.e. before creating the first +`FooTest` object), and calls `TearDownTestCase()` after running the *last test* +in it (i.e. after deleting the last `FooTest` object). In between, the tests can +use the shared resources. Remember that the test order is undefined, so your code can't depend on a test -preceding or following another. Also, the tests must either not modify the -state of any shared resource, or, if they do modify the state, they must -restore the state to its original value before passing control to the next -test. +preceding or following another. Also, the tests must either not modify the state +of any shared resource, or, if they do modify the state, they must restore the +state to its original value before passing control to the next test. Here's an example of per-test-case set-up and tear-down: -``` + +```c++ class FooTest : public ::testing::Test { protected: // Per-test-case set-up. @@ -1051,8 +1241,10 @@ class FooTest : public ::testing::Test { shared_resource_ = NULL; } - // You can define per-test set-up and tear-down logic as usual. + // You can define per-test set-up logic as usual. virtual void SetUp() { ... } + + // You can define per-test tear-down logic as usual. virtual void TearDown() { ... } // Some expensive resource shared by all tests. @@ -1062,16 +1254,21 @@ class FooTest : public ::testing::Test { T* FooTest::shared_resource_ = NULL; TEST_F(FooTest, Test1) { - ... you can refer to shared_resource here ... + ... you can refer to shared_resource_ here ... } + TEST_F(FooTest, Test2) { - ... you can refer to shared_resource here ... + ... you can refer to shared_resource_ here ... } ``` -_Availability:_ Linux, Windows, Mac. +NOTE: Though the above code declares `SetUpTestCase()` protected, it may +sometimes be necessary to declare it public, such as when using it with +`TEST_P`. + +**Availability**: Linux, Windows, Mac. -# Global Set-Up and Tear-Down # +## Global Set-Up and Tear-Down Just as you can do set-up and tear-down at the test level and the test case level, you can also do it at the test program level. Here's how. @@ -1079,21 +1276,23 @@ level, you can also do it at the test program level. Here's how. First, you subclass the `::testing::Environment` class to define a test environment, which knows how to set-up and tear-down: -``` +```c++ class Environment { public: virtual ~Environment() {} + // Override this to define how to set up the environment. virtual void SetUp() {} + // Override this to define how to tear down the environment. virtual void TearDown() {} }; ``` -Then, you register an instance of your environment class with Google Test by +Then, you register an instance of your environment class with googletest by calling the `::testing::AddGlobalTestEnvironment()` function: -``` +```c++ Environment* AddGlobalTestEnvironment(Environment* env); ``` @@ -1105,79 +1304,58 @@ It's OK to register multiple environment objects. In this case, their `SetUp()` will be called in the order they are registered, and their `TearDown()` will be called in the reverse order. -Note that Google Test takes ownership of the registered environment objects. +Note that googletest takes ownership of the registered environment objects. Therefore **do not delete them** by yourself. -You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is -called, probably in `main()`. If you use `gtest_main`, you need to call -this before `main()` starts for it to take effect. One way to do this is to -define a global variable like this: +You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, +probably in `main()`. If you use `gtest_main`, you need to call this before +`main()` starts for it to take effect. One way to do this is to define a global +variable like this: -``` -::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); +```c++ +::testing::Environment* const foo_env = + ::testing::AddGlobalTestEnvironment(new FooEnvironment); ``` However, we strongly recommend you to write your own `main()` and call `AddGlobalTestEnvironment()` there, as relying on initialization of global -variables makes the code harder to read and may cause problems when you -register multiple environments from different translation units and the -environments have dependencies among them (remember that the compiler doesn't -guarantee the order in which global variables from different translation units -are initialized). - -_Availability:_ Linux, Windows, Mac. +variables makes the code harder to read and may cause problems when you register +multiple environments from different translation units and the environments have +dependencies among them (remember that the compiler doesn't guarantee the order +in which global variables from different translation units are initialized). + +## Value-Parameterized Tests + +*Value-parameterized tests* allow you to test your code with different +parameters without writing multiple copies of the same test. This is useful in a +number of situations, for example: + +* You have a piece of code whose behavior is affected by one or more + command-line flags. You want to make sure your code performs correctly for + various values of those flags. +* You want to test different implementations of an OO interface. +* You want to test your code over various inputs (a.k.a. data-driven testing). + This feature is easy to abuse, so please exercise your good sense when doing + it! + +### How to Write Value-Parameterized Tests + +To write value-parameterized tests, first you should define a fixture class. It +must be derived from both `::testing::Test` and +`::testing::WithParamInterface` (the latter is a pure interface), where `T` +is the type of your parameter values. For convenience, you can just derive the +fixture class from `::testing::TestWithParam`, which itself is derived from +both `::testing::Test` and `::testing::WithParamInterface`. `T` can be any +copyable type. If it's a raw pointer, you are responsible for managing the +lifespan of the pointed values. + +NOTE: If your test fixture defines `SetUpTestCase()` or `TearDownTestCase()` +they must be declared **public** rather than **protected** in order to use +`TEST_P`. - -# Value Parameterized Tests # - -_Value-parameterized tests_ allow you to test your code with different -parameters without writing multiple copies of the same test. - -Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag. - -``` -TEST(MyCodeTest, TestFoo) { - // A code to test foo(). -} -``` - -Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code. - -``` -void TestFooHelper(bool flag_value) { - flag = flag_value; - // A code to test foo(). -} - -TEST(MyCodeTest, TestFoo) { - TestFooHelper(false); - TestFooHelper(true); -} -``` - -But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred? - -Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values. - -Here are some other situations when value-parameterized tests come handy: - - * You want to test different implementations of an OO interface. - * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! - -## How to Write Value-Parameterized Tests ## - -To write value-parameterized tests, first you should define a fixture -class. It must be derived from both `::testing::Test` and -`::testing::WithParamInterface` (the latter is a pure interface), -where `T` is the type of your parameter values. For convenience, you -can just derive the fixture class from `::testing::TestWithParam`, -which itself is derived from both `::testing::Test` and -`::testing::WithParamInterface`. `T` can be any copyable type. If -it's a raw pointer, you are responsible for managing the lifespan of -the pointed values. - -``` -class FooTest : public ::testing::TestWithParam { +```c++ +class FooTest : + public ::testing::TestWithParam { // You can implement all the usual fixture class members here. // To access the test parameter, call GetParam() from class // TestWithParam. @@ -1193,11 +1371,11 @@ class BarTest : public BaseTest, }; ``` -Then, use the `TEST_P` macro to define as many test patterns using -this fixture as you want. The `_P` suffix is for "parameterized" or -"pattern", whichever you prefer to think. +Then, use the `TEST_P` macro to define as many test patterns using this fixture +as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you +prefer to think. -``` +```c++ TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method // of the TestWithParam class: @@ -1210,50 +1388,62 @@ TEST_P(FooTest, HasBlahBlah) { } ``` -Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test -case with any set of parameters you want. Google Test defines a number of -functions for generating test parameters. They return what we call -(surprise!) _parameter generators_. Here is a summary of them, -which are all in the `testing` namespace: +Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test case with +any set of parameters you want. googletest defines a number of functions for +generating test parameters. They return what we call (surprise!) *parameter +generators*. Here is a summary of them, which are all in the `testing` +namespace: -| `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | -|:----------------------------|:------------------------------------------------------------------------------------------------------------------| -| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | -| `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time. | -| `Bool()` | Yields sequence `{false, true}`. | -| `Combine(g1, g2, ..., gN)` | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](../include/gtest/internal/gtest-port.h) for more information. | +| Parameter Generator | Behavior | +| ---------------------------- | ------------------------------------------- | +| `Range(begin, end [, step])` | Yields values `{begin, begin+step, | +: : begin+step+step, ...}`. The values do not : +: : include `end`. `step` defaults to 1. : +| `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | +| `ValuesIn(container)` and | Yields values from a C-style array, an | +: `ValuesIn(begin,end)` : STL-style container, or an iterator range : +: : `[begin, end)`. : +| `Bool()` | Yields sequence `{false, true}`. | +| `Combine(g1, g2, ..., gN)` | Yields all combinations (Cartesian product) | +: : as std\:\:tuples of the values generated by : +: : the `N` generators. : -For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h). +For more details, see the comments at the definitions of these functions. -The following statement will instantiate tests from the `FooTest` test case -each with parameter values `"meeny"`, `"miny"`, and `"moe"`. +The following statement will instantiate tests from the `FooTest` test case each +with parameter values `"meeny"`, `"miny"`, and `"moe"`. -``` +```c++ INSTANTIATE_TEST_CASE_P(InstantiationName, FooTest, ::testing::Values("meeny", "miny", "moe")); ``` -To distinguish different instances of the pattern (yes, you can -instantiate it more than once), the first argument to -`INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual -test case name. Remember to pick unique prefixes for different -instantiations. The tests from the instantiation above will have these -names: +NOTE: The code above must be placed at global or namespace scope, not at +function scope. - * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` - * `InstantiationName/FooTest.DoesBlah/1` for `"miny"` - * `InstantiationName/FooTest.DoesBlah/2` for `"moe"` - * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` - * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` - * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` +NOTE: Don't forget this step! If you do your test will silently pass, but none +of its cases will ever run! -You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests). +To distinguish different instances of the pattern (yes, you can instantiate it +more than once), the first argument to `INSTANTIATE_TEST_CASE_P` is a prefix +that will be added to the actual test case name. Remember to pick unique +prefixes for different instantiations. The tests from the instantiation above +will have these names: -This statement will instantiate all tests from `FooTest` again, each -with parameter values `"cat"` and `"dog"`: +* `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` +* `InstantiationName/FooTest.DoesBlah/1` for `"miny"` +* `InstantiationName/FooTest.DoesBlah/2` for `"moe"` +* `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` +* `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` +* `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` -``` +You can use these names in [`--gtest_filter`](#TestFilter). + +This statement will instantiate all tests from `FooTest` again, each with +parameter values `"cat"` and `"dog"`: + +```c++ const char* pets[] = {"cat", "dog"}; INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ::testing::ValuesIn(pets)); @@ -1261,65 +1451,91 @@ INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, The tests from the instantiation above will have these names: - * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` - * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` - * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` - * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` +* `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` +* `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` +* `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` +* `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` -Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_ -tests in the given test case, whether their definitions come before or -_after_ the `INSTANTIATE_TEST_CASE_P` statement. +Please note that `INSTANTIATE_TEST_CASE_P` will instantiate *all* tests in the +given test case, whether their definitions come before or *after* the +`INSTANTIATE_TEST_CASE_P` statement. -You can see -[these](../samples/sample7_unittest.cc) -[files](../samples/sample8_unittest.cc) for more examples. +You can see sample7_unittest.cc and sample8_unittest.cc for more examples. -_Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Mac -## Creating Value-Parameterized Abstract Tests ## +### Creating Value-Parameterized Abstract Tests -In the above, we define and instantiate `FooTest` in the same source -file. Sometimes you may want to define value-parameterized tests in a -library and let other people instantiate them later. This pattern is -known as abstract tests. As an example of its application, when you -are designing an interface you can write a standard suite of abstract -tests (perhaps using a factory function as the test parameter) that -all implementations of the interface are expected to pass. When -someone implements the interface, they can instantiate your suite to get -all the interface-conformance tests for free. +In the above, we define and instantiate `FooTest` in the *same* source file. +Sometimes you may want to define value-parameterized tests in a library and let +other people instantiate them later. This pattern is known as *abstract tests*. +As an example of its application, when you are designing an interface you can +write a standard suite of abstract tests (perhaps using a factory function as +the test parameter) that all implementations of the interface are expected to +pass. When someone implements the interface, they can instantiate your suite to +get all the interface-conformance tests for free. To define abstract tests, you should organize your code like this: - 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests. - 1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests. +1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) + in a header file, say `foo_param_test.h`. Think of this as *declaring* your + abstract tests. +1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes + `foo_param_test.h`. Think of this as *implementing* your abstract tests. + +Once they are defined, you can instantiate them by including `foo_param_test.h`, +invoking `INSTANTIATE_TEST_CASE_P()`, and depending on the library target that +contains `foo_param_test.cc`. You can instantiate the same abstract test case +multiple times, possibly in different source files. -Once they are defined, you can instantiate them by including -`foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking -with `foo_param_test.cc`. You can instantiate the same abstract test -case multiple times, possibly in different source files. +### Specifying Names for Value-Parameterized Test Parameters -# Typed Tests # +The optional last argument to `INSTANTIATE_TEST_CASE_P()` allows the user to +specify a function or functor that generates custom test name suffixes based on +the test parameters. The function should accept one argument of type +`testing::TestParamInfo`, and return `std::string`. -Suppose you have multiple implementations of the same interface and -want to make sure that all of them satisfy some common requirements. -Or, you may have defined several types that are supposed to conform to -the same "concept" and you want to verify it. In both cases, you want -the same test logic repeated for different types. +`testing::PrintToStringParamName` is a builtin test suffix generator that +returns the value of `testing::PrintToString(GetParam())`. It does not work for +`std::string` or C strings. -While you can write one `TEST` or `TEST_F` for each type you want to -test (and you may even factor the test logic into a function template -that you invoke from the `TEST`), it's tedious and doesn't scale: -if you want _m_ tests over _n_ types, you'll end up writing _m\*n_ -`TEST`s. +NOTE: test names must be non-empty, unique, and may only contain ASCII +alphanumeric characters. In particular, they [should not contain +underscores](https://g3doc.corp.google.com/third_party/googletest/googletest/g3doc/faq.md#no-underscores). -_Typed tests_ allow you to repeat the same test logic over a list of -types. You only need to write the test logic once, although you must -know the type list when writing typed tests. Here's how you do it: +```c++ +class MyTestCase : public testing::TestWithParam {}; -First, define a fixture class template. It should be parameterized -by a type. Remember to derive it from `::testing::Test`: +TEST_P(MyTestCase, MyTest) +{ + std::cout << "Example Test Param: " << GetParam() << std::endl; +} +INSTANTIATE_TEST_CASE_P(MyGroup, MyTestCase, testing::Range(0, 10), + testing::PrintToStringParamName()); ``` + +## Typed Tests + +Suppose you have multiple implementations of the same interface and want to make +sure that all of them satisfy some common requirements. Or, you may have defined +several types that are supposed to conform to the same "concept" and you want to +verify it. In both cases, you want the same test logic repeated for different +types. + +While you can write one `TEST` or `TEST_F` for each type you want to test (and +you may even factor the test logic into a function template that you invoke from +the `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n` +types, you'll end up writing `m*n` `TEST`s. + +*Typed tests* allow you to repeat the same test logic over a list of types. You +only need to write the test logic once, although you must know the type list +when writing typed tests. Here's how you do it: + +First, define a fixture class template. It should be parameterized by a type. +Remember to derive it from `::testing::Test`: + +```c++ template class FooTest : public ::testing::Test { public: @@ -1330,22 +1546,22 @@ class FooTest : public ::testing::Test { }; ``` -Next, associate a list of types with the test case, which will be -repeated for each type in the list: +Next, associate a list of types with the test case, which will be repeated for +each type in the list: -``` -typedef ::testing::Types MyTypes; +```c++ +using MyTypes = ::testing::Types; TYPED_TEST_CASE(FooTest, MyTypes); ``` -The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse -correctly. Otherwise the compiler will think that each comma in the -type list introduces a new macro argument. +The type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_CASE` +macro to parse correctly. Otherwise the compiler will think that each comma in +the type list introduces a new macro argument. -Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test -for this test case. You can repeat this as many times as you want: +Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this +test case. You can repeat this as many times as you want: -``` +```c++ TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to the special name TypeParam to get the type // parameter. Since we are inside a derived class template, C++ requires @@ -1359,6 +1575,7 @@ TYPED_TEST(FooTest, DoesBlah) { // To refer to typedefs in the fixture, add the 'typename TestFixture::' // prefix. The 'typename' is required to satisfy the compiler. typename TestFixture::List values; + values.push_back(n); ... } @@ -1366,29 +1583,27 @@ TYPED_TEST(FooTest, DoesBlah) { TYPED_TEST(FooTest, HasPropertyA) { ... } ``` -You can see [`samples/sample6_unittest.cc`](../samples/sample6_unittest.cc) for a complete example. +You can see sample6_unittest.cc -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; -since version 1.1.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Mac -# Type-Parameterized Tests # +## Type-Parameterized Tests -_Type-parameterized tests_ are like typed tests, except that they -don't require you to know the list of types ahead of time. Instead, -you can define the test logic first and instantiate it with different -type lists later. You can even instantiate it more than once in the -same program. +*Type-parameterized tests* are like typed tests, except that they don't require +you to know the list of types ahead of time. Instead, you can define the test +logic first and instantiate it with different type lists later. You can even +instantiate it more than once in the same program. -If you are designing an interface or concept, you can define a suite -of type-parameterized tests to verify properties that any valid -implementation of the interface/concept should have. Then, the author -of each implementation can just instantiate the test suite with his -type to verify that it conforms to the requirements, without having to -write similar tests repeatedly. Here's an example: +If you are designing an interface or concept, you can define a suite of +type-parameterized tests to verify properties that any valid implementation of +the interface/concept should have. Then, the author of each implementation can +just instantiate the test suite with their type to verify that it conforms to +the requirements, without having to write similar tests repeatedly. Here's an +example: First, define a fixture class template, as we did with typed tests: -``` +```c++ template class FooTest : public ::testing::Test { ... @@ -1397,17 +1612,14 @@ class FooTest : public ::testing::Test { Next, declare that you will define a type-parameterized test case: -``` +```c++ TYPED_TEST_CASE_P(FooTest); ``` -The `_P` suffix is for "parameterized" or "pattern", whichever you -prefer to think. - -Then, use `TYPED_TEST_P()` to define a type-parameterized test. You -can repeat this as many times as you want: +Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat +this as many times as you want: -``` +```c++ TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; @@ -1418,204 +1630,212 @@ TYPED_TEST_P(FooTest, HasPropertyA) { ... } ``` Now the tricky part: you need to register all test patterns using the -`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. -The first argument of the macro is the test case name; the rest are -the names of the tests in this test case: +`REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. The first +argument of the macro is the test case name; the rest are the names of the tests +in this test case: -``` +```c++ REGISTER_TYPED_TEST_CASE_P(FooTest, DoesBlah, HasPropertyA); ``` -Finally, you are free to instantiate the pattern with the types you -want. If you put the above code in a header file, you can `#include` -it in multiple C++ source files and instantiate it multiple times. +Finally, you are free to instantiate the pattern with the types you want. If you +put the above code in a header file, you can `#include` it in multiple C++ +source files and instantiate it multiple times. -``` +```c++ typedef ::testing::Types MyTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); ``` -To distinguish different instances of the pattern, the first argument -to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be -added to the actual test case name. Remember to pick unique prefixes -for different instances. +To distinguish different instances of the pattern, the first argument to the +`INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be added to the +actual test case name. Remember to pick unique prefixes for different instances. -In the special case where the type list contains only one type, you -can write that type directly without `::testing::Types<...>`, like this: +In the special case where the type list contains only one type, you can write +that type directly without `::testing::Types<...>`, like this: -``` +```c++ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); ``` -You can see `samples/sample6_unittest.cc` for a complete example. +You can see `sample6_unittest.cc` for a complete example. -_Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; -since version 1.1.0. +**Availability**: Linux, Windows (requires MSVC 8.0 or above), Mac -# Testing Private Code # +## Testing Private Code If you change your software's internal implementation, your tests should not -break as long as the change is not observable by users. Therefore, per the -_black-box testing principle_, most of the time you should test your code -through its public interfaces. +break as long as the change is not observable by users. Therefore, **per the +black-box testing principle, most of the time you should test your code through +its public interfaces.** + +**If you still find yourself needing to test internal implementation code, +consider if there's a better design.** The desire to test internal +implementation is often a sign that the class is doing too much. Consider +extracting an implementation class, and testing it. Then use that implementation +class in the original class. + +If you absolutely have to test non-public interface code though, you can. There +are two cases to consider: + +* Static functions ( *not* the same as static member functions!) or unnamed + namespaces, and +* Private or protected class members + +To test them, we use the following special techniques: + +* Both static functions and definitions/declarations in an unnamed namespace + are only visible within the same translation unit. To test them, you can + `#include` the entire `.cc` file being tested in your `*_test.cc` file. + (#including `.cc` files is not a good way to reuse code - you should not do + this in production code!) + + However, a better approach is to move the private code into the + `foo::internal` namespace, where `foo` is the namespace your project + normally uses, and put the private declarations in a `*-internal.h` file. + Your production `.cc` files and your tests are allowed to include this + internal header, but your clients are not. This way, you can fully test your + internal implementation without leaking it to your clients. + +* Private class members are only accessible from within the class or by + friends. To access a class' private members, you can declare your test + fixture as a friend to the class and define accessors in your fixture. Tests + using the fixture can then access the private members of your production + class via the accessors in the fixture. Note that even though your fixture + is a friend to your production class, your tests are not automatically + friends to it, as they are technically defined in sub-classes of the + fixture. + + Another way to test private members is to refactor them into an + implementation class, which is then declared in a `*-internal.h` file. Your + clients aren't allowed to include this header but your tests can. Such is + called the + [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/) + (Private Implementation) idiom. + + Or, you can declare an individual test as a friend of your class by adding + this line in the class body: + + ```c++ + FRIEND_TEST(TestCaseName, TestName); + ``` + + For example, + + ```c++ + // foo.h -If you still find yourself needing to test internal implementation code, -consider if there's a better design that wouldn't require you to do so. If you -absolutely have to test non-public interface code though, you can. There are -two cases to consider: +#include "gtest/gtest_prod.h" - * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and - * Private or protected class members. + class Foo { + ... + private: + FRIEND_TEST(FooTest, BarReturnsZeroOnNull); -## Static Functions ## + int Bar(void* x); + }; -Both static functions and definitions/declarations in an unnamed namespace are -only visible within the same translation unit. To test them, you can `#include` -the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc` -files is not a good way to reuse code - you should not do this in production -code!) + // foo_test.cc + ... + TEST(FooTest, BarReturnsZeroOnNull) { + Foo foo; + EXPECT_EQ(0, foo.Bar(NULL)); // Uses Foo's private member Bar(). + } + ``` -However, a better approach is to move the private code into the -`foo::internal` namespace, where `foo` is the namespace your project normally -uses, and put the private declarations in a `*-internal.h` file. Your -production `.cc` files and your tests are allowed to include this internal -header, but your clients are not. This way, you can fully test your internal -implementation without leaking it to your clients. + Pay special attention when your class is defined in a namespace, as you + should define your test fixtures and tests in the same namespace if you want + them to be friends of your class. For example, if the code to be tested + looks like: -## Private Class Members ## + ```c++ + namespace my_namespace { -Private class members are only accessible from within the class or by friends. -To access a class' private members, you can declare your test fixture as a -friend to the class and define accessors in your fixture. Tests using the -fixture can then access the private members of your production class via the -accessors in the fixture. Note that even though your fixture is a friend to -your production class, your tests are not automatically friends to it, as they -are technically defined in sub-classes of the fixture. + class Foo { + friend class FooTest; + FRIEND_TEST(FooTest, Bar); + FRIEND_TEST(FooTest, Baz); + ... definition of the class Foo ... + }; -Another way to test private members is to refactor them into an implementation -class, which is then declared in a `*-internal.h` file. Your clients aren't -allowed to include this header but your tests can. Such is called the Pimpl -(Private Implementation) idiom. + } // namespace my_namespace + ``` -Or, you can declare an individual test as a friend of your class by adding this -line in the class body: + Your test code should be something like: -``` -FRIEND_TEST(TestCaseName, TestName); -``` + ```c++ + namespace my_namespace { -For example, -``` -// foo.h -#include "gtest/gtest_prod.h" + class FooTest : public ::testing::Test { + protected: + ... + }; -// Defines FRIEND_TEST. -class Foo { - ... - private: - FRIEND_TEST(FooTest, BarReturnsZeroOnNull); - int Bar(void* x); -}; + TEST_F(FooTest, Bar) { ... } + TEST_F(FooTest, Baz) { ... } -// foo_test.cc -... -TEST(FooTest, BarReturnsZeroOnNull) { - Foo foo; - EXPECT_EQ(0, foo.Bar(NULL)); - // Uses Foo's private member Bar(). -} -``` + } // namespace my_namespace + ``` -Pay special attention when your class is defined in a namespace, as you should -define your test fixtures and tests in the same namespace if you want them to -be friends of your class. For example, if the code to be tested looks like: -``` -namespace my_namespace { + ## "Catching" Failures -class Foo { - friend class FooTest; - FRIEND_TEST(FooTest, Bar); - FRIEND_TEST(FooTest, Baz); - ... - definition of the class Foo - ... -}; +If you are building a testing utility on top of googletest, you'll want to test +your utility. What framework would you use to test it? googletest, of course. -} // namespace my_namespace -``` +The challenge is to verify that your testing utility reports failures correctly. +In frameworks that report a failure by throwing an exception, you could catch +the exception and assert on it. But googletest doesn't use exceptions, so how do +we test that a piece of code generates an expected failure? -Your test code should be something like: +gunit-spi.h contains some constructs to do this. After #including this header, +you can use +```c++ + EXPECT_FATAL_FAILURE(statement, substring); ``` -namespace my_namespace { -class FooTest : public ::testing::Test { - protected: - ... -}; -TEST_F(FooTest, Bar) { ... } -TEST_F(FooTest, Baz) { ... } +to assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the +current thread whose message contains the given `substring`, or use -} // namespace my_namespace +```c++ + EXPECT_NONFATAL_FAILURE(statement, substring); ``` -# Catching Failures # - -If you are building a testing utility on top of Google Test, you'll -want to test your utility. What framework would you use to test it? -Google Test, of course. - -The challenge is to verify that your testing utility reports failures -correctly. In frameworks that report a failure by throwing an -exception, you could catch the exception and assert on it. But Google -Test doesn't use exceptions, so how do we test that a piece of code -generates an expected failure? - -`"gtest/gtest-spi.h"` contains some constructs to do this. After -`#include`ing this header, you can use - -| `EXPECT_FATAL_FAILURE(`_statement, substring_`);` | -|:--------------------------------------------------| +if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. -to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure -whose message contains the given _substring_, or use +Only failures in the current thread are checked to determine the result of this +type of expectations. If `statement` creates new threads, failures in these +threads are also ignored. If you want to catch failures in other threads as +well, use one of the following macros instead: -| `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` | -|:-----------------------------------------------------| +```c++ + EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring); + EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring); +``` -if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. +NOTE: Assertions from multiple threads are currently not supported on Windows. For technical reasons, there are some caveats: - 1. You cannot stream a failure message to either macro. - 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object. - 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value. +1. You cannot stream a failure message to either macro. + +1. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference + local non-static variables or non-static members of `this` object. -_Note:_ Google Test is designed with threads in mind. Once the -synchronization primitives in `"gtest/internal/gtest-port.h"` have -been implemented, Google Test will become thread-safe, meaning that -you can then use assertions in multiple threads concurrently. Before -that, however, Google Test only supports single-threaded usage. Once -thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()` -will capture failures in the current thread only. If _statement_ -creates new threads, failures in these threads will be ignored. If -you want to capture failures from all threads instead, you should use -the following macros: +1. `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()()` cannot return a + value. -| `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | -|:-----------------------------------------------------------------| -| `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | -# Getting the Current Test's Name # +## Getting the Current Test's Name Sometimes a function may need to know the name of the currently running test. For example, you may be using the `SetUp()` method of your test fixture to set the golden file name based on which test is running. The `::testing::TestInfo` class has this information: -``` +```c++ namespace testing { class TestInfo { @@ -1628,65 +1848,68 @@ class TestInfo { const char* name() const; }; -} // namespace testing +} ``` - -> To obtain a `TestInfo` object for the currently running test, call +To obtain a `TestInfo` object for the currently running test, call `current_test_info()` on the `UnitTest` singleton object: -``` -// Gets information about the currently running test. -// Do NOT delete the returned object - it's managed by the UnitTest class. -const ::testing::TestInfo* const test_info = - ::testing::UnitTest::GetInstance()->current_test_info(); -printf("We are in test %s of test case %s.\n", - test_info->name(), test_info->test_case_name()); +```c++ + // Gets information about the currently running test. + // Do NOT delete the returned object - it's managed by the UnitTest class. + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + + + printf("We are in test %s of test case %s.\n", + test_info->name(), + test_info->test_case_name()); ``` `current_test_info()` returns a null pointer if no test is running. In -particular, you cannot find the test case name in `SetUpTestCase()`, -`TearDownTestCase()` (where you know the test case name implicitly), or +particular, you cannot find the test case name in `TestCaseSetUp()`, +`TestCaseTearDown()` (where you know the test case name implicitly), or functions called from them. -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -# Extending Google Test by Handling Test Events # +## Extending googletest by Handling Test Events -Google Test provides an event listener API to let you receive -notifications about the progress of a test program and test -failures. The events you can listen to include the start and end of -the test program, a test case, or a test method, among others. You may -use this API to augment or replace the standard console output, -replace the XML output, or provide a completely different form of -output, such as a GUI or a database. You can also use test events as +googletest provides an **event listener API** to let you receive notifications +about the progress of a test program and test failures. The events you can +listen to include the start and end of the test program, a test case, or a test +method, among others. You may use this API to augment or replace the standard +console output, replace the XML output, or provide a completely different form +of output, such as a GUI or a database. You can also use test events as checkpoints to implement a resource leak checker, for example. -_Availability:_ Linux, Windows, Mac; since v1.4.0. +**Availability**: Linux, Windows, Mac. -## Defining Event Listeners ## +### Defining Event Listeners -To define a event listener, you subclass either -[testing::TestEventListener](../include/gtest/gtest.h#L991) -or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L1044). -The former is an (abstract) interface, where each pure virtual method
-can be overridden to handle a test event
(For example, when a test -starts, the `OnTestStart()` method will be called.). The latter provides -an empty implementation of all methods in the interface, such that a -subclass only needs to override the methods it cares about. +To define a event listener, you subclass either testing::TestEventListener or +testing::EmptyTestEventListener The former is an (abstract) interface, where +*each pure virtual method can be overridden to handle a test event* (For +example, when a test starts, the `OnTestStart()` method will be called.). The +latter provides an empty implementation of all methods in the interface, such +that a subclass only needs to override the methods it cares about. -When an event is fired, its context is passed to the handler function -as an argument. The following argument types are used: - * [UnitTest](../include/gtest/gtest.h#L1151) reflects the state of the entire test program, - * [TestCase](../include/gtest/gtest.h#L778) has information about a test case, which can contain one or more tests, - * [TestInfo](../include/gtest/gtest.h#L644) contains the state of a test, and - * [TestPartResult](../include/gtest/gtest-test-part.h#L47) represents the result of a test assertion. +When an event is fired, its context is passed to the handler function as an +argument. The following argument types are used: -An event handler function can examine the argument it receives to find -out interesting information about the event and the test program's -state. Here's an example: +* UnitTest reflects the state of the entire test program, +* TestCase has information about a test case, which can contain one or more + tests, +* TestInfo contains the state of a test, and +* TestPartResult represents the result of a test assertion. -``` +An event handler function can examine the argument it receives to find out +interesting information about the event and the test program's state. + +Here's an example: + +```c++ class MinimalistPrinter : public ::testing::EmptyTestEventListener { // Called before a test starts. virtual void OnTestStart(const ::testing::TestInfo& test_info) { @@ -1694,9 +1917,8 @@ state. Here's an example: test_info.test_case_name(), test_info.name()); } - // Called after a failed assertion or a SUCCEED() invocation. - virtual void OnTestPartResult( - const ::testing::TestPartResult& test_part_result) { + // Called after a failed assertion or a SUCCESS(). + virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) { printf("%s in %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", test_part_result.file_name(), @@ -1712,105 +1934,88 @@ state. Here's an example: }; ``` -## Using Event Listeners ## +### Using Event Listeners -To use the event listener you have defined, add an instance of it to -the Google Test event listener list (represented by class -[TestEventListeners](../include/gtest/gtest.h#L1064) -- note the "s" at the end of the name) in your -`main()` function, before calling `RUN_ALL_TESTS()`: -``` +To use the event listener you have defined, add an instance of it to the +googletest event listener list (represented by class TestEventListeners - note +the "s" at the end of the name) in your `main()` function, before calling +`RUN_ALL_TESTS()`: + +```c++ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); // Gets hold of the event listener list. ::testing::TestEventListeners& listeners = - ::testing::UnitTest::GetInstance()->listeners(); - // Adds a listener to the end. Google Test takes the ownership. + ::testing::UnitTest::GetInstance()->listeners(); + // Adds a listener to the end. googletest takes the ownership. listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); } ``` -There's only one problem: the default test result printer is still in -effect, so its output will mingle with the output from your minimalist -printer. To suppress the default printer, just release it from the -event listener list and delete it. You can do so by adding one line: -``` +There's only one problem: the default test result printer is still in effect, so +its output will mingle with the output from your minimalist printer. To suppress +the default printer, just release it from the event listener list and delete it. +You can do so by adding one line: + +```c++ ... delete listeners.Release(listeners.default_result_printer()); listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); ``` -Now, sit back and enjoy a completely different output from your -tests. For more details, you can read this -[sample](../samples/sample9_unittest.cc). +Now, sit back and enjoy a completely different output from your tests. For more +details, you can read this sample9_unittest.cc -You may append more than one listener to the list. When an `On*Start()` -or `OnTestPartResult()` event is fired, the listeners will receive it in -the order they appear in the list (since new listeners are added to -the end of the list, the default text printer and the default XML -generator will receive the event first). An `On*End()` event will be -received by the listeners in the _reverse_ order. This allows output by -listeners added later to be framed by output from listeners added -earlier. +You may append more than one listener to the list. When an `On*Start()` or +`OnTestPartResult()` event is fired, the listeners will receive it in the order +they appear in the list (since new listeners are added to the end of the list, +the default text printer and the default XML generator will receive the event +first). An `On*End()` event will be received by the listeners in the *reverse* +order. This allows output by listeners added later to be framed by output from +listeners added earlier. -## Generating Failures in Listeners ## +### Generating Failures in Listeners -You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, -`FAIL()`, etc) when processing an event. There are some restrictions: +You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) +when processing an event. There are some restrictions: - 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively). - 1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure. +1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will + cause `OnTestPartResult()` to be called recursively). +1. A listener that handles `OnTestPartResult()` is not allowed to generate any + failure. -When you add listeners to the listener list, you should put listeners -that handle `OnTestPartResult()` _before_ listeners that can generate -failures. This ensures that failures generated by the latter are -attributed to the right test by the former. +When you add listeners to the listener list, you should put listeners that +handle `OnTestPartResult()` *before* listeners that can generate failures. This +ensures that failures generated by the latter are attributed to the right test +by the former. -We have a sample of failure-raising listener -[here](../samples/sample10_unittest.cc). +We have a sample of failure-raising listener sample10_unittest.cc -# Running Test Programs: Advanced Options # +## Running Test Programs: Advanced Options -Google Test test programs are ordinary executables. Once built, you can run -them directly and affect their behavior via the following environment variables +googletest test programs are ordinary executables. Once built, you can run them +directly and affect their behavior via the following environment variables and/or command line flags. For the flags to work, your programs must call `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. -To see a list of supported flags and their usage, please run your test -program with the `--help` flag. You can also use `-h`, `-?`, or `/?` -for short. This feature is added in version 1.3.0. - -If an option is specified both by an environment variable and by a -flag, the latter takes precedence. Most of the options can also be -set/read in code: to access the value of command line flag -`--gtest_foo`, write `::testing::GTEST_FLAG(foo)`. A common pattern is -to set the value of a flag before calling `::testing::InitGoogleTest()` -to change the default value of the flag: -``` -int main(int argc, char** argv) { - // Disables elapsed time by default. - ::testing::GTEST_FLAG(print_time) = false; +To see a list of supported flags and their usage, please run your test program +with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. - // This allows the user to override the flag on the command line. - ::testing::InitGoogleTest(&argc, argv); +If an option is specified both by an environment variable and by a flag, the +latter takes precedence. - return RUN_ALL_TESTS(); -} -``` +### Selecting Tests -## Selecting Tests ## - -This section shows various options for choosing which tests to run. - -### Listing Test Names ### +#### Listing Test Names Sometimes it is necessary to list the available tests in a program before running them so that a filter may be applied if needed. Including the flag `--gtest_list_tests` overrides all other flags and lists tests in the following format: -``` + +```none TestCase1. TestName1 TestName2 @@ -1821,39 +2026,44 @@ TestCase2. None of the tests listed are actually run if the flag is provided. There is no corresponding environment variable for this flag. -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Running a Subset of the Tests ### +#### Running a Subset of the Tests -By default, a Google Test program runs all tests the user has defined. -Sometimes, you want to run only a subset of the tests (e.g. for debugging or -quickly verifying a change). If you set the `GTEST_FILTER` environment variable -or the `--gtest_filter` flag to a filter string, Google Test will only run the -tests whose full names (in the form of `TestCaseName.TestName`) match the -filter. +By default, a googletest program runs all tests the user has defined. Sometimes, +you want to run only a subset of the tests (e.g. for debugging or quickly +verifying a change). If you set the `GTEST_FILTER` environment variable or the +`--gtest_filter` flag to a filter string, googletest will only run the tests +whose full names (in the form of `TestCaseName.TestName`) match the filter. The format of a filter is a '`:`'-separated list of wildcard patterns (called -the positive patterns) optionally followed by a '`-`' and another -'`:`'-separated pattern list (called the negative patterns). A test matches the -filter if and only if it matches any of the positive patterns but does not +the *positive patterns*) optionally followed by a '`-`' and another +'`:`'-separated pattern list (called the *negative patterns*). A test matches +the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns. A pattern may contain `'*'` (matches any string) or `'?'` (matches any single -character). For convenience, the filter `'*-NegativePatterns'` can be also -written as `'-NegativePatterns'`. - -For example: +character). For convenience, the filter - * `./foo_test` Has no flag, and thus runs all its tests. - * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. - * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`. - * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`. - * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. - * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`. +`'*-NegativePatterns'` can be also written as `'-NegativePatterns'`. -_Availability:_ Linux, Windows, Mac. +For example: -### Temporarily Disabling Tests ### +* `./foo_test` Has no flag, and thus runs all its tests. +* `./foo_test --gtest_filter=*` Also runs everything, due to the single + match-everything `*` value. +* `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest` + . +* `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full + name contains either `"Null"` or `"Constructor"` . +* `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. +* `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test + case `FooTest` except `FooTest.Bar`. +* `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs + everything in test case `FooTest` except `FooTest.Bar` and everything in + test case `BarTest` except `BarTest.Foo`. + +#### Temporarily Disabling Tests If you have a broken test that you cannot fix right away, you can add the `DISABLED_` prefix to its name. This will exclude it from execution. This is @@ -1864,10 +2074,10 @@ If you need to disable all tests in a test case, you can either add `DISABLED_` to the front of the name of each test, or alternatively add it to the front of the test case name. -For example, the following tests won't be run by Google Test, even though they +For example, the following tests won't be run by googletest, even though they will still be compiled: -``` +```c++ // Tests that Foo does Abc. TEST(FooTest, DISABLED_DoesAbc) { ... } @@ -1877,140 +2087,164 @@ class DISABLED_BarTest : public ::testing::Test { ... }; TEST_F(DISABLED_BarTest, DoesXyz) { ... } ``` -_Note:_ This feature should only be used for temporary pain-relief. You still -have to fix the disabled tests at a later date. As a reminder, Google Test will -print a banner warning you if a test program contains any disabled tests. +NOTE: This feature should only be used for temporary pain-relief. You still have +to fix the disabled tests at a later date. As a reminder, googletest will print +a banner warning you if a test program contains any disabled tests. -_Tip:_ You can easily count the number of disabled tests you have -using `grep`. This number can be used as a metric for improving your -test quality. +TIP: You can easily count the number of disabled tests you have using `gsearch` +and/or `grep`. This number can be used as a metric for improving your test +quality. -_Availability:_ Linux, Windows, Mac. +**Availability**: Linux, Windows, Mac. -### Temporarily Enabling Disabled Tests ### +#### Temporarily Enabling Disabled Tests -To include [disabled tests](#temporarily-disabling-tests) in test -execution, just invoke the test program with the -`--gtest_also_run_disabled_tests` flag or set the -`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other -than `0`. You can combine this with the -[--gtest\_filter](#running-a-subset-of-the-tests) flag to further select -which disabled tests to run. +To include disabled tests in test execution, just invoke the test program with +the `--gtest_also_run_disabled_tests` flag or set the +`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. +You can combine this with the `--gtest_filter` flag to further select which +disabled tests to run. -_Availability:_ Linux, Windows, Mac; since version 1.3.0. +**Availability**: Linux, Windows, Mac. -## Repeating the Tests ## +### Repeating the Tests Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it will fail only 1% of the time, making it rather hard to reproduce the bug under a debugger. This can be a major source of frustration. -The `--gtest_repeat` flag allows you to repeat all (or selected) test methods -in a program many times. Hopefully, a flaky test will eventually fail and give -you a chance to debug. Here's how to use it: +The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in +a program many times. Hopefully, a flaky test will eventually fail and give you +a chance to debug. Here's how to use it: -| `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. | -|:---------------------------------|:--------------------------------------------------------| -| `$ foo_test --gtest_repeat=-1` | A negative count means repeating forever. | -| `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. | -| `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. | +```none +$ foo_test --gtest_repeat=1000 +Repeat foo_test 1000 times and don't stop at failures. -If your test program contains global set-up/tear-down code registered -using `AddGlobalTestEnvironment()`, it will be repeated in each -iteration as well, as the flakiness may be in it. You can also specify -the repeat count by setting the `GTEST_REPEAT` environment variable. +$ foo_test --gtest_repeat=-1 +A negative count means repeating forever. -_Availability:_ Linux, Windows, Mac. +$ foo_test --gtest_repeat=1000 --gtest_break_on_failure +Repeat foo_test 1000 times, stopping at the first failure. This +is especially useful when running under a debugger: when the test +fails, it will drop into the debugger and you can then inspect +variables and stacks. -## Shuffling the Tests ## +$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.* +Repeat the tests whose name matches the filter 1000 times. +``` + +If your test program contains [global set-up/tear-down](#GlobalSetUp) code, it +will be repeated in each iteration as well, as the flakiness may be in it. You +can also specify the repeat count by setting the `GTEST_REPEAT` environment +variable. + +**Availability**: Linux, Windows, Mac. + +### Shuffling the Tests You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` -environment variable to `1`) to run the tests in a program in a random -order. This helps to reveal bad dependencies between tests. - -By default, Google Test uses a random seed calculated from the current -time. Therefore you'll get a different order every time. The console -output includes the random seed value, such that you can reproduce an -order-related test failure later. To specify the random seed -explicitly, use the `--gtest_random_seed=SEED` flag (or set the -`GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer -between 0 and 99999. The seed value 0 is special: it tells Google Test -to do the default behavior of calculating the seed from the current +environment variable to `1`) to run the tests in a program in a random order. +This helps to reveal bad dependencies between tests. + +By default, googletest uses a random seed calculated from the current time. +Therefore you'll get a different order every time. The console output includes +the random seed value, such that you can reproduce an order-related test failure +later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` +flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an +integer in the range [0, 99999]. The seed value 0 is special: it tells +googletest to do the default behavior of calculating the seed from the current time. -If you combine this with `--gtest_repeat=N`, Google Test will pick a -different random seed and re-shuffle the tests in each iteration. +If you combine this with `--gtest_repeat=N`, googletest will pick a different +random seed and re-shuffle the tests in each iteration. + +**Availability**: Linux, Windows, Mac. -_Availability:_ Linux, Windows, Mac; since v1.4.0. +### Controlling Test Output -## Controlling Test Output ## +#### Colored Terminal Output -This section teaches how to tweak the way test results are reported. +googletest can use colors in its terminal output to make it easier to spot the +important information: -### Colored Terminal Output ### +... +[----------] 1 test from FooTest +[ RUN ] FooTest.DoesAbc +[ OK ] FooTest.DoesAbc +[----------] 2 tests from BarTest +[ RUN ] BarTest.HasXyzProperty +[ OK ] BarTest.HasXyzProperty +[ RUN ] BarTest.ReturnsTrueOnSuccess +... some error messages ... +[ FAILED ] BarTest.ReturnsTrueOnSuccess +... +[==========] 30 tests from 14 test cases ran. +[ PASSED ] 28 tests. +[ FAILED ] 2 tests, listed below: +[ FAILED ] BarTest.ReturnsTrueOnSuccess +[ FAILED ] AnotherTest.DoesXyz -Google Test can use colors in its terminal output to make it easier to spot -the separation between tests, and whether tests passed. + 2 FAILED TESTS -You can set the GTEST\_COLOR environment variable or set the `--gtest_color` +You can set the `GTEST_COLOR` environment variable or the `--gtest_color` command line flag to `yes`, `no`, or `auto` (the default) to enable colors, -disable colors, or let Google Test decide. When the value is `auto`, Google -Test 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`. +disable colors, or let googletest decide. When the value is `auto`, googletest +will use colors if and only if the output goes to a terminal and (on non-Windows +platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. -_Availability:_ Linux, Windows, Mac. +> +> **Availability**: Linux, Windows, Mac. -### Suppressing the Elapsed Time ### +#### Suppressing the Elapsed Time -By default, Google Test prints the time it takes to run each test. To -suppress that, run the test program with the `--gtest_print_time=0` -command line flag. Setting the `GTEST_PRINT_TIME` environment -variable to `0` has the same effect. - -_Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, -the default behavior is that the elapsed time is **not** printed.) +By default, googletest prints the time it takes to run each test. To disable +that, run the test program with the `--gtest_print_time=0` command line flag, or +set the GTEST_PRINT_TIME environment variable to `0`. **Availability**: Linux, Windows, Mac. #### Suppressing UTF-8 Text Output -In case of assertion failures, gUnit prints expected and actual values of type -`string` both as hex-encoded strings as well as in readable UTF-8 text if they -contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 text -because, for example, you don't have an UTF-8 compatible output medium, run the -test program with `--gunit_print_utf8=0` or set the `GUNIT_PRINT_UTF8` +In case of assertion failures, googletest prints expected and actual values of +type `string` both as hex-encoded strings as well as in readable UTF-8 text if +they contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8 +text because, for example, you don't have an UTF-8 compatible output medium, run +the test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8` environment variable to `0`. -### Generating an XML Report ### +**Availability**: Linux, Windows, Mac. + -Google Test 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. +#### Generating an XML Report + +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. 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 -create the file at the given location. You can also just use the string -`"xml"`, in which case the output can be found in the `test_detail.xml` file in -the current directory. +`--gtest_output` flag to the string `"xml:path_to_output_file"`, which will +create the file at the given location. You can also just use the string `"xml"`, +in which case the output can be found in the `test_detail.xml` file in the +current directory. If you specify a directory (for example, `"xml:output/directory/"` on Linux or -`"xml:output\directory\"` on Windows), Google Test will create the XML file in +`"xml:output\directory\"` on Windows), googletest will create the XML file in that directory, named after the test executable (e.g. `foo_test.xml` for test program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left -over from a previous run), Google Test will pick a different name (e.g. +over from a previous run), googletest will pick a different name (e.g. `foo_test_1.xml`) to avoid overwriting it. -The report uses the format described here. It is based on the -`junitreport` Ant task and can be parsed by popular continuous build -systems like [Hudson](https://hudson.dev.java.net/). Since that format -was originally intended for Java, a little interpretation is required -to make it apply to Google Test tests, as shown here: -``` +The report is based on the `junitreport` Ant task. Since that format was +originally intended for Java, a little interpretation is required to make it +apply to googletest tests, as shown here: + +```xml - + @@ -2019,13 +2253,13 @@ to make it apply to Google Test tests, as shown here: ``` - * The root `` element corresponds to the entire test program. - * `` elements correspond to Google Test test cases. - * `` elements correspond to Google Test test functions. +* The root `` element corresponds to the entire test program. +* `` elements correspond to googletest test cases. +* `` elements correspond to googletest test functions. For instance, the following program -``` +```c++ TEST(MathTest, Addition) { ... } TEST(MathTest, Subtraction) { ... } TEST(LogicTest, NonContradiction) { ... } @@ -2033,19 +2267,19 @@ TEST(LogicTest, NonContradiction) { ... } could generate this report: -``` +```xml - - - - - + + + + ... + ... - + - - + + @@ -2053,18 +2287,26 @@ could generate this report: Things to note: - * The `tests` attribute of a `` or `` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed. - * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds. - * Each `` element corresponds to a single failed Google Test assertion. - * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts. +* The `tests` attribute of a `` or `` element tells how + many test functions the googletest program or test case contains, while the + `failures` attribute tells how many of them failed. + +* The `time` attribute expresses the duration of the test, test case, or + entire test program in seconds. + +* The `timestamp` attribute records the local date and time of the test + execution. -_Availability:_ Linux, Windows, Mac. +* Each `` element corresponds to a single failed googletest + assertion. -#### Generating an JSON Report {#JsonReport} +**Availability**: Linux, Windows, Mac. + +#### Generating an JSON Report -gUnit can also emit a JSON report as an alternative format to XML. To generate -the JSON report, set the `GUNIT_OUTPUT` environment variable or the -`--gunit_output` flag to the string `"json:path_to_output_file"`, which will +googletest can also emit a JSON report as an alternative format to XML. To +generate the JSON report, set the `GTEST_OUTPUT` environment variable or the +`--gtest_output` flag to the string `"json:path_to_output_file"`, which will create the file at the given location. You can also just use the string `"json"`, in which case the output can be found in the `test_detail.json` file in the current directory. @@ -2139,8 +2381,8 @@ The report format conforms to the following JSON Schema: } ``` -The report uses the format that conforms to the following Proto3 using the -[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): +The report uses the format that conforms to the following Proto3 using the [JSON +encoding](https://developers.google.com/protocol-buffers/docs/proto3#json): ```proto syntax = "proto3"; @@ -2261,156 +2503,34 @@ IMPORTANT: The exact format of the JSON document is subject to change. **Availability**: Linux, Windows, Mac. -## Controlling How Failures Are Reported ## +### Controlling How Failures Are Reported -### Turning Assertion Failures into Break-Points ### +#### Turning Assertion Failures into Break-Points When running test programs under a debugger, it's very convenient if the debugger can catch an assertion failure and automatically drop into interactive -mode. Google Test's _break-on-failure_ mode supports this behavior. +mode. googletest's *break-on-failure* mode supports this behavior. To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value other than `0` . Alternatively, you can use the `--gtest_break_on_failure` command line flag. -_Availability:_ Linux, Windows, Mac. - -### Disabling Catching Test-Thrown Exceptions ### - -Google Test can be used either with or without exceptions enabled. If -a test throws a C++ exception or (on Windows) a structured exception -(SEH), by default Google Test catches it, reports it as a test -failure, and continues with the next test method. This maximizes the -coverage of a test run. Also, on Windows an uncaught exception will -cause a pop-up window, so catching the exceptions allows you to run -the tests automatically. - -When debugging the test failures, however, you may instead want the -exceptions to be handled by the debugger, such that you can examine -the call stack when an exception is thrown. To achieve that, set the -`GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the -`--gtest_catch_exceptions=0` flag when running the tests. - **Availability**: Linux, Windows, Mac. -### Letting Another Testing Framework Drive ### - -If you work on a project that has already been using another testing -framework and is not ready to completely switch to Google Test yet, -you can get much of Google Test's benefit by using its assertions in -your existing tests. Just change your `main()` function to look -like: - -``` -#include "gtest/gtest.h" - -int main(int argc, char** argv) { - ::testing::GTEST_FLAG(throw_on_failure) = true; - // Important: Google Test must be initialized. - ::testing::InitGoogleTest(&argc, argv); - - ... whatever your existing testing framework requires ... -} -``` - -With that, you can use Google Test assertions in addition to the -native assertions your testing framework provides, for example: - -``` -void TestFooDoesBar() { - Foo foo; - EXPECT_LE(foo.Bar(1), 100); // A Google Test assertion. - CPPUNIT_ASSERT(foo.IsEmpty()); // A native assertion. -} -``` - -If a Google Test assertion fails, it will print an error message and -throw an exception, which will be treated as a failure by your host -testing framework. If you compile your code with exceptions disabled, -a failed Google Test assertion will instead exit your program with a -non-zero code, which will also signal a test failure to your test -runner. - -If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in -your `main()`, you can alternatively enable this feature by specifying -the `--gtest_throw_on_failure` flag on the command-line or setting the -`GTEST_THROW_ON_FAILURE` environment variable to a non-zero value. - -Death tests are _not_ supported when other test framework is used to organize tests. - -_Availability:_ Linux, Windows, Mac; since v1.3.0. - -## Distributing Test Functions to Multiple Machines ## - -If you have more than one machine you can use to run a test program, -you might want to run the test functions in parallel and get the -result faster. We call this technique _sharding_, where each machine -is called a _shard_. - -Google Test is compatible with test sharding. To take advantage of -this feature, your test runner (not part of Google Test) needs to do -the following: +#### Disabling Catching Test-Thrown Exceptions - 1. Allocate a number of machines (shards) to run the tests. - 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards. It must be the same for all shards. - 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. - 1. Run the same test program on all shards. When Google Test sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once. - 1. Wait for all shards to finish, then collect and report the results. +googletest can be used either with or without exceptions enabled. If a test +throws a C++ exception or (on Windows) a structured exception (SEH), by default +googletest catches it, reports it as a test failure, and continues with the next +test method. This maximizes the coverage of a test run. Also, on Windows an +uncaught exception will cause a pop-up window, so catching the exceptions allows +you to run the tests automatically. -Your project may have tests that were written without Google Test and -thus don't understand this protocol. In order for your test runner to -figure out which test supports sharding, it can set the environment -variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path. If a -test program supports sharding, it will create this file to -acknowledge the fact (the actual contents of the file are not -important at this time; although we may stick some useful information -in it in the future.); otherwise it will not create it. +When debugging the test failures, however, you may instead want the exceptions +to be handled by the debugger, such that you can examine the call stack when an +exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` +environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when +running the tests. -Here's an example to make it clear. Suppose you have a test program -`foo_test` that contains the following 5 test functions: -``` -TEST(A, V) -TEST(A, W) -TEST(B, X) -TEST(B, Y) -TEST(B, Z) -``` -and you have 3 machines at your disposal. To run the test functions in -parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and -set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. -Then you would run the same `foo_test` on each machine. - -Google Test reserves the right to change how the work is distributed -across the shards, but here's one possible scenario: - - * Machine #0 runs `A.V` and `B.X`. - * Machine #1 runs `A.W` and `B.Y`. - * Machine #2 runs `B.Z`. - -_Availability:_ Linux, Windows, Mac; since version 1.3.0. - -# Fusing Google Test Source Files # - -Google Test's implementation consists of ~30 files (excluding its own -tests). Sometimes you may want them to be packaged up in two files (a -`.h` and a `.cc`) instead, such that you can easily copy them to a new -machine and start hacking there. For this we provide an experimental -Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0). -Assuming you have Python 2.4 or above installed on your machine, just -go to that directory and run -``` -python fuse_gtest_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h` and `gtest/gtest-all.cc` in it. These files contain -everything you need to use Google Test. Just copy them to anywhere -you want and you are ready to write tests. You can use the -[scripts/test/Makefile](../scripts/test/Makefile) -file as an example on how to compile your tests against them. - -# Where to Go from Here # +**Availability**: Linux, Windows, Mac. -Congratulations! You've now learned more advanced Google Test tools and are -ready to tackle more complex testing tasks. If you want to dive even deeper, you -can read the [Frequently-Asked Questions](faq.md). diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index 1e2c341..dad2836 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -1,337 +1,203 @@ +# Googletest FAQ -If you cannot find the answer to your question here, and you have read -[Primer](primer.md) and [AdvancedGuide](advanced.md), send it to -googletestframework@googlegroups.com. +## Why should test case names and test names not contain underscore? -## Why should I use Google Test instead of my favorite C++ testing framework? ## +Underscore (`_`) is special, as C++ reserves the following to be used by the +compiler and the standard library: -First, let us say clearly that we don't want to get into the debate of -which C++ testing framework is **the best**. There exist many fine -frameworks for writing C++ tests, and we have tremendous respect for -the developers and users of them. We don't think there is (or will -be) a single best framework - you have to pick the right tool for the -particular task you are tackling. +1. any identifier that starts with an `_` followed by an upper-case letter, and +1. any identifier that contains two consecutive underscores (i.e. `__`) + *anywhere* in its name. -We created Google Test because we couldn't find the right combination -of features and conveniences in an existing framework to satisfy _our_ -needs. The following is a list of things that _we_ like about Google -Test. We don't claim them to be unique to Google Test - rather, the -combination of them makes Google Test the choice for us. We hope this -list can help you decide whether it is for you too. - - * Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc. As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems. - * Nonfatal assertions (`EXPECT_*`) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle. - * It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. `ASSERT_EQ(5, Foo(i)) << " where i = " << i;`. It doesn't require a new set of macros or special functions. - * Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them. - * Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions. - * `SCOPED_TRACE` helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop. - * You can decide which tests to run using name patterns. This saves time when you want to quickly reproduce a test failure. - * Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson. - * Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like [global test environments](advanced.md#global-set-up-and-tear-down) and tests parameterized by [values](advanced.md#value-parameterized-tests) or [types](docs/advanced.md#typed-tests), Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: - * expand your testing vocabulary by defining [custom predicates](advanced.md#predicate-assertions-for-better-error-messages), - * teach Google Test how to [print your types](advanced.md#teaching-google-test-how-to-print-your-values), - * define your own testing macros or utilities and verify them using Google Test's [Service Provider Interface](advanced.md#catching-failures), and - * reflect on the test cases or change the test output format by intercepting the [test events](advanced.md#extending-google-test-by-handling-test-events). - -## I'm getting warnings when compiling Google Test. Would you fix them? ## - -We strive to minimize compiler warnings Google Test generates. Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS. - -Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment: - - * You may be using a different compiler as we use, or a different version of the same compiler. We cannot possibly test for all compilers. - * You may be compiling on a different platform as we do. - * Your project may be using different compiler flags as we do. - -It is not always possible to make Google Test warning-free for everyone. Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex. - -If you see warnings when compiling Google Test, we suggest that you use the `-isystem` flag (assuming your are using GCC) to mark Google Test headers as system headers. That'll suppress warnings from Google Test headers. - -## Why should not test case names and test names contain underscore? ## - -Underscore (`_`) is special, as C++ reserves the following to be used by -the compiler and the standard library: - - 1. any identifier that starts with an `_` followed by an upper-case letter, and - 1. any identifier that contains two consecutive underscores (i.e. `__`) _anywhere_ in its name. - -User code is _prohibited_ from using such identifiers. +User code is *prohibited* from using such identifiers. Now let's look at what this means for `TEST` and `TEST_F`. Currently `TEST(TestCaseName, TestName)` generates a class named -`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` +`TestCaseName_TestName_Test`. What happens if `TestCaseName` or `TestName` contains `_`? - 1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus invalid. - 1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get `Foo__TestName_Test`, which is invalid. - 1. If `TestName` starts with an `_` (say, `_Bar`), we get `TestCaseName__Bar_Test`, which is invalid. - 1. If `TestName` ends with an `_` (say, `Bar_`), we get `TestCaseName_Bar__Test`, which is invalid. +1. If `TestCaseName` starts with an `_` followed by an upper-case letter (say, + `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus + invalid. +1. If `TestCaseName` ends with an `_` (say, `Foo_`), we get + `Foo__TestName_Test`, which is invalid. +1. If `TestName` starts with an `_` (say, `_Bar`), we get + `TestCaseName__Bar_Test`, which is invalid. +1. If `TestName` ends with an `_` (say, `Bar_`), we get + `TestCaseName_Bar__Test`, which is invalid. + +So clearly `TestCaseName` and `TestName` cannot start or end with `_` (Actually, +`TestCaseName` can start with `_` -- as long as the `_` isn't followed by an +upper-case letter. But that's getting complicated. So for simplicity we just say +that it cannot start with `_`.). -So clearly `TestCaseName` and `TestName` cannot start or end with `_` -(Actually, `TestCaseName` can start with `_` -- as long as the `_` isn't -followed by an upper-case letter. But that's getting complicated. So -for simplicity we just say that it cannot start with `_`.). +It may seem fine for `TestCaseName` and `TestName` to contain `_` in the middle. +However, consider this: -It may seem fine for `TestCaseName` and `TestName` to contain `_` in the -middle. However, consider this: ```c++ TEST(Time, Flies_Like_An_Arrow) { ... } TEST(Time_Flies, Like_An_Arrow) { ... } ``` Now, the two `TEST`s will both generate the same class -(`Time_Files_Like_An_Arrow_Test`). That's not good. - -So for simplicity, we just ask the users to avoid `_` in `TestCaseName` -and `TestName`. The rule is more constraining than necessary, but it's -simple and easy to remember. It also gives Google Test some wiggle -room in case its implementation needs to change in the future. - -If you violate the rule, there may not be immediately consequences, -but your test may (just may) break with a new compiler (or a new -version of the compiler you are using) or with a new version of Google -Test. Therefore it's best to follow the rule. - -## Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? ## - -In the early days, we said that you could install -compiled Google Test libraries on `*`nix systems using `make install`. -Then every user of your machine can write tests without -recompiling Google Test. - -This seemed like a good idea, but it has a -got-cha: every user needs to compile their tests using the _same_ compiler -flags used to compile the installed Google Test libraries; otherwise -they may run into undefined behaviors (i.e. the tests can behave -strangely and may even crash for no obvious reasons). - -Why? Because C++ has this thing called the One-Definition Rule: if -two C++ source files contain different definitions of the same -class/function/variable, and you link them together, you violate the -rule. The linker may or may not catch the error (in many cases it's -not required by the C++ standard to catch the violation). If it -doesn't, you get strange run-time behaviors that are unexpected and -hard to debug. - -If you compile Google Test and your test code using different compiler -flags, they may see different definitions of the same -class/function/variable (e.g. due to the use of `#if` in Google Test). -Therefore, for your sanity, we recommend to avoid installing pre-compiled -Google Test libraries. Instead, each project should compile -Google Test itself such that it can be sure that the same flags are -used for both Google Test and the tests. - -## How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? ## - -(Answered by Trevor Robinson) - -Load the supplied Visual Studio solution file, either `msvc\gtest-md.sln` or -`msvc\gtest.sln`. Go through the migration wizard to migrate the -solution and project files to Visual Studio 2008. Select -`Configuration Manager...` from the `Build` menu. Select `` from -the `Active solution platform` dropdown. Select `x64` from the new -platform dropdown, leave `Copy settings from` set to `Win32` and -`Create new project platforms` checked, then click `OK`. You now have -`Win32` and `x64` platform configurations, selectable from the -`Standard` toolbar, which allow you to toggle between building 32-bit or -64-bit binaries (or both at once using Batch Build). - -In order to prevent build output files from overwriting one another, -you'll need to change the `Intermediate Directory` settings for the -newly created platform configuration across all the projects. To do -this, multi-select (e.g. using shift-click) all projects (but not the -solution) in the `Solution Explorer`. Right-click one of them and -select `Properties`. In the left pane, select `Configuration Properties`, -and from the `Configuration` dropdown, select `All Configurations`. -Make sure the selected platform is `x64`. For the -`Intermediate Directory` setting, change the value from -`$(PlatformName)\$(ConfigurationName)` to -`$(OutDir)\$(ProjectName)`. Click `OK` and then build the -solution. When the build is complete, the 64-bit binaries will be in -the `msvc\x64\Debug` directory. - -## Can I use Google Test on MinGW? ## - -We haven't tested this ourselves, but Per Abrahamsen reported that he -was able to compile and install Google Test successfully when using -MinGW from Cygwin. You'll need to configure it with: - -`PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin"` - -You should be able to replace the `-mno-cygwin` option with direct links -to the real MinGW binaries, but we haven't tried that. - -Caveats: - - * There are many warnings when compiling. - * `make check` will produce some errors as not all tests for Google Test itself are compatible with MinGW. - -We also have reports on successful cross compilation of Google Test -MinGW binaries on Linux using -[these instructions](http://wiki.wxwidgets.org/Cross-Compiling_Under_Linux#Cross-compiling_under_Linux_for_MS_Windows) -on the WxWidgets site. - -Please contact `googletestframework@googlegroups.com` if you are -interested in improving the support for MinGW. - -## Why does Google Test support EXPECT\_EQ(NULL, ptr) and ASSERT\_EQ(NULL, ptr) but not EXPECT\_NE(NULL, ptr) and ASSERT\_NE(NULL, ptr)? ## - -Due to some peculiarity of C++, it requires some non-trivial template -meta programming tricks to support using `NULL` as an argument of the -`EXPECT_XX()` and `ASSERT_XX()` macros. Therefore we only do it where -it's most needed (otherwise we make the implementation of Google Test -harder to maintain and more error-prone than necessary). - -The `EXPECT_EQ()` macro takes the _expected_ value as its first -argument and the _actual_ value as the second. It's reasonable that -someone wants to write `EXPECT_EQ(NULL, some_expression)`, and this -indeed was requested several times. Therefore we implemented it. - -The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the -assertion fails, you already know that `ptr` must be `NULL`, so it -doesn't add any information to print ptr in this case. That means -`EXPECT_TRUE(ptr != NULL)` works just as well. - -If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll -have to support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, -we don't have a convention on the order of the two arguments for -`EXPECT_NE`. This means using the template meta programming tricks -twice in the implementation, making it even harder to understand and -maintain. We believe the benefit doesn't justify the cost. - -Finally, with the growth of Google Mock's [matcher](../../googlemock/docs/CookBook.md#using-matchers-in-google-test-assertions) library, we are -encouraging people to use the unified `EXPECT_THAT(value, matcher)` -syntax more often in tests. One significant advantage of the matcher -approach is that matchers can be easily combined to form new matchers, -while the `EXPECT_NE`, etc, macros cannot be easily -combined. Therefore we want to invest more in the matchers than in the +(`Time_Flies_Like_An_Arrow_Test`). That's not good. + +So for simplicity, we just ask the users to avoid `_` in `TestCaseName` and +`TestName`. The rule is more constraining than necessary, but it's simple and +easy to remember. It also gives googletest some wiggle room in case its +implementation needs to change in the future. + +If you violate the rule, there may not be immediate consequences, but your test +may (just may) break with a new compiler (or a new version of the compiler you +are using) or with a new version of googletest. Therefore it's best to follow +the rule. + +## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`? + +First of all you can use `EXPECT_NE(nullptr, ptr)` and `ASSERT_NE(nullptr, +ptr)`. This is the preferred syntax in the style guide because nullptr does not +have the type problems that NULL does. Which is why NULL does not work. + +Due to some peculiarity of C++, it requires some non-trivial template meta +programming tricks to support using `NULL` as an argument of the `EXPECT_XX()` +and `ASSERT_XX()` macros. Therefore we only do it where it's most needed +(otherwise we make the implementation of googletest harder to maintain and more +error-prone than necessary). + +The `EXPECT_EQ()` macro takes the *expected* value as its first argument and the +*actual* value as the second. It's reasonable that someone wants to write +`EXPECT_EQ(NULL, some_expression)`, and this indeed was requested several times. +Therefore we implemented it. + +The need for `EXPECT_NE(NULL, ptr)` isn't nearly as strong. When the assertion +fails, you already know that `ptr` must be `NULL`, so it doesn't add any +information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)` +works just as well. + +If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'll have to +support `EXPECT_NE(ptr, NULL)` as well, as unlike `EXPECT_EQ`, we don't have a +convention on the order of the two arguments for `EXPECT_NE`. This means using +the template meta programming tricks twice in the implementation, making it even +harder to understand and maintain. We believe the benefit doesn't justify the +cost. + +Finally, with the growth of the gMock matcher library, we are encouraging people +to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One +significant advantage of the matcher approach is that matchers can be easily +combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be +easily combined. Therefore we want to invest more in the matchers than in the `EXPECT_XX()` macros. -## Does Google Test support running tests in parallel? ## - -Test runners tend to be tightly coupled with the build/test -environment, and Google Test doesn't try to solve the problem of -running tests in parallel. Instead, we tried to make Google Test work -nicely with test runners. For example, Google Test's XML report -contains the time spent on each test, and its `gtest_list_tests` and -`gtest_filter` flags can be used for splitting the execution of test -methods into multiple processes. These functionalities can help the -test runner run the tests in parallel. +## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests? -## Why don't Google Test run the tests in different threads to speed things up? ## +For testing various implementations of the same interface, either typed tests or +value-parameterized tests can get it done. It's really up to you the user to +decide which is more convenient for you, depending on your particular case. Some +rough guidelines: -It's difficult to write thread-safe code. Most tests are not written -with thread-safety in mind, and thus may not work correctly in a -multi-threaded setting. +* Typed tests can be easier to write if instances of the different + implementations can be created the same way, modulo the type. For example, + if all these implementations have a public default constructor (such that + you can write `new TypeParam`), or if their factory functions have the same + form (e.g. `CreateInstance()`). +* Value-parameterized tests can be easier to write if you need different code + patterns to create different implementations' instances, e.g. `new Foo` vs + `new Bar(5)`. To accommodate for the differences, you can write factory + function wrappers and pass these function pointers to the tests as their + parameters. +* When a typed test fails, the output includes the name of the type, which can + help you quickly identify which implementation is wrong. Value-parameterized + tests cannot do this, so there you'll have to look at the iteration number + to know which implementation the failure is from, which is less direct. +* If you make a mistake writing a typed test, the compiler errors can be + harder to digest, as the code is templatized. +* When using typed tests, you need to make sure you are testing against the + interface type, not the concrete types (in other words, you want to make + sure `implicit_cast(my_concrete_impl)` works, not just that + `my_concrete_impl` works). It's less likely to make mistakes in this area + when using value-parameterized tests. -If you think about it, it's already hard to make your code work when -you know what other threads are doing. It's much harder, and -sometimes even impossible, to make your code work when you don't know -what other threads are doing (remember that test methods can be added, -deleted, or modified after your test was written). If you want to run -the tests in parallel, you'd better run them in different processes. +I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give +both approaches a try. Practice is a much better way to grasp the subtle +differences between the two tools. Once you have some concrete experience, you +can much more easily decide which one to use the next time. -## Why aren't Google Test assertions implemented using exceptions? ## +## My death tests became very slow - what happened? -Our original motivation was to be able to use Google Test in projects -that disable exceptions. Later we realized some additional benefits -of this approach: - - 1. Throwing in a destructor is undefined behavior in C++. Not using exceptions means Google Test's assertions are safe to use in destructors. - 1. The `EXPECT_*` family of macros will continue even after a failure, allowing multiple failures in a `TEST` to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing. - 1. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code: -```c++ -try { ... ASSERT_TRUE(...) ... } -catch (...) { ... } -``` -The above code will pass even if the `ASSERT_TRUE` throws. While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test. +In August 2008 we had to switch the default death test style from `fast` to +`threadsafe`, as the former is no longer safe now that threaded logging is the +default. This caused many death tests to slow down. Unfortunately this change +was necessary. -The downside of not using exceptions is that `ASSERT_*` (implemented -using `return`) will only abort the current function, not the current -`TEST`. +Please read [Fixing Failing Death Tests](death_test_styles.md) for what you can +do. -## Why do we use two different macros for tests with and without fixtures? ## +## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help! -Unfortunately, C++'s macro system doesn't allow us to use the same -macro for both cases. One possibility is to provide only one macro -for tests with fixtures, and require the user to define an empty -fixture sometimes: +**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated* +now. Please use `EqualsProto`, etc instead. -```c++ -class FooTest : public ::testing::Test {}; +`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and +are now less tolerant on invalid protocol buffer definitions. In particular, if +you have a `foo.proto` that doesn't fully qualify the type of a protocol message +it references (e.g. `message` where it should be `message`), you +will now get run-time errors like: -TEST_F(FooTest, DoesThis) { ... } ``` -or -```c++ -typedef ::testing::Test FooTest; - -TEST_F(FooTest, DoesThat) { ... } +... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto": +... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined. ``` -Yet, many people think this is one line too many. :-) Our goal was to -make it really easy to write tests, so we tried to make simple tests -trivial to create. That means using a separate macro for such tests. +If you see this, your `.proto` file is broken and needs to be fixed by making +the types fully qualified. The new definition of `ProtocolMessageEquals` and +`ProtocolMessageEquiv` just happen to reveal your bug. -We think neither approach is ideal, yet either of them is reasonable. -In the end, it probably doesn't matter much either way. +## My death test modifies some state, but the change seems lost after the death test finishes. Why? -## Why don't we use structs as test fixtures? ## +Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the +expected crash won't kill the test program (i.e. the parent process). As a +result, any in-memory side effects they incur are observable in their respective +sub-processes, but not in the parent process. You can think of them as running +in a parallel universe, more or less. -We like to use structs only when representing passive data. This -distinction between structs and classes is good for documenting the -intent of the code's author. Since test fixtures have logic like -`SetUp()` and `TearDown()`, they are better defined as classes. +In particular, if you use [gMock](http://go/gmock) and the death test statement +invokes some mock methods, the parent process will think the calls have never +occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside +the `EXPECT_DEATH` macro. -## Why are death tests implemented as assertions instead of using a test runner? ## +## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug? -Our goal was to make death tests as convenient for a user as C++ -possibly allows. In particular: +Actually, the bug is in `htonl()`. - * The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect. The death test would be written in C++, while the runner spec may or may not be. A user needs to carefully keep the two in sync. `ASSERT_DEATH(statement, expected_message)` specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative. - * `ASSERT_DEATH` has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn. - * `ASSERT_DEATH` can be mixed with other assertions and other logic at your will. You are not limited to one death test per test method. For example, you can write something like: -```c++ - if (FooCondition()) { - ASSERT_DEATH(Bar(), "blah"); - } else { - ASSERT_EQ(5, Bar()); - } -``` -If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users. The fewer artificial limitations the better. - * `ASSERT_DEATH` can reference local variables in the current function, and you can decide how many death tests you want based on run-time information. For example, -```c++ - const int count = GetCount(); // Only known at run time. - for (int i = 1; i <= count; i++) { - ASSERT_DEATH({ - double* buffer = new double[i]; - ... initializes buffer ... - Foo(buffer, i) - }, "blah blah"); - } -``` -The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility. +According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to +use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as +a *macro*, which breaks this usage. -Another interesting thing about `ASSERT_DEATH` is that it calls `fork()` -to create a child process to run the death test. This is lightening -fast, as `fork()` uses copy-on-write pages and incurs almost zero -overhead, and the child process starts from the user-supplied -statement directly, skipping all global and local initialization and -any code leading to the given statement. If you launch the child -process from scratch, it can take seconds just to load everything and -start running if the test links to many libraries dynamically. +Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not* +standard C++. That hacky implementation has some ad hoc limitations. In +particular, it prevents you from writing `Foo()`, where `Foo` +is a template that has an integral argument. -## My death test modifies some state, but the change seems lost after the death test finishes. Why? ## +The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a +template argument, and thus doesn't compile in opt mode when `a` contains a call +to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as +the solution must work with different compilers on various platforms. -Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the -expected crash won't kill the test program (i.e. the parent process). As a -result, any in-memory side effects they incur are observable in their -respective sub-processes, but not in the parent process. You can think of them -as running in a parallel universe, more or less. +`htonl()` has some other problems as described in `//util/endian/endian.h`, +which defines `ghtonl()` to replace it. `ghtonl()` does the same thing `htonl()` +does, only without its problems. We suggest you to use `ghtonl()` instead of +`htonl()`, both in your tests and production code. + +`//util/endian/endian.h` also defines `ghtons()`, which solves similar problems +in `htons()`. -## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? ## +Don't forget to add `//util/endian` to the list of dependencies in the `BUILD` +file wherever `ghtonl()` and `ghtons()` are used. The library consists of a +single header file and will not bloat your binary. + +## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? If your class has a static data member: @@ -343,23 +209,18 @@ class Foo { }; ``` -You also need to define it _outside_ of the class body in `foo.cc`: +You also need to define it *outside* of the class body in `foo.cc`: ```c++ const int Foo::kBar; // No initializer here. ``` Otherwise your code is **invalid C++**, and may break in unexpected ways. In -particular, using it in Google Test comparison assertions (`EXPECT_EQ`, etc) -will generate an "undefined reference" linker error. - -## I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? ## - -Google Test doesn't yet have good support for this kind of tests, or -data-driven tests in general. We hope to be able to make improvements in this -area soon. +particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will +generate an "undefined reference" linker error. The fact that "it used to work" +doesn't mean it's valid. It just means that you were lucky. :-) -## Can I derive a test fixture from another? ## +## Can I derive a test fixture from another? Yes. @@ -369,33 +230,35 @@ cases may want to use the same or slightly different fixtures. For example, you may want to make sure that all of a GUI library's test cases don't leak important system resources like fonts and brushes. -In Google Test, you share a fixture among test cases by putting the shared -logic in a base test fixture, then deriving from that base a separate fixture -for each test case that wants to use this common logic. You then use `TEST_F()` -to write tests using each derived fixture. +In googletest, you share a fixture among test cases by putting the shared logic +in a base test fixture, then deriving from that base a separate fixture for each +test case that wants to use this common logic. You then use `TEST_F()` to write +tests using each derived fixture. Typically, your code looks like this: ```c++ // Defines a base test fixture. class BaseTest : public ::testing::Test { - protected: - ... + protected: + ... }; // Derives a fixture FooTest from BaseTest. class FooTest : public BaseTest { - protected: - virtual void SetUp() { - BaseTest::SetUp(); // Sets up the base fixture first. - ... additional set-up work ... - } - virtual void TearDown() { - ... clean-up work for FooTest ... - BaseTest::TearDown(); // Remember to tear down the base fixture - // after cleaning up FooTest! - } - ... functions and variables for FooTest ... + protected: + void SetUp() override { + BaseTest::SetUp(); // Sets up the base fixture first. + ... additional set-up work ... + } + + void TearDown() override { + ... clean-up work for FooTest ... + BaseTest::TearDown(); // Remember to tear down the base fixture + // after cleaning up FooTest! + } + + ... functions and variables for FooTest ... }; // Tests that use the fixture FooTest. @@ -406,32 +269,35 @@ TEST_F(FooTest, Baz) { ... } ``` If necessary, you can continue to derive test fixtures from a derived fixture. -Google Test has no limit on how deep the hierarchy can be. +googletest has no limit on how deep the hierarchy can be. -For a complete example using derived test fixtures, see -[sample5](../samples/sample5_unittest.cc). +For a complete example using derived test fixtures, see [googletest +sample](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc) -## My compiler complains "void value not ignored as it ought to be." What does this mean? ## +## My compiler complains "void value not ignored as it ought to be." What does this mean? You're probably using an `ASSERT_*()` in a function that doesn't return `void`. -`ASSERT_*()` can only be used in `void` functions. +`ASSERT_*()` can only be used in `void` functions, due to exceptions being +disabled by our build system. Please see more details +[here](advanced.md#assertion-placement). -## My death test hangs (or seg-faults). How do I fix it? ## +## My death test hangs (or seg-faults). How do I fix it? -In Google Test, death tests are run in a child process and the way they work is +In googletest, death tests are run in a child process and the way they work is delicate. To write death tests you really need to understand how they work. -Please make sure you have read this. +Please make sure you have read [this](advanced.md#how-it-works). In particular, death tests don't like having multiple threads in the parent -process. So the first thing you can try is to eliminate creating threads -outside of `EXPECT_DEATH()`. +process. So the first thing you can try is to eliminate creating threads outside +of `EXPECT_DEATH()`. For example, you may want to use [mocks](http://go/gmock) +or fake objects instead of real ones in your tests. Sometimes this is impossible as some library you must use may be creating threads before `main()` is even reached. In this case, you can try to minimize the chance of conflicts by either moving as many activities as possible inside `EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or -leaving as few things as possible in it. Also, you can try to set the death -test style to `"threadsafe"`, which is safer but slower, and see if it helps. +leaving as few things as possible in it. Also, you can try to set the death test +style to `"threadsafe"`, which is safer but slower, and see if it helps. If you go with thread-safe death tests, remember that they rerun the test program from the beginning in the child process. Therefore make sure your @@ -441,28 +307,52 @@ In the end, this boils down to good concurrent programming. You have to make sure that there is no race conditions or dead locks in your program. No silver bullet - sorry! -## Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? ## +## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? -The first thing to remember is that Google Test does not reuse the -same test fixture object across multiple tests. For each `TEST_F`, -Google Test will create a fresh test fixture object, _immediately_ -call `SetUp()`, run the test body, call `TearDown()`, and then -_immediately_ delete the test fixture object. +The first thing to remember is that googletest does **not** reuse the same test +fixture object across multiple tests. For each `TEST_F`, googletest will create +a **fresh** test fixture object, immediately call `SetUp()`, run the test body, +call `TearDown()`, and then delete the test fixture object. -When you need to write per-test set-up and tear-down logic, you have -the choice between using the test fixture constructor/destructor or -`SetUp()/TearDown()`. The former is usually preferred, as it has the -following benefits: +When you need to write per-test set-up and tear-down logic, you have the choice +between using the test fixture constructor/destructor or `SetUp()/TearDown()`. +The former is usually preferred, as it has the following benefits: - * By initializing a member variable in the constructor, we have the option to make it `const`, which helps prevent accidental changes to its value and makes the tests more obviously correct. - * In case we need to subclass the test fixture class, the subclass' constructor is guaranteed to call the base class' constructor first, and the subclass' destructor is guaranteed to call the base class' destructor afterward. With `SetUp()/TearDown()`, a subclass may make the mistake of forgetting to call the base class' `SetUp()/TearDown()` or call them at the wrong moment. +* By initializing a member variable in the constructor, we have the option to + make it `const`, which helps prevent accidental changes to its value and + makes the tests more obviously correct. +* In case we need to subclass the test fixture class, the subclass' + constructor is guaranteed to call the base class' constructor *first*, and + the subclass' destructor is guaranteed to call the base class' destructor + *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of + forgetting to call the base class' `SetUp()/TearDown()` or call them at the + wrong time. You may still want to use `SetUp()/TearDown()` in the following rare cases: - * If the tear-down operation could throw an exception, you must use `TearDown()` as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer `TearDown()` if you want to write portable tests that work with or without exceptions. - * The assertion macros throw an exception when flag `--gtest_throw_on_failure` is specified. Therefore, you shouldn't use Google Test assertions in a destructor if you plan to run your tests with this flag. - * In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overridden in a derived class, you have to use `SetUp()/TearDown()`. -## The compiler complains "no matching function to call" when I use ASSERT\_PREDn. How do I fix it? ## +* In the body of a constructor (or destructor), it's not possible to use the + `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal + test failure that should prevent the test from running, it's necessary to + use a `CHECK` macro or to use `SetUp()` instead of a constructor. +* If the tear-down operation could throw an exception, you must use + `TearDown()` as opposed to the destructor, as throwing in a destructor leads + to undefined behavior and usually will kill your program right away. Note + that many standard libraries (like STL) may throw when exceptions are + enabled in the compiler. Therefore you should prefer `TearDown()` if you + want to write portable tests that work with or without exceptions. +* The googletest team is considering making the assertion macros throw on + platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux + client-side), which will eliminate the need for the user to propagate + failures from a subroutine to its caller. Therefore, you shouldn't use + googletest assertions in a destructor if your code could run on such a + platform. +* In a constructor or destructor, you cannot make a virtual function call on + this object. (You can call a method declared as virtual, but it will be + statically bound.) Therefore, if you need to call a method that will be + overridden in a derived class, you have to use `SetUp()/TearDown()`. + + +## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it? If the predicate function you use in `ASSERT_PRED*` or `EXPECT_PRED*` is overloaded or a template, the compiler will have trouble figuring out which @@ -480,6 +370,7 @@ For example, suppose you have bool IsPositive(int n) { return n > 0; } + bool IsPositive(double x) { return x > 0; } @@ -497,8 +388,8 @@ However, this will work: EXPECT_PRED1(static_cast(IsPositive), 5); ``` -(The stuff inside the angled brackets for the `static_cast` operator is the -type of the function pointer for the `int`-version of `IsPositive()`.) +(The stuff inside the angled brackets for the `static_cast` operator is the type +of the function pointer for the `int`-version of `IsPositive()`.) As another example, when you have a template function @@ -522,72 +413,76 @@ following won't compile: ASSERT_PRED2(GreaterThan, 5, 0); ``` - -as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, -which is one more than expected. The workaround is to wrap the predicate -function in parentheses: +as the C++ pre-processor thinks you are giving `ASSERT_PRED2` 4 arguments, which +is one more than expected. The workaround is to wrap the predicate function in +parentheses: ```c++ ASSERT_PRED2((GreaterThan), 5, 0); ``` -## My compiler complains about "ignoring return value" when I call RUN\_ALL\_TESTS(). Why? ## +## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is, instead of ```c++ -return RUN_ALL_TESTS(); + return RUN_ALL_TESTS(); ``` they write ```c++ -RUN_ALL_TESTS(); + RUN_ALL_TESTS(); ``` -This is wrong and dangerous. A test runner needs to see the return value of -`RUN_ALL_TESTS()` in order to determine if a test has passed. If your `main()` -function ignores it, your test will be considered successful even if it has a -Google Test assertion failure. Very bad. +This is **wrong and dangerous**. The testing services needs to see the return +value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your +`main()` function ignores it, your test will be considered successful even if it +has a googletest assertion failure. Very bad. -To help the users avoid this dangerous bug, the implementation of -`RUN_ALL_TESTS()` causes gcc to raise this warning, when the return value is -ignored. If you see this warning, the fix is simple: just make sure its value -is used as the return value of `main()`. +We have decided to fix this (thanks to Michael Chastain for the idea). Now, your +code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with +`gcc`. If you do so, you'll get a compiler error. -## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? ## +If you see the compiler complaining about you ignoring the return value of +`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the +return value of `main()`. + +But how could we introduce a change that breaks existing tests? Well, in this +case, the code was already broken in the first place, so we didn't break it. :-) + +## My compiler complains that a constructor (or destructor) cannot return a value. What's going on? Due to a peculiarity of C++, in order to support the syntax for streaming messages to an `ASSERT_*`, e.g. ```c++ -ASSERT_EQ(1, Foo()) << "blah blah" << foo; + ASSERT_EQ(1, Foo()) << "blah blah" << foo; ``` we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and `ADD_FAILURE*`) in constructors and destructors. The workaround is to move the content of your constructor/destructor to a private void member function, or -switch to `EXPECT_*()` if that works. This section in the user's guide explains -it. +switch to `EXPECT_*()` if that works. This +[section](advanced.md#assertion-placement) in the user's guide explains it. -## My set-up function is not called. Why? ## +## My SetUp() function is not called. Why? -C++ is case-sensitive. It should be spelled as `SetUp()`. Did you -spell it as `Setup()`? +C++ is case-sensitive. Did you spell it as `Setup()`? Similarly, sometimes people spell `SetUpTestCase()` as `SetupTestCase()` and wonder why it's never called. -## How do I jump to the line of a failure in Emacs directly? ## +## How do I jump to the line of a failure in Emacs directly? + +googletest's failure message format is understood by Emacs and many other IDEs, +like acme and XCode. If a googletest message is in a compilation buffer in +Emacs, then it's clickable. -Google Test's failure message format is understood by Emacs and many other -IDEs, like acme and XCode. If a Google Test message is in a compilation buffer -in Emacs, then it's clickable. You can now hit `enter` on a message to jump to -the corresponding source code, or use `C-x `` to jump to the next failure. -## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. ## +## I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. You don't have to. Instead of @@ -604,6 +499,7 @@ TEST_F(BarTest, Def) { ... } ``` you can simply `typedef` the test fixtures: + ```c++ typedef BaseTest FooTest; @@ -616,192 +512,47 @@ TEST_F(BarTest, Abc) { ... } TEST_F(BarTest, Def) { ... } ``` -## The Google Test output is buried in a whole bunch of log messages. What do I do? ## +## googletest output is buried in a whole bunch of LOG messages. What do I do? -The Google Test output is meant to be a concise and human-friendly report. If -your test generates textual output itself, it will mix with the Google Test +The googletest output is meant to be a concise and human-friendly report. If +your test generates textual output itself, it will mix with the googletest output, making it hard to read. However, there is an easy solution to this problem. -Since most log messages go to stderr, we decided to let Google Test output go -to stdout. This way, you can easily separate the two using redirection. For +Since `LOG` messages go to stderr, we decided to let googletest output go to +stdout. This way, you can easily separate the two using redirection. For example: -``` -./my_test > googletest_output.txt -``` - -## Why should I prefer test fixtures over global variables? ## - -There are several good reasons: - 1. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other. - 1. Global variables pollute the global namespace. - 1. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common. - -## How do I test private class members without writing FRIEND\_TEST()s? ## -You should try to write testable code, which means classes should be easily -tested from their public interface. One way to achieve this is the Pimpl idiom: -you move all private members of a class into a helper class, and make all -members of the helper class public. - -You have several other options that don't require using `FRIEND_TEST`: - * Write the tests as members of the fixture class: -```c++ -class Foo { - friend class FooTest; - ... -}; - -class FooTest : public ::testing::Test { - protected: - ... - void Test1() {...} // This accesses private members of class Foo. - void Test2() {...} // So does this one. -}; - -TEST_F(FooTest, Test1) { - Test1(); -} - -TEST_F(FooTest, Test2) { - Test2(); -} +```shell +$ ./my_test > gtest_output.txt ``` - * In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests: -```c++ -class Foo { - friend class FooTest; - ... -}; -class FooTest : public ::testing::Test { - protected: - ... - T1 get_private_member1(Foo* obj) { - return obj->private_member1_; - } -}; -TEST_F(FooTest, Test1) { - ... - get_private_member1(x) - ... -} -``` - * If the methods are declared **protected**, you can change their access level in a test-only subclass: -```c++ -class YourClass { - ... - protected: // protected access for testability. - int DoSomethingReturningInt(); - ... -}; - -// in the your_class_test.cc file: -class TestableYourClass : public YourClass { - ... - public: using YourClass::DoSomethingReturningInt; // changes access rights - ... -}; - -TEST_F(YourClassTest, DoSomethingTest) { - TestableYourClass obj; - assertEquals(expected_value, obj.DoSomethingReturningInt()); -} -``` - -## How do I test private class static members without writing FRIEND\_TEST()s? ## - -We find private static methods clutter the header file. They are -implementation details and ideally should be kept out of a .h. So often I make -them free functions instead. - -Instead of: -```c++ -// foo.h -class Foo { - ... - private: - static bool Func(int n); -}; - -// foo.cc -bool Foo::Func(int n) { ... } - -// foo_test.cc -EXPECT_TRUE(Foo::Func(12345)); -``` - -You probably should better write: -```c++ -// foo.h -class Foo { - ... -}; - -// foo.cc -namespace internal { - bool Func(int n) { ... } -} - -// foo_test.cc -namespace internal { - bool Func(int n); -} - -EXPECT_TRUE(internal::Func(12345)); -``` - -## I would like to run a test several times with different parameters. Do I need to write several similar copies of it? ## - -No. You can use a feature called [value-parameterized tests](advanced.md#Value_Parameterized_Tests) which -lets you repeat your tests with different parameters, without defining it more than once. - -## How do I test a file that defines main()? ## - -To test a `foo.cc` file, you need to compile and link it into your unit test -program. However, when the file contains a definition for the `main()` -function, it will clash with the `main()` of your unit test, and will result in -a build error. +## Why should I prefer test fixtures over global variables? -The right solution is to split it into three files: - 1. `foo.h` which contains the declarations, - 1. `foo.cc` which contains the definitions except `main()`, and - 1. `foo_main.cc` which contains nothing but the definition of `main()`. - -Then `foo.cc` can be easily tested. - -If you are adding tests to an existing file and don't want an intrusive change -like this, there is a hack: just include the entire `foo.cc` file in your unit -test. For example: -```c++ -// File foo_unittest.cc - -// The headers section -... - -// Renames main() in foo.cc to make room for the unit test main() -#define main FooMain - -#include "a/b/foo.cc" - -// The tests start here. -... -``` +There are several good reasons: +1. It's likely your test needs to change the states of its global variables. + This makes it difficult to keep side effects from escaping one test and + contaminating others, making debugging difficult. By using fixtures, each + test has a fresh set of variables that's different (but with the same + names). Thus, tests are kept independent of each other. +1. Global variables pollute the global namespace. +1. Test fixtures can be reused via subclassing, which cannot be done easily + with global variables. This is useful if many test cases have something in + common. -However, please remember this is a hack and should only be used as the last -resort. -## What can the statement argument in ASSERT\_DEATH() be? ## + ## What can the statement argument in ASSERT_DEATH() be? -`ASSERT_DEATH(_statement_, _regex_)` (or any death assertion macro) can be used -wherever `_statement_` is valid. So basically `_statement_` can be any C++ +`ASSERT_DEATH(*statement*, *regex*)` (or any death assertion macro) can be used +wherever `*statement*` is valid. So basically `*statement*` can be any C++ statement that makes sense in the current context. In particular, it can reference global and/or local variables, and can be: - * a simple function call (often the case), - * a complex expression, or - * a compound statement. + +* a simple function call (often the case), +* a complex expression, or +* a compound statement. Some examples are shown here: @@ -818,7 +569,7 @@ TEST(MyDeathTest, ComplexExpression) { "(Func1|Method) failed"); } -// Death assertions can be used any where in a function. In +// Death assertions can be used any where in a function. In // particular, they can be inside a loop. TEST(MyDeathTest, InsideLoop) { // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. @@ -837,49 +588,47 @@ TEST(MyDeathTest, CompoundStatement) { Bar(i); } }, - "Bar has \\d+ errors");} + "Bar has \\d+ errors"); +} ``` -`googletest_unittest.cc` contains more examples if you are interested. - -## What syntax does the regular expression in ASSERT\_DEATH use? ## +gtest-death-test_test.cc contains more examples if you are interested. -On POSIX systems, Google Test uses the POSIX Extended regular -expression syntax -(http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). -On Windows, it uses a limited variant of regular expression -syntax. For more details, see the -[regular expression syntax](advanced.md#Regular_Expression_Syntax). +## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why? -## I have a fixture class Foo, but TEST\_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? ## +Googletest needs to be able to create objects of your test fixture class, so it +must have a default constructor. Normally the compiler will define one for you. +However, there are cases where you have to define your own: -Google Test needs to be able to create objects of your test fixture class, so -it must have a default constructor. Normally the compiler will define one for -you. However, there are cases where you have to define your own: - * If you explicitly declare a non-default constructor for class `Foo`, then you need to define a default constructor, even if it would be empty. - * If `Foo` has a const non-static data member, then you have to define the default constructor _and_ initialize the const member in the initializer list of the constructor. (Early versions of `gcc` doesn't force you to initialize the const member. It's a bug that has been fixed in `gcc 4`.) +* If you explicitly declare a non-default constructor for class `FooTest` + (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a + default constructor, even if it would be empty. +* If `FooTest` has a const non-static data member, then you have to define the + default constructor *and* initialize the const member in the initializer + list of the constructor. (Early versions of `gcc` doesn't force you to + initialize the const member. It's a bug that has been fixed in `gcc 4`.) -## Why does ASSERT\_DEATH complain about previous threads that were already joined? ## +## Why does ASSERT_DEATH complain about previous threads that were already joined? -With the Linux pthread library, there is no turning back once you cross the -line from single thread to multiple threads. The first time you create a -thread, a manager thread is created in addition, so you get 3, not 2, threads. -Later when the thread you create joins the main thread, the thread count -decrements by 1, but the manager thread will never be killed, so you still have -2 threads, which means you cannot safely run a death test. +With the Linux pthread library, there is no turning back once you cross the line +from single thread to multiple threads. The first time you create a thread, a +manager thread is created in addition, so you get 3, not 2, threads. Later when +the thread you create joins the main thread, the thread count decrements by 1, +but the manager thread will never be killed, so you still have 2 threads, which +means you cannot safely run a death test. The new NPTL thread library doesn't suffer from this problem, as it doesn't create a manager thread. However, if you don't control which machine your test runs on, you shouldn't depend on this. -## Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT\_DEATH? ## +## Why does googletest require the entire test case, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH? -Google Test does not interleave tests from different test cases. That is, it -runs all tests in one test case first, and then runs all tests in the next test -case, and so on. Google Test does this because it needs to set up a test case -before the first test in it is run, and tear it down afterwords. Splitting up -the test case would require multiple set-up and tear-down processes, which is -inefficient and makes the semantics unclean. +googletest does not interleave tests from different test cases. That is, it runs +all tests in one test case first, and then runs all tests in the next test case, +and so on. googletest does this because it needs to set up a test case before +the first test in it is run, and tear it down afterwords. Splitting up the test +case would require multiple set-up and tear-down processes, which is inefficient +and makes the semantics unclean. If we were to determine the order of tests based on test name instead of test case name, then we would have a problem with the following situation: @@ -897,7 +646,7 @@ interleave tests from different test cases, we need to run all tests in the `FooTest` case before running any test in the `BarTest` case. This contradicts with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`. -## But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? ## +## But I don't like calling my entire test case \*DeathTest when it contains both death tests and non-death tests. What do I do? You don't have to, but if you like, you may split up the test case into `FooTest` and `FooDeathTest`, where the names make it clear that they are @@ -909,119 +658,81 @@ class FooTest : public ::testing::Test { ... }; TEST_F(FooTest, Abc) { ... } TEST_F(FooTest, Def) { ... } -typedef FooTest FooDeathTest; +using FooDeathTest = FooTest; TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } ``` -## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? ## +## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds? + +Printing the LOG messages generated by the statement inside `EXPECT_DEATH()` +makes it harder to search for real problems in the parent's log. Therefore, +googletest only prints them when the death test has failed. + +If you really need to see such LOG messages, a workaround is to temporarily +break the death test (e.g. by changing the regex pattern it is expected to +match). Admittedly, this is a hack. We'll consider a more permanent solution +after the fork-and-exec-style death tests are implemented. + +## The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? If you use a user-defined type `FooType` in an assertion, you must make sure there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function defined such that we can print a value of `FooType`. In addition, if `FooType` is declared in a name space, the `<<` operator also -needs to be defined in the _same_ name space. +needs to be defined in the *same* name space. See go/totw/49 for details. -## How do I suppress the memory leak messages on Windows? ## +## How do I suppress the memory leak messages on Windows? -Since the statically initialized Google Test singleton requires allocations on +Since the statically initialized googletest singleton requires allocations on the heap, the Visual C++ memory leak detector will report memory leaks at the end of the program run. The easiest way to avoid this is to use the `_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any statically initialized heap objects. See MSDN for more details and additional heap check/debug routines. -## I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! ## - -You may get a number of the following linker error or warnings if you -attempt to link your test project with the Google Test library when -your project and the are not built using the same compiler settings. - - * LNK2005: symbol already defined in object - * LNK4217: locally defined symbol 'symbol' imported in function 'function' - * LNK4049: locally defined symbol 'symbol' imported - -The Google Test project (gtest.vcproj) has the Runtime Library option -set to /MT (use multi-threaded static libraries, /MTd for debug). If -your project uses something else, for example /MD (use multi-threaded -DLLs, /MDd for debug), you need to change the setting in the Google -Test project to match your project's. - -To update this setting open the project properties in the Visual -Studio IDE then select the branch Configuration Properties | C/C++ | -Code Generation and change the option "Runtime Library". You may also try -using gtest-md.vcproj instead of gtest.vcproj. - -## I put my tests in a library and Google Test doesn't run them. What's happening? ## -Have you read a -[warning](primer.md#important-note-for-visual-c-users) on -the Google Test Primer page? - -## I want to use Google Test with Visual Studio but don't know where to start. ## -Many people are in your position and one of them posted his solution to our mailing list. - -## I am seeing compile errors mentioning std::type\_traits when I try to use Google Test on Solaris. ## -Google Test uses parts of the standard C++ library that SunStudio does not support. -Our users reported success using alternative implementations. Try running the build after running this command: - -`export CC=cc CXX=CC CXXFLAGS='-library=stlport4'` - -## How can my code detect if it is running in a test? ## - -If you write code that sniffs whether it's running in a test and does -different things accordingly, you are leaking test-only logic into -production code and there is no easy way to ensure that the test-only -code paths aren't run by mistake in production. Such cleverness also -leads to -[Heisenbugs](http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbug). -Therefore we strongly advise against the practice, and Google Test doesn't -provide a way to do it. - -In general, the recommended way to cause the code to behave -differently under test is [dependency injection](http://jamesshore.com/Blog/Dependency-Injection-Demystified.html). -You can inject different functionality from the test and from the -production code. Since your production code doesn't link in the -for-test logic at all, there is no danger in accidentally running it. - -However, if you _really_, _really_, _really_ have no choice, and if -you follow the rule of ending your test program names with `_test`, -you can use the _horrible_ hack of sniffing your executable name -(`argv[0]` in `main()`) to know whether the code is under test. - -## Google Test defines a macro that clashes with one defined by another library. How do I deal with that? ## - -In C++, macros don't obey namespaces. Therefore two libraries that -both define a macro of the same name will clash if you `#include` both -definitions. In case a Google Test macro clashes with another -library, you can force Google Test to rename its macro to avoid the -conflict. - -Specifically, if both Google Test and some other code define macro -`FOO`, you can add -``` - -DGTEST_DONT_DEFINE_FOO=1 -``` -to the compiler flags to tell Google Test to change the macro's name -from `FOO` to `GTEST_FOO`. For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write -```c++ - GTEST_TEST(SomeTest, DoesThis) { ... } -``` -instead of -```c++ - TEST(SomeTest, DoesThis) { ... } -``` -in order to define a test. -Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have . You can see the full list of covered macros [here](../include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file. +## How can my code detect if it is running in a test? + +If you write code that sniffs whether it's running in a test and does different +things accordingly, you are leaking test-only logic into production code and +there is no easy way to ensure that the test-only code paths aren't run by +mistake in production. Such cleverness also leads to +[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly +advise against the practice, and googletest doesn't provide a way to do it. + +In general, the recommended way to cause the code to behave differently under +test is [Dependency Injection](http://go/dependency-injection). You can inject +different functionality from the test and from the production code. Since your +production code doesn't link in the for-test logic at all (the +[`testonly`](http://go/testonly) attribute for BUILD targets helps to ensure +that), there is no danger in accidentally running it. +However, if you *really*, *really*, *really* have no choice, and if you follow +the rule of ending your test program names with `_test`, you can use the +*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know +whether the code is under test. -## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? ## + +## How do I temporarily disable a test? + +If you have a broken test that you cannot fix right away, you can add the +DISABLED_ prefix to its name. This will exclude it from execution. This is +better than commenting out the code or using #if 0, as disabled tests are still +compiled (and thus won't rot). + +To include disabled tests in test execution, just invoke the test program with +the --gtest_also_run_disabled_tests flag. + +## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces? Yes. -The rule is **all test methods in the same test case must use the same fixture class**. This means that the following is **allowed** because both tests use the same fixture class (`::testing::Test`). +The rule is **all test methods in the same test case must use the same fixture +class.** This means that the following is **allowed** because both tests use the +same fixture class (`::testing::Test`). ```c++ namespace foo { @@ -1037,7 +748,9 @@ TEST(CoolTest, DoSomething) { } // namespace bar ``` -However, the following code is **not allowed** and will produce a runtime error from Google Test because the test methods are using different test fixture classes with the same test case name. +However, the following code is **not allowed** and will produce a runtime error +from googletest because the test methods are using different test fixture +classes with the same test case name. ```c++ namespace foo { @@ -1054,39 +767,3 @@ TEST_F(CoolTest, DoSomething) { } } // namespace bar ``` - -## How do I build Google Testing Framework with Xcode 4? ## - -If you try to build Google Test's Xcode project with Xcode 4.0 or later, you may encounter an error message that looks like -"Missing SDK in target gtest\_framework: /Developer/SDKs/MacOSX10.4u.sdk". That means that Xcode does not support the SDK the project is targeting. See the Xcode section in the [README](../README.md) file on how to resolve this. - -## How do I easily discover the flags needed for GoogleTest? ## - -GoogleTest (and GoogleMock) now support discovering all necessary flags using pkg-config. -See the [pkg-config guide](Pkgconfig.md) on how you can easily discover all compiler and -linker flags using pkg-config. - -## My question is not covered in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](../docs), - 1. search the mailing list [archive](https://groups.google.com/forum/#!forum/googletestframework), - 1. ask it on [googletestframework@googlegroups.com](mailto:googletestframework@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googletestframework) before you can post.). - -Please note that creating an issue in the -[issue tracker](https://github.com/google/googletest/issues) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the commit hash if you check out from Git directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 9949658..b80418e 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -1,5 +1,6 @@ # Googletest Primer + ## Introduction: Why googletest? *googletest* helps you write better C++ tests. @@ -436,6 +437,7 @@ When these tests run, the following happens: **Availability**: Linux, Windows, Mac. + ## Invoking the Tests `TEST()` and `TEST_F()` implicitly register their tests with googletest. So, @@ -544,6 +546,7 @@ int main(int argc, char **argv) { } ``` + The `::testing::InitGoogleTest()` function parses the command line for googletest flags, and removes all recognized flags. This allows the user to control a test program's behavior via various flags, which we'll cover in @@ -560,6 +563,7 @@ gtest\_main library and you are good to go. NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`. + ## Known Limitations * Google Test is designed to be thread-safe. The implementation is thread-safe -- cgit v0.12 From 7e73a7ae6e665e3a9e34543090625ab8278412bb Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:17:19 -0400 Subject: Formatting and a link --- googlemock/include/gmock/internal/custom/gmock-matchers.h | 2 +- googletest/include/gtest/internal/gtest-port.h | 2 +- googletest/src/gtest.cc | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h index fe0d9e8..af8240e 100644 --- a/googlemock/include/gmock/internal/custom/gmock-matchers.h +++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -32,7 +32,7 @@ // ============================================================ // // Adds google3 callback support to CallableTraits. -// + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index d5ec086..bc35c34 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1218,7 +1218,7 @@ class scoped_ptr { // Defines RE. #if GTEST_USES_PCRE -using ::RE; +// if used, PCRE is injected by custom/gtest-port.h #elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE // A simple C++ wrapper for . It uses the POSIX Extended diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 9c25c99..26a3710 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -5273,7 +5273,7 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see -// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md +// https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? -- cgit v0.12 From 8d07cfd0532352379c624ce8844aeca0dc68a585 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:30:36 -0400 Subject: Code sync, mostly formatting and removing outdates --- googlemock/test/gmock-actions_test.cc | 202 ---------------------------------- googlemock/test/gmock_ex_test.cc | 3 +- 2 files changed, 2 insertions(+), 203 deletions(-) diff --git a/googlemock/test/gmock-actions_test.cc b/googlemock/test/gmock-actions_test.cc index 7fbb50d..e8bdbee 100644 --- a/googlemock/test/gmock-actions_test.cc +++ b/googlemock/test/gmock-actions_test.cc @@ -88,10 +88,6 @@ using testing::tuple_element; using testing::SetErrnoAndReturn; #endif -#if GTEST_HAS_PROTOBUF_ -using testing::internal::TestMessage; -#endif // GTEST_HAS_PROTOBUF_ - // Tests that BuiltInDefaultValue::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { EXPECT_TRUE(BuiltInDefaultValue::Get() == NULL); @@ -895,105 +891,6 @@ TEST(SetArgPointeeTest, AcceptsWideCharPointer) { # endif } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgPointee(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgPointee(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgPointee(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgPointee<1>(*msg); - // SetArgPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Tests that SetArgumentPointee(v) sets the variable pointed to by // the N-th (0-based) argument to v. TEST(SetArgumentPointeeTest, SetsTheNthPointee) { @@ -1014,105 +911,6 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) { EXPECT_EQ('a', ch); } -#if GTEST_HAS_PROTOBUF_ - -// Tests that SetArgumentPointee(proto_buffer) sets the v1 protobuf -// variable pointed to by the N-th (0-based) argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, &dest)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee(proto_buffer) sets the -// ::ProtocolMessage variable pointed to by the N-th (0-based) -// argument to proto_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) { - TestMessage* const msg = new TestMessage; - msg->set_member("yes"); - TestMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto_buffer) makes a copy of proto_buffer - // s.t. the action works even when the original proto_buffer has - // died. We ensure this behavior by deleting msg before using the - // action. - delete msg; - - TestMessage dest; - ::ProtocolMessage* const dest_base = &dest; - EXPECT_FALSE(orig_msg.Equals(dest)); - a.Perform(make_tuple(true, dest_base)); - EXPECT_TRUE(orig_msg.Equals(dest)); -} - -// Tests that SetArgumentPointee(proto2_buffer) sets the v2 -// protobuf variable pointed to by the N-th (0-based) argument to -// proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - a.Perform(make_tuple(true, &dest)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -// Tests that SetArgumentPointee(proto2_buffer) sets the -// proto2::Message variable pointed to by the N-th (0-based) argument -// to proto2_buffer. -TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { - using testing::internal::FooMessage; - FooMessage* const msg = new FooMessage; - msg->set_int_field(2); - msg->set_string_field("hi"); - FooMessage orig_msg; - orig_msg.CopyFrom(*msg); - - Action a = SetArgumentPointee<1>(*msg); - // SetArgumentPointee(proto2_buffer) makes a copy of - // proto2_buffer s.t. the action works even when the original - // proto2_buffer has died. We ensure this behavior by deleting msg - // before using the action. - delete msg; - - FooMessage dest; - dest.set_int_field(0); - ::proto2::Message* const dest_base = &dest; - a.Perform(make_tuple(true, dest_base)); - EXPECT_EQ(2, dest.int_field()); - EXPECT_EQ("hi", dest.string_field()); -} - -#endif // GTEST_HAS_PROTOBUF_ - // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } diff --git a/googlemock/test/gmock_ex_test.cc b/googlemock/test/gmock_ex_test.cc index 99268b3..b03de82 100644 --- a/googlemock/test/gmock_ex_test.cc +++ b/googlemock/test/gmock_ex_test.cc @@ -38,6 +38,7 @@ namespace { using testing::HasSubstr; + using testing::internal::GoogleTestFailureException; // A type that cannot be default constructed. @@ -53,7 +54,6 @@ class MockFoo { MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible()); }; - TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { MockFoo mock; try { @@ -76,5 +76,6 @@ TEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) { } } + } // unnamed namespace #endif -- cgit v0.12 From d41bfd732f3980c573f8fa27faf4d38d7fb16a45 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:38:18 -0400 Subject: Fix link --- googletest/src/gtest.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index 26a3710..9c25c99 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -5273,7 +5273,7 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see -// https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md +// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md // . Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? -- cgit v0.12 From 3530ab9e437b57e9d6778f646d5b88343cae5e02 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 18 Jul 2018 11:51:14 -0400 Subject: Code sync --- googlemock/test/gmock-matchers_test.cc | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index 87b2ad5..a451842 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2680,7 +2680,7 @@ TEST(AllOfTest, ExplainsResult) { } // Helper to allow easy testing of AnyOf matchers with num parameters. -void AnyOfMatches(int num, const Matcher& m) { +static void AnyOfMatches(int num, const Matcher& m) { SCOPED_TRACE(Describe(m)); EXPECT_FALSE(m.Matches(0)); for (int i = 1; i <= num; ++i) { @@ -2689,6 +2689,18 @@ void AnyOfMatches(int num, const Matcher& m) { EXPECT_FALSE(m.Matches(num + 1)); } +#if GTEST_LANG_CXX11 +static void AnyOfStringMatches(int num, const Matcher& m) { + SCOPED_TRACE(Describe(m)); + EXPECT_FALSE(m.Matches(std::to_string(0))); + + for (int i = 1; i <= num; ++i) { + EXPECT_TRUE(m.Matches(std::to_string(i))); + } + EXPECT_FALSE(m.Matches(std::to_string(num + 1))); +} +#endif + // Tests that AnyOf(m1, ..., mn) matches any value that matches at // least one of the given matchers. TEST(AnyOfTest, MatchesWhenAnyMatches) { @@ -2746,6 +2758,12 @@ TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); + AnyOfStringMatches( + 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", + "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", + "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", + "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", + "43", "44", "45", "46", "47", "48", "49", "50")); } // Tests the variadic version of the ElementsAreMatcher @@ -4570,7 +4588,7 @@ TEST(ResultOfTest, WorksForFunctors) { } // Tests that ResultOf(f, ...) compiles and works as expected when f is a -// functor with more then one operator() defined. ResultOf() must work +// functor with more than one operator() defined. ResultOf() must work // for each defined operator(). struct PolymorphicFunctor { typedef int result_type; @@ -6764,4 +6782,3 @@ TEST(NotTest, WorksOnMoveOnlyType) { } // namespace gmock_matchers_test } // namespace testing - -- cgit v0.12 From 0c17888bcfa7a05ae2cb14c1f5e2451ea9745211 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Thu, 19 Jul 2018 12:42:39 -0400 Subject: code sync --- googlemock/include/gmock/gmock-matchers.h | 12 ++++++++---- googlemock/test/gmock-matchers_test.cc | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index c94f582..7fd5787 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -5165,13 +5165,17 @@ std::string DescribeMatcher(const M& matcher, bool negation = false) { // Define variadic matcher versions. They are overloaded in // gmock-generated-matchers.h for the cases supported by pre C++11 compilers. template -internal::AllOfMatcher AllOf(const Args&... matchers) { - return internal::AllOfMatcher(matchers...); +internal::AllOfMatcher::type...> AllOf( + const Args&... matchers) { + return internal::AllOfMatcher::type...>( + matchers...); } template -internal::AnyOfMatcher AnyOf(const Args&... matchers) { - return internal::AnyOfMatcher(matchers...); +internal::AnyOfMatcher::type...> AnyOf( + const Args&... matchers) { + return internal::AnyOfMatcher::type...>( + matchers...); } template diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index a451842..f9dfd3c 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2795,6 +2795,7 @@ TEST(ElementsAreTest, HugeMatcherUnordered) { #endif // GTEST_LANG_CXX11 + // Tests that AnyOf(m1, ..., mn) describes itself properly. TEST(AnyOfTest, CanDescribeSelf) { Matcher m; -- cgit v0.12 From 2eb43960076417a3dca33ea5ad58e3e9feaee6e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=9C=E4=BF=AE=E6=9D=8F?= Date: Fri, 20 Jul 2018 06:15:13 +0800 Subject: =?UTF-8?q?Replace=20"=E2=80=A6"=20with=20"..."(three=20dots)=20to?= =?UTF-8?q?=20fix=20warning=20C4819=20in=20Visual=20Studio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- googlemock/docs/CookBook.md | 4 ++-- googlemock/include/gmock/gmock-generated-function-mockers.h.pump | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/googlemock/docs/CookBook.md b/googlemock/docs/CookBook.md index bd9f026..8809b0e 100644 --- a/googlemock/docs/CookBook.md +++ b/googlemock/docs/CookBook.md @@ -2247,7 +2247,7 @@ enum class AccessLevel { kInternal, kPublic }; class Buzz { public: - explicit Buzz(AccessLevel access) { … } + explicit Buzz(AccessLevel access) { ... } ... }; @@ -2320,7 +2320,7 @@ Note that `ByMove()` is essential here - if you drop it, the code won’t compil Quiz time! What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write -`….WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first +`.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))` can only be run once. diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index efcb3e8..9865922 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -114,7 +114,7 @@ class FunctionMocker : public // // class MockClass { // // Overload 1 -// MockSpec gmock_GetName() { … } +// MockSpec gmock_GetName() { ... } // // Overload 2. Declared const so that the compiler will generate an // // error when trying to resolve between this and overload 4 in // // 'gmock_GetName(WithoutMatchers(), nullptr)'. @@ -125,7 +125,7 @@ class FunctionMocker : public // } // // // Overload 3 -// const string& gmock_GetName() const { … } +// const string& gmock_GetName() const { ... } // // Overload 4 // MockSpec gmock_GetName( // const WithoutMatchers&, const Function*) const { -- cgit v0.12 From a02af2f689426aa9622b06643f53ed27fa6dc8a5 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 20 Jul 2018 11:28:58 -0400 Subject: code merge --- googlemock/include/gmock/gmock-matchers.h | 14 ++++++++++++++ googlemock/test/gmock-matchers_test.cc | 5 ++++- googletest/include/gtest/internal/gtest-port.h | 4 ---- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 7fd5787..eb09613 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -4529,6 +4529,20 @@ Property(PropertyType (Class::*property)() const &, property, MatcherCast(matcher))); } + +// Three-argument form for reference-qualified member functions. +template +inline PolymorphicMatcher > +Property(const std::string& property_name, + PropertyType (Class::*property)() const &, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher( + internal::PropertyMatcher( + property_name, property, + MatcherCast(matcher))); +} #endif // Creates a matcher that matches an object iff the result of applying diff --git a/googlemock/test/gmock-matchers_test.cc b/googlemock/test/gmock-matchers_test.cc index f9dfd3c..9f1a547 100644 --- a/googlemock/test/gmock-matchers_test.cc +++ b/googlemock/test/gmock-matchers_test.cc @@ -2795,7 +2795,6 @@ TEST(ElementsAreTest, HugeMatcherUnordered) { #endif // GTEST_LANG_CXX11 - // Tests that AnyOf(m1, ..., mn) describes itself properly. TEST(AnyOfTest, CanDescribeSelf) { Matcher m; @@ -4239,13 +4238,17 @@ TEST(PropertyTest, WorksForReferenceToConstProperty) { // ref-qualified. TEST(PropertyTest, WorksForRefQualifiedProperty) { Matcher m = Property(&AClass::s_ref, StartsWith("hi")); + Matcher m_with_name = + Property("s", &AClass::s_ref, StartsWith("hi")); AClass a; a.set_s("hill"); EXPECT_TRUE(m.Matches(a)); + EXPECT_TRUE(m_with_name.Matches(a)); a.set_s("hole"); EXPECT_FALSE(m.Matches(a)); + EXPECT_FALSE(m_with_name.Matches(a)); } #endif diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index bc35c34..dbe703b 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -522,11 +522,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING -// The user didn't tell us whether ::string is available, so we need -// to figure it out. - # define GTEST_HAS_GLOBAL_STRING 0 - #endif // GTEST_HAS_GLOBAL_STRING #ifndef GTEST_HAS_STD_WSTRING -- cgit v0.12 From baf2115a592758f207c52dd95db42b1962c7aac7 Mon Sep 17 00:00:00 2001 From: Stian Valle Date: Sat, 21 Jul 2018 15:29:58 +0200 Subject: Update primer.md --- googletest/docs/primer.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index f7f26eb..81d8be4 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -203,7 +203,7 @@ for more details. If you're working with floating point numbers, you may want to use the floating point variations of some of these macros in order to avoid problems caused by -rounding. See [Advanced googletest Topics](advanced) for details. +rounding. See [Advanced googletest Topics](advanced.md) for details. Macros in this section work with both narrow and wide string objects (`string` and `wstring`). @@ -222,15 +222,15 @@ two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. | Fatal assertion | Nonfatal assertion | Verifies | | ----------------------- | ----------------------- | ---------------------- | | `ASSERT_STREQ(str1, | `EXPECT_STREQ(str1, | the two C strings have | -: str2);` : str2);` : the same content : +| str2);` | str2);` | the same content | | `ASSERT_STRNE(str1, | `EXPECT_STRNE(str1, | the two C strings have | -: str2);` : str2);` : different contents : +| str2);` | str2);` | different contents | | `ASSERT_STRCASEEQ(str1, | `EXPECT_STRCASEEQ(str1, | the two C strings have | -: str2);` : str2);` : the same content, : -: : : ignoring case : +| str2);` | str2);` | the same content, | +| | | ignoring case | | `ASSERT_STRCASENE(str1, | `EXPECT_STRCASENE(str1, | the two C strings have | -: str2);` : str2);` : different contents, : -: : : ignoring case : +| str2);` | str2);` | different contents, | +| | | ignoring case | Note that "CASE" in an assertion name means that case is ignored. A `NULL` pointer and an empty string are considered *different*. -- cgit v0.12 From 7abf99d941ba0c865114702bff4b4e88b3e34564 Mon Sep 17 00:00:00 2001 From: Stian Valle Date: Sat, 21 Jul 2018 15:40:57 +0200 Subject: Update primer.md --- googletest/docs/primer.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 81d8be4..7e03112 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -219,18 +219,18 @@ as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now The assertions in this group compare two **C strings**. If you want to compare two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. -| Fatal assertion | Nonfatal assertion | Verifies | -| ----------------------- | ----------------------- | ---------------------- | -| `ASSERT_STREQ(str1, | `EXPECT_STREQ(str1, | the two C strings have | -| str2);` | str2);` | the same content | -| `ASSERT_STRNE(str1, | `EXPECT_STRNE(str1, | the two C strings have | -| str2);` | str2);` | different contents | -| `ASSERT_STRCASEEQ(str1, | `EXPECT_STRCASEEQ(str1, | the two C strings have | -| str2);` | str2);` | the same content, | -| | | ignoring case | -| `ASSERT_STRCASENE(str1, | `EXPECT_STRCASENE(str1, | the two C strings have | -| str2);` | str2);` | different contents, | -| | | ignoring case | +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------------ | ------------------------ | ---------------------- | +| `ASSERT_STREQ(str1,` | `EXPECT_STREQ(str1,` | the two C strings have | +| `str2);` | `str2);` | the same content | +| `ASSERT_STRNE(str1,` | `EXPECT_STRNE(str1,` | the two C strings have | +| `str2);` | `str2);` | different contents | +| `ASSERT_STRCASEEQ(str1,` | `EXPECT_STRCASEEQ(str1,` | the two C strings have | +| `str2);` | `str2);` | the same content, | +| | | ignoring case | +| `ASSERT_STRCASENE(str1,` | `EXPECT_STRCASENE(str1,` | the two C strings have | +| `str2);` | `str2);` | different contents, | +| | | ignoring case | Note that "CASE" in an assertion name means that case is ignored. A `NULL` pointer and an empty string are considered *different*. -- cgit v0.12 From bb9fc6f66e4954576a51cc05c99f01ff97c2da29 Mon Sep 17 00:00:00 2001 From: Stian Valle Date: Sat, 21 Jul 2018 15:50:45 +0200 Subject: Update primer.md --- googletest/docs/primer.md | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 7e03112..260d50b 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -219,18 +219,12 @@ as `ASSERT_EQ(expected, actual)`, so lots of existing code uses this order. Now The assertions in this group compare two **C strings**. If you want to compare two `string` objects, use `EXPECT_EQ`, `EXPECT_NE`, and etc instead. -| Fatal assertion | Nonfatal assertion | Verifies | -| ------------------------ | ------------------------ | ---------------------- | -| `ASSERT_STREQ(str1,` | `EXPECT_STREQ(str1,` | the two C strings have | -| `str2);` | `str2);` | the same content | -| `ASSERT_STRNE(str1,` | `EXPECT_STRNE(str1,` | the two C strings have | -| `str2);` | `str2);` | different contents | -| `ASSERT_STRCASEEQ(str1,` | `EXPECT_STRCASEEQ(str1,` | the two C strings have | -| `str2);` | `str2);` | the same content, | -| | | ignoring case | -| `ASSERT_STRCASENE(str1,` | `EXPECT_STRCASENE(str1,` | the two C strings have | -| `str2);` | `str2);` | different contents, | -| | | ignoring case | +| Fatal assertion | Nonfatal assertion | Verifies | +| ------------------------------- | ------------------------------- | -------------------------------------------------------- | +| `ASSERT_STREQ(str1, str2);` | `EXPECT_STREQ(str1, str2);` | the two C strings have the same content | +| `ASSERT_STRNE(str1, str2);` | `EXPECT_STRNE(str1, str2);` | the two C strings have different contents | +| `ASSERT_STRCASEEQ(str1, str2);` | `EXPECT_STRCASEEQ(str1, str2);` | the two C strings have the same content, ignoring case | +| `ASSERT_STRCASENE(str1, str2);` | `EXPECT_STRCASENE(str1, str2);` | the two C strings have different contents, ignoring case | Note that "CASE" in an assertion name means that case is ignored. A `NULL` pointer and an empty string are considered *different*. -- cgit v0.12 From ed1edf641dc5a04dc559df763ca71a5d6d05d939 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 25 Jul 2018 10:24:13 -0400 Subject: Formatting changes, code sync --- googlemock/test/gmock_stress_test.cc | 3 +-- googletest/include/gtest/internal/gtest-string.h | 3 +-- googletest/test/gtest_prod_test.cc | 2 +- googletest/test/gtest_unittest.cc | 4 ++-- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/googlemock/test/gmock_stress_test.cc b/googlemock/test/gmock_stress_test.cc index b9fdc45..e4e61f0 100644 --- a/googlemock/test/gmock_stress_test.cc +++ b/googlemock/test/gmock_stress_test.cc @@ -33,13 +33,12 @@ // threads concurrently. #include "gmock/gmock.h" - #include "gtest/gtest.h" namespace testing { namespace { -// From "gtest/internal/gtest-port.h". +// From gtest-port.h. using ::testing::internal::ThreadWithParam; // The maximum number of test threads (not including helper threads) diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 71eb840..64da26c 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -34,8 +34,7 @@ // Google Test. They are subject to change without notice. They should not used // by code external to Google Test. // -// This header file is #included by -// gtest/internal/gtest-internal.h. +// This header file is #included by gtest-internal.h. // It should not be #included by other files. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ diff --git a/googletest/test/gtest_prod_test.cc b/googletest/test/gtest_prod_test.cc index dfb9998..c5cceab 100644 --- a/googletest/test/gtest_prod_test.cc +++ b/googletest/test/gtest_prod_test.cc @@ -29,7 +29,7 @@ // // Author: wan@google.com (Zhanyong Wan) // -// Unit test for gtest/gtest_prod.h. +// Unit test for gtest_prod.h. #include "production.h" #include "gtest/gtest.h" diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 39b6841..8ebb667 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -35,8 +35,8 @@ #include "gtest/gtest.h" // Verifies that the command line flag variables can be accessed in -// code once "gtest/gtest.h" has been -// #included. Do not move it after other gtest #includes. +// 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) -- cgit v0.12 From 309e8a271e9aca1ef4aab899ce5d2d07c42123bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20K=C4=85kol?= Date: Wed, 25 Jul 2018 19:19:26 +0200 Subject: Updated broken and outdated URLs --- .travis.yml | 2 +- googlemock/docs/ForDummies.md | 2 +- googlemock/docs/FrequentlyAskedQuestions.md | 2 +- googlemock/scripts/upload.py | 8 ++++---- googlemock/src/gmock_main.cc | 2 +- googletest/cmake/internal_utils.cmake | 2 +- googletest/docs/XcodeGuide.md | 8 ++++---- googletest/docs/advanced.md | 16 ++++++++-------- googletest/docs/faq.md | 6 +++--- googletest/docs/primer.md | 6 +++--- googletest/include/gtest/internal/gtest-port.h | 6 +++--- googletest/scripts/upload.py | 8 ++++---- googletest/src/gtest-port.cc | 2 +- googletest/test/gtest-death-test_test.cc | 2 +- googletest/xcode/Config/DebugProject.xcconfig | 2 +- googletest/xcode/Config/FrameworkTarget.xcconfig | 2 +- googletest/xcode/Config/General.xcconfig | 2 +- googletest/xcode/Config/ReleaseProject.xcconfig | 2 +- googletest/xcode/Config/StaticLibraryTarget.xcconfig | 2 +- 19 files changed, 41 insertions(+), 41 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1200c67..0e17bc2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ # Build matrix / environment variable are explained on: -# http://about.travis-ci.org/docs/user/build-configuration/ +# https://docs.travis-ci.com/user/customizing-the-build/ # This file can be validated on: # http://lint.travis-ci.org/ diff --git a/googlemock/docs/ForDummies.md b/googlemock/docs/ForDummies.md index 1e0fd41..566a34e 100644 --- a/googlemock/docs/ForDummies.md +++ b/googlemock/docs/ForDummies.md @@ -170,7 +170,7 @@ Admittedly, this test is contrived and doesn't do much. You can easily achieve t ## Using Google Mock with Any Testing Framework ## If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: +[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to: ``` int main(int argc, char** argv) { // The following line causes Google Mock to throw an exception on failure, diff --git a/googlemock/docs/FrequentlyAskedQuestions.md b/googlemock/docs/FrequentlyAskedQuestions.md index 23f7da0..9008c63 100644 --- a/googlemock/docs/FrequentlyAskedQuestions.md +++ b/googlemock/docs/FrequentlyAskedQuestions.md @@ -528,7 +528,7 @@ interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly. This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) +[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it excellently. Check it out. ## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## diff --git a/googlemock/scripts/upload.py b/googlemock/scripts/upload.py index 6e6f9a1..95239dc 100755 --- a/googlemock/scripts/upload.py +++ b/googlemock/scripts/upload.py @@ -242,7 +242,7 @@ class AbstractRpcServer(object): The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user - (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). + (see https://developers.google.com/identity/protocols/AuthForInstalledApps). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. @@ -506,7 +506,7 @@ def EncodeMultipartFormData(fields, files): (content_type, body) ready for httplib.HTTP instance. Source: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 + https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' @@ -807,7 +807,7 @@ class SubversionVCS(VersionControlSystem): # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team - # who had the same problem (http://reviews.review-board.org/r/276/). + # who had the same problem (https://reviews.reviewboard.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords @@ -860,7 +860,7 @@ class SubversionVCS(VersionControlSystem): status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See - # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt + # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): diff --git a/googlemock/src/gmock_main.cc b/googlemock/src/gmock_main.cc index bd5be03..6182159 100644 --- a/googlemock/src/gmock_main.cc +++ b/googlemock/src/gmock_main.cc @@ -37,7 +37,7 @@ // causes a link error when _tmain is defined in a static library and UNICODE // is enabled. For this reason instead of _tmain, main function is used on // Windows. See the following link to track the current status of this bug: -// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT +// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library // NOLINT #if GTEST_OS_WINDOWS_MOBILE # include // NOLINT diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index be7af38..086f51c 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -20,7 +20,7 @@ macro(fix_default_compiler_settings_) if (MSVC) # For MSVC, CMake sets certain flags to defaults we want to override. # This replacement code is taken from sample in the CMake Wiki at - # http://www.cmake.org/Wiki/CMake_FAQ#Dynamic_Replace. + # https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace. foreach (flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) diff --git a/googletest/docs/XcodeGuide.md b/googletest/docs/XcodeGuide.md index 117265c..1c60a33 100644 --- a/googletest/docs/XcodeGuide.md +++ b/googletest/docs/XcodeGuide.md @@ -6,7 +6,7 @@ This guide will explain how to use the Google Testing Framework in your Xcode pr Here is the quick guide for using Google Test in your Xcode project. - 1. Download the source from the [website](http://code.google.com/p/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`. + 1. Download the source from the [website](https://github.com/google/googletest) using this command: `svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only`. 1. Open up the `gtest.xcodeproj` in the `googletest-read-only/xcode/` directory and build the gtest.framework. 1. Create a new "Shell Tool" target in your Xcode project called something like "UnitTests". 1. Add the gtest.framework to your project and add it to the "Link Binary with Libraries" build phase of "UnitTests". @@ -18,7 +18,7 @@ The following sections further explain each of the steps listed above in depth, # Get the Source # -Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](http://code.google.com/p/googletest/source/checkout">svn), you can get the code from anonymous SVN with this command: +Currently, the gtest.framework discussed here isn't available in a tagged release of Google Test, it is only available in the trunk. As explained at the Google Test [site](https://github.com/google/googletest), you can get the code from anonymous SVN with this command: ``` svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only @@ -28,7 +28,7 @@ Alternatively, if you are working with Subversion in your own code base, you can To use `svn:externals`, decide where you would like to have the external source reside. You might choose to put the external source inside the trunk, because you want it to be part of the branch when you make a release. However, keeping it outside the trunk in a version-tagged directory called something like `third-party/googletest/1.0.1`, is another option. Once the location is established, use `svn propedit svn:externals _directory_` to set the svn:externals property on a directory in your repository. This directory won't contain the code, but be its versioned parent directory. -The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `http://googletest.googlecode.com/svn/tags/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`). +The command `svn propedit` will bring up your Subversion editor, making editing the long, (potentially multi-line) property simpler. This same method can be used to check out a tagged branch, by using the appropriate URL (e.g. `https://github.com/google/googletest/releases/tag/release-1.0.1`). Additionally, the svn:externals property allows the specification of a particular revision of the trunk with the `-r_##_` option (e.g. `externals/src/googletest -r60 http://googletest.googlecode.com/svn/trunk`). Here is an example of using the svn:externals properties on a trunk (read via `svn propget`) of a project. This value checks out a copy of Google Test into the `trunk/externals/src/googletest/` directory. @@ -90,4 +90,4 @@ The Debugger has exited with status 0. # Summary # -Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. \ No newline at end of file +Unit testing is a valuable way to ensure your data model stays valid even during rapid development or refactoring. The Google Testing Framework is a great unit testing framework for C and C++ which integrates well with an Xcode development environment. diff --git a/googletest/docs/advanced.md b/googletest/docs/advanced.md index 6883784..feb8ad6 100644 --- a/googletest/docs/advanced.md +++ b/googletest/docs/advanced.md @@ -154,7 +154,7 @@ c is 10 > `ASSERT_PRED*` or `EXPECT_PRED*`, please see > [this](faq#OverloadedPredicate) for how to resolve it. > 1. Currently we only provide predicate assertions of arity <= 5. If you need -> a higher-arity assertion, let [us](http://g/opensource-gtest) know. +> a higher-arity assertion, let [us](https://github.com/google/googletest/issues) know. **Availability**: Linux, Windows, Mac. @@ -382,7 +382,7 @@ Verifies that `val1` is less than, or almost equal to, `val2`. You can replace ### Asserting Using gMock Matchers -Google-developed C++ mocking framework [gMock](http://go/gmock) comes with a +Google-developed C++ mocking framework [gMock](../../googlemock) comes with a library of matchers for validating arguments passed to mock objects. A gMock *matcher* is basically a predicate that knows how to describe itself. It can be used in these assertion macros: @@ -402,17 +402,17 @@ using ::testing::StartsWith; EXPECT_THAT(Foo(), StartsWith("Hello")); ``` -Read this [recipe](http://go/gmockguide#using-matchers-in-gunit-assertions) in +Read this [recipe](../../googlemock/docs/CookBook.md#using-matchers-in-google-test-assertions) in the gMock Cookbook for more details. gMock has a rich set of matchers. You can do many things googletest cannot do alone with them. For a list of matchers gMock provides, read -[this](http://go/gmockguide#using-matchers). Especially useful among them are -some [protocol buffer matchers](http://go/protomatchers). It's easy to write -your [own matchers](http://go/gmockguide#NewMatchers) too. +[this](../../googlemock/docs/CookBook.md#using-matchers). Especially useful among them are +some [protocol buffer matchers](https://github.com/google/nucleus/blob/master/nucleus/testing/protocol-buffer-matchers.h). It's easy to write +your [own matchers](../../googlemock/docs/CookBook.md#writing-new-matchers-quickly) too. For example, you can use gMock's -[EqualsProto](http://cs/#piper///depot/google3/testing/base/public/gmock_utils/protocol-buffer-matchers.h) +[EqualsProto](https://github.com/google/nucleus/blob/master/nucleus/testing/protocol-buffer-matchers.h) to compare protos in your tests: ```c++ @@ -433,7 +433,7 @@ and you're ready to go. (Please read the [previous](#AssertThat) section first if you haven't.) -You can use the gMock [string matchers](http://go/gmockguide#string-matchers) +You can use the gMock [string matchers](../../googlemock/docs/CheatSheet.md#string-matchers) with `EXPECT_THAT()` or `ASSERT_THAT()` to do more string comparison tricks (sub-string, prefix, suffix, regular expression, and etc). For example, diff --git a/googletest/docs/faq.md b/googletest/docs/faq.md index dad2836..d613f7b 100644 --- a/googletest/docs/faq.md +++ b/googletest/docs/faq.md @@ -162,7 +162,7 @@ result, any in-memory side effects they incur are observable in their respective sub-processes, but not in the parent process. You can think of them as running in a parallel universe, more or less. -In particular, if you use [gMock](http://go/gmock) and the death test statement +In particular, if you use [gMock](../../googlemock) and the death test statement invokes some mock methods, the parent process will think the calls have never occurred. Therefore, you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH` macro. @@ -289,7 +289,7 @@ Please make sure you have read [this](advanced.md#how-it-works). In particular, death tests don't like having multiple threads in the parent process. So the first thing you can try is to eliminate creating threads outside -of `EXPECT_DEATH()`. For example, you may want to use [mocks](http://go/gmock) +of `EXPECT_DEATH()`. For example, you may want to use [mocks](../../googlemock) or fake objects instead of real ones in your tests. Sometimes this is impossible as some library you must use may be creating @@ -704,7 +704,7 @@ mistake in production. Such cleverness also leads to advise against the practice, and googletest doesn't provide a way to do it. In general, the recommended way to cause the code to behave differently under -test is [Dependency Injection](http://go/dependency-injection). You can inject +test is [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection). You can inject different functionality from the test and from the production code. Since your production code doesn't link in the for-test logic at all (the [`testonly`](http://go/testonly) attribute for BUILD targets helps to ensure diff --git a/googletest/docs/primer.md b/googletest/docs/primer.md index 260d50b..02dea42 100644 --- a/googletest/docs/primer.md +++ b/googletest/docs/primer.md @@ -5,8 +5,8 @@ *googletest* helps you write better C++ tests. -googletest is a testing framework developed by the [Testing -Technology](http://engdoc/eng/testing/TT/) team with Google's specific +googletest is a testing framework developed by the Testing +Technology team with Google's specific requirements and constraints in mind. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it supports *any* kind of tests, not just unit tests. @@ -75,7 +75,7 @@ the terms: Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term :----------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :---------------------------------- Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case](http://glossary.istqb.org/search/test%20case) -A set of several tests related to one component | [TestCase](https://g3doc.corp.google.com/third_party/googletest/googletest/g3doc/primer.md#basic-concepts) | [TestSuite](http://glossary.istqb.org/search/test%20suite) +A set of several tests related to one component | [TestCase](#basic-concepts) | [TestSuite](http://glossary.istqb.org/search/test%20suite) ## Basic Concepts diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index dbe703b..cfe5515 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -379,7 +379,7 @@ #if GTEST_LANG_CXX11 # define GTEST_HAS_STD_TUPLE_ 1 # if defined(__clang__) -// Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include +// Inspired by https://clang.llvm.org/docs/LanguageExtensions.html#include-file-checking-macros # if defined(__has_include) && !__has_include() # undef GTEST_HAS_STD_TUPLE_ # endif @@ -391,7 +391,7 @@ # elif defined(__GLIBCXX__) // Inspired by boost/config/stdlib/libstdcpp3.hpp, // http://gcc.gnu.org/gcc-4.2/changes.html and -// http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x +// https://web.archive.org/web/20140227044429/gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) # undef GTEST_HAS_STD_TUPLE_ # endif @@ -1799,7 +1799,7 @@ class GTEST_API_ Mutex { // Initializes owner_thread_id_ and critical_section_ in static mutexes. void ThreadSafeLazyInit(); - // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx, + // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503, // we assume that 0 is an invalid value for thread IDs. unsigned int owner_thread_id_; diff --git a/googletest/scripts/upload.py b/googletest/scripts/upload.py index 81e8e04..c852e4c 100755 --- a/googletest/scripts/upload.py +++ b/googletest/scripts/upload.py @@ -242,7 +242,7 @@ class AbstractRpcServer(object): The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user - (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). + (see https://developers.google.com/identity/protocols/AuthForInstalledApps). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. @@ -506,7 +506,7 @@ def EncodeMultipartFormData(fields, files): (content_type, body) ready for httplib.HTTP instance. Source: - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 + https://web.archive.org/web/20160116052001/code.activestate.com/recipes/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' @@ -807,7 +807,7 @@ class SubversionVCS(VersionControlSystem): # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team - # who had the same problem (http://reviews.review-board.org/r/276/). + # who had the same problem (https://reviews.reviewboard.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords @@ -860,7 +860,7 @@ class SubversionVCS(VersionControlSystem): status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See - # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt + # https://web.archive.org/web/20090918234815/svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index f8a0ad6..5fbb08b 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -264,7 +264,7 @@ Mutex::~Mutex() { // to clean them up. // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires // nothing to clean it up but is available only on Vista and later. - // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx + // https://docs.microsoft.com/en-us/windows/desktop/Sync/slim-reader-writer--srw--locks if (type_ == kDynamic) { ::DeleteCriticalSection(critical_section_); delete critical_section_; diff --git a/googletest/test/gtest-death-test_test.cc b/googletest/test/gtest-death-test_test.cc index 37261cb..9d8f13c 100644 --- a/googletest/test/gtest-death-test_test.cc +++ b/googletest/test/gtest-death-test_test.cc @@ -784,7 +784,7 @@ static void TestExitMacros() { // Of all signals effects on the process exit code, only those of SIGABRT // are documented on Windows. - // See http://msdn.microsoft.com/en-us/library/dwwzkt4c(VS.71).aspx. + // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c. EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), "") << "b_ar"; # elif !GTEST_OS_FUCHSIA diff --git a/googletest/xcode/Config/DebugProject.xcconfig b/googletest/xcode/Config/DebugProject.xcconfig index 3d68157..645701e 100644 --- a/googletest/xcode/Config/DebugProject.xcconfig +++ b/googletest/xcode/Config/DebugProject.xcconfig @@ -5,7 +5,7 @@ // examples. It is set in the "Based On:" dropdown in the "Project" info // dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // #include "General.xcconfig" diff --git a/googletest/xcode/Config/FrameworkTarget.xcconfig b/googletest/xcode/Config/FrameworkTarget.xcconfig index 357b1c8..77081fb 100644 --- a/googletest/xcode/Config/FrameworkTarget.xcconfig +++ b/googletest/xcode/Config/FrameworkTarget.xcconfig @@ -4,7 +4,7 @@ // These are Framework target settings for the gtest framework and examples. It // is set in the "Based On:" dropdown in the "Target" info dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // // Dynamic libs need to be position independent diff --git a/googletest/xcode/Config/General.xcconfig b/googletest/xcode/Config/General.xcconfig index f23e322..1aba486 100644 --- a/googletest/xcode/Config/General.xcconfig +++ b/googletest/xcode/Config/General.xcconfig @@ -4,7 +4,7 @@ // These are General configuration settings for the gtest framework and // examples. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // // Build for PPC and Intel, 32- and 64-bit diff --git a/googletest/xcode/Config/ReleaseProject.xcconfig b/googletest/xcode/Config/ReleaseProject.xcconfig index 5349f0a..df9a38f 100644 --- a/googletest/xcode/Config/ReleaseProject.xcconfig +++ b/googletest/xcode/Config/ReleaseProject.xcconfig @@ -5,7 +5,7 @@ // and examples. It is set in the "Based On:" dropdown in the "Project" info // dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // #include "General.xcconfig" diff --git a/googletest/xcode/Config/StaticLibraryTarget.xcconfig b/googletest/xcode/Config/StaticLibraryTarget.xcconfig index 3922fa5..d2424fe 100644 --- a/googletest/xcode/Config/StaticLibraryTarget.xcconfig +++ b/googletest/xcode/Config/StaticLibraryTarget.xcconfig @@ -4,7 +4,7 @@ // These are static library target settings for libgtest.a. It // is set in the "Based On:" dropdown in the "Target" info dialog. // This file is based on the Xcode Configuration files in: -// http://code.google.com/p/google-toolbox-for-mac/ +// https://github.com/google/google-toolbox-for-mac // // Static libs can be included in bundles so make them position independent -- cgit v0.12 From 984cba30ed10622122c12960b4914656fc770e04 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 27 Jul 2018 11:15:08 -0400 Subject: Formatting changes for automatic code management --- googlemock/include/gmock/gmock-actions.h | 2 ++ googlemock/include/gmock/gmock-cardinalities.h | 2 ++ googlemock/include/gmock/gmock-generated-actions.h | 2 ++ googlemock/include/gmock/gmock-generated-actions.h.pump | 2 ++ googlemock/include/gmock/gmock-generated-function-mockers.h | 2 ++ googlemock/include/gmock/gmock-generated-function-mockers.h.pump | 4 +++- googlemock/include/gmock/gmock-generated-matchers.h | 2 ++ googlemock/include/gmock/gmock-generated-matchers.h.pump | 2 ++ googlemock/include/gmock/gmock-generated-nice-strict.h | 2 ++ googlemock/include/gmock/gmock-generated-nice-strict.h.pump | 2 ++ googlemock/include/gmock/gmock-matchers.h | 2 ++ googlemock/include/gmock/gmock-more-actions.h | 2 ++ googlemock/include/gmock/gmock-more-matchers.h | 2 ++ googlemock/include/gmock/gmock-spec-builders.h | 2 ++ googlemock/include/gmock/gmock.h | 2 ++ googlemock/include/gmock/internal/custom/gmock-generated-actions.h | 2 ++ .../include/gmock/internal/custom/gmock-generated-actions.h.pump | 2 ++ googlemock/include/gmock/internal/custom/gmock-matchers.h | 2 ++ googlemock/include/gmock/internal/custom/gmock-port.h | 2 ++ googlemock/include/gmock/internal/gmock-generated-internal-utils.h | 2 ++ .../include/gmock/internal/gmock-generated-internal-utils.h.pump | 2 ++ googlemock/include/gmock/internal/gmock-internal-utils.h | 2 ++ googlemock/include/gmock/internal/gmock-port.h | 2 ++ googletest/include/gtest/gtest-death-test.h | 1 + googletest/include/gtest/gtest-message.h | 2 ++ googletest/include/gtest/gtest-param-test.h | 1 + googletest/include/gtest/gtest-param-test.h.pump | 1 + googletest/include/gtest/gtest-printers.h | 2 ++ googletest/include/gtest/gtest-spi.h | 2 ++ googletest/include/gtest/gtest-test-part.h | 2 ++ googletest/include/gtest/gtest-typed-test.h | 2 ++ googletest/include/gtest/gtest.h | 2 ++ googletest/include/gtest/gtest_pred_impl.h | 2 ++ googletest/include/gtest/gtest_prod.h | 1 + googletest/include/gtest/internal/gtest-death-test-internal.h | 1 + googletest/include/gtest/internal/gtest-filepath.h | 2 ++ googletest/include/gtest/internal/gtest-internal.h | 2 ++ googletest/include/gtest/internal/gtest-linked_ptr.h | 2 ++ googletest/include/gtest/internal/gtest-param-util-generated.h | 2 ++ googletest/include/gtest/internal/gtest-param-util-generated.h.pump | 2 ++ googletest/include/gtest/internal/gtest-param-util.h | 2 ++ googletest/include/gtest/internal/gtest-port.h | 2 ++ googletest/include/gtest/internal/gtest-string.h | 2 ++ googletest/include/gtest/internal/gtest-tuple.h | 2 ++ googletest/include/gtest/internal/gtest-tuple.h.pump | 2 ++ googletest/include/gtest/internal/gtest-type-util.h | 2 ++ googletest/include/gtest/internal/gtest-type-util.h.pump | 2 ++ 47 files changed, 90 insertions(+), 1 deletion(-) diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index a2784f6..42648ad 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -33,6 +33,8 @@ // // This file implements some commonly used actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-cardinalities.h b/googlemock/include/gmock/gmock-cardinalities.h index fc315f9..2ce16af 100644 --- a/googlemock/include/gmock/gmock-cardinalities.h +++ b/googlemock/include/gmock/gmock-cardinalities.h @@ -35,6 +35,8 @@ // cardinalities can be defined by the user implementing the // CardinalityInterface interface if necessary. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/googlemock/include/gmock/gmock-generated-actions.h b/googlemock/include/gmock/gmock-generated-actions.h index 7728d74..4ce7d35 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h +++ b/googlemock/include/gmock/gmock-generated-actions.h @@ -37,6 +37,8 @@ // // This file implements some commonly used variadic actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-generated-actions.h.pump b/googlemock/include/gmock/gmock-generated-actions.h.pump index 8bafa47..4ec6679 100644 --- a/googlemock/include/gmock/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/gmock-generated-actions.h.pump @@ -39,6 +39,8 @@ $$}} This meta comment fixes auto-indentation in editors. // // This file implements some commonly used variadic actions. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h b/googlemock/include/gmock/gmock-generated-function-mockers.h index b8bf7a5..0474c89 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h @@ -37,6 +37,8 @@ // // This file implements function mockers of various arities. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ diff --git a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump index 6426d9a..f6e1781 100644 --- a/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/googlemock/include/gmock/gmock-generated-function-mockers.h.pump @@ -38,6 +38,8 @@ $var n = 10 $$ The maximum arity we support. // // This file implements function mockers of various arities. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ @@ -139,7 +141,7 @@ const MockType* AdjustConstness_const(const MockType* mock) { return mock; } -// Removes const from and returns the given pointer; this is a helper for the +// Removes const from and returns the given pointer; this is a helper for the // expectation setter method for parameterless matchers. template MockType* AdjustConstness_(const MockType* mock) { diff --git a/googlemock/include/gmock/gmock-generated-matchers.h b/googlemock/include/gmock/gmock-generated-matchers.h index 21af61b..0d46d23 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h +++ b/googlemock/include/gmock/gmock-generated-matchers.h @@ -35,6 +35,8 @@ // // This file implements some commonly used variadic matchers. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-generated-matchers.h.pump b/googlemock/include/gmock/gmock-generated-matchers.h.pump index 4b62844..9fe0fd7 100644 --- a/googlemock/include/gmock/gmock-generated-matchers.h.pump +++ b/googlemock/include/gmock/gmock-generated-matchers.h.pump @@ -37,6 +37,8 @@ $$ }} This line fixes auto-indentation of the following code in Emacs. // // This file implements some commonly used variadic matchers. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h b/googlemock/include/gmock/gmock-generated-nice-strict.h index 8e56873..96d6f39 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h @@ -63,6 +63,8 @@ // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ diff --git a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump index 2f443ae..7c2bf36 100644 --- a/googlemock/include/gmock/gmock-generated-nice-strict.h.pump +++ b/googlemock/include/gmock/gmock-generated-nice-strict.h.pump @@ -64,6 +64,8 @@ $var n = 10 $$ The maximum arity we support. // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index eb09613..adf4999 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -35,6 +35,8 @@ // matchers can be defined by the user implementing the // MatcherInterface interface if necessary. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-more-actions.h b/googlemock/include/gmock/gmock-more-actions.h index 3d387b6..1106818 100644 --- a/googlemock/include/gmock/gmock-more-actions.h +++ b/googlemock/include/gmock/gmock-more-actions.h @@ -33,6 +33,8 @@ // // This file implements some actions that depend on gmock-generated-actions.h. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-more-matchers.h b/googlemock/include/gmock/gmock-more-matchers.h index 6d810eb..6c6b3e3 100644 --- a/googlemock/include/gmock/gmock-more-matchers.h +++ b/googlemock/include/gmock/gmock-more-matchers.h @@ -36,6 +36,8 @@ // Note that tests are implemented in gmock-matchers_test.cc rather than // gmock-more-matchers-test.cc. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_GMOCK_MORE_MATCHERS_H_ #define GMOCK_GMOCK_MORE_MATCHERS_H_ diff --git a/googlemock/include/gmock/gmock-spec-builders.h b/googlemock/include/gmock/gmock-spec-builders.h index 090cff4..9670b59 100644 --- a/googlemock/include/gmock/gmock-spec-builders.h +++ b/googlemock/include/gmock/gmock-spec-builders.h @@ -57,6 +57,8 @@ // where all clauses are optional, and .InSequence()/.After()/ // .WillOnce() can appear any number of times. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ diff --git a/googlemock/include/gmock/gmock.h b/googlemock/include/gmock/gmock.h index 6ccb118..6330294 100644 --- a/googlemock/include/gmock/gmock.h +++ b/googlemock/include/gmock/gmock.h @@ -33,6 +33,8 @@ // // This is the main header file a user should include. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h index 7dc3b1a..92d910c 100644 --- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h +++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h @@ -2,6 +2,8 @@ // pump.py gmock-generated-actions.h.pump // DO NOT EDIT BY HAND!!! +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump index 03cfd8c..67c221f 100644 --- a/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump +++ b/googlemock/include/gmock/internal/custom/gmock-generated-actions.h.pump @@ -4,6 +4,8 @@ $$ it to callback-actions.h. $$ $var max_callback_arity = 5 $$}} This meta comment fixes auto-indentation in editors. + +// GOOGLETEST_CM0002 DO NOT DELETE #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-matchers.h b/googlemock/include/gmock/internal/custom/gmock-matchers.h index af8240e..b9b7e3f 100644 --- a/googlemock/include/gmock/internal/custom/gmock-matchers.h +++ b/googlemock/include/gmock/internal/custom/gmock-matchers.h @@ -33,6 +33,8 @@ // // Adds google3 callback support to CallableTraits. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_ diff --git a/googlemock/include/gmock/internal/custom/gmock-port.h b/googlemock/include/gmock/internal/custom/gmock-port.h index 9ce8bfe..ad9ae36 100644 --- a/googlemock/include/gmock/internal/custom/gmock-port.h +++ b/googlemock/include/gmock/internal/custom/gmock-port.h @@ -40,6 +40,8 @@ // // ** Custom implementation starts here ** +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h index cd94d64..c9bfbc8 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h @@ -38,6 +38,8 @@ // This file contains template meta-programming utility classes needed // for implementing Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ diff --git a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump index 800af17..f13151b 100644 --- a/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump +++ b/googlemock/include/gmock/internal/gmock-generated-internal-utils.h.pump @@ -39,6 +39,8 @@ $var n = 10 $$ The maximum arity we support. // This file contains template meta-programming utility classes needed // for implementing Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ diff --git a/googlemock/include/gmock/internal/gmock-internal-utils.h b/googlemock/include/gmock/internal/gmock-internal-utils.h index c5841ab..e0846d9 100644 --- a/googlemock/include/gmock/internal/gmock-internal-utils.h +++ b/googlemock/include/gmock/internal/gmock-internal-utils.h @@ -35,6 +35,8 @@ // Mock. They are subject to change without notice, so please DO NOT // USE THEM IN USER CODE. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ diff --git a/googlemock/include/gmock/internal/gmock-port.h b/googlemock/include/gmock/internal/gmock-port.h index cb37f26..79f4366 100644 --- a/googlemock/include/gmock/internal/gmock-port.h +++ b/googlemock/include/gmock/internal/gmock-port.h @@ -36,6 +36,8 @@ // end with _ are part of Google Mock's public API and can be used by // code outside Google Mock. +// GOOGLETEST_CM0002 DO NOT DELETE + #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ diff --git a/googletest/include/gtest/gtest-death-test.h b/googletest/include/gtest/gtest-death-test.h index 53f11d4..8add8c0 100644 --- a/googletest/include/gtest/gtest-death-test.h +++ b/googletest/include/gtest/gtest-death-test.h @@ -34,6 +34,7 @@ // This header file defines the public API for death tests. It is // #included by gtest.h so a user doesn't need to include this // directly. +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ diff --git a/googletest/include/gtest/gtest-message.h b/googletest/include/gtest/gtest-message.h index d7266ba..3e3870c 100644 --- a/googletest/include/gtest/gtest-message.h +++ b/googletest/include/gtest/gtest-message.h @@ -43,6 +43,8 @@ // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ diff --git a/googletest/include/gtest/gtest-param-test.h b/googletest/include/gtest/gtest-param-test.h index 8993c1c..3ea3338 100644 --- a/googletest/include/gtest/gtest-param-test.h +++ b/googletest/include/gtest/gtest-param-test.h @@ -38,6 +38,7 @@ // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/googletest/include/gtest/gtest-param-test.h.pump b/googletest/include/gtest/gtest-param-test.h.pump index 7b7243f..4dac9f2 100644 --- a/googletest/include/gtest/gtest-param-test.h.pump +++ b/googletest/include/gtest/gtest-param-test.h.pump @@ -37,6 +37,7 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ diff --git a/googletest/include/gtest/gtest-printers.h b/googletest/include/gtest/gtest-printers.h index 66d54b9..57eb5ae 100644 --- a/googletest/include/gtest/gtest-printers.h +++ b/googletest/include/gtest/gtest-printers.h @@ -96,6 +96,8 @@ // being defined as many user-defined container types don't have // value_type. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h index 0e5c10c..2a48cca 100644 --- a/googletest/include/gtest/gtest-spi.h +++ b/googletest/include/gtest/gtest-spi.h @@ -32,6 +32,8 @@ // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). +GOOGLETEST_CM0004 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/googletest/include/gtest/gtest-test-part.h b/googletest/include/gtest/gtest-test-part.h index 77eb844..301a012 100644 --- a/googletest/include/gtest/gtest-test-part.h +++ b/googletest/include/gtest/gtest-test-part.h @@ -30,6 +30,8 @@ // Author: mheule@google.com (Markus Heule) // +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ diff --git a/googletest/include/gtest/gtest-typed-test.h b/googletest/include/gtest/gtest-typed-test.h index 759d1db..00925af 100644 --- a/googletest/include/gtest/gtest-typed-test.h +++ b/googletest/include/gtest/gtest-typed-test.h @@ -29,6 +29,8 @@ // // Author: wan@google.com (Zhanyong Wan) +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ diff --git a/googletest/include/gtest/gtest.h b/googletest/include/gtest/gtest.h index 686750e..a6c674b 100644 --- a/googletest/include/gtest/gtest.h +++ b/googletest/include/gtest/gtest.h @@ -48,6 +48,8 @@ // registration from Barthelemy Dagenais' (barthelemy@prologique.com) // easyUnit framework. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/googletest/include/gtest/gtest_pred_impl.h b/googletest/include/gtest/gtest_pred_impl.h index c8be230..0c1105c 100644 --- a/googletest/include/gtest/gtest_pred_impl.h +++ b/googletest/include/gtest/gtest_pred_impl.h @@ -32,6 +32,8 @@ // // Implements a family of generic predicate assertion macros. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index 89314f4..21e211e 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -30,6 +30,7 @@ // Author: wan@google.com (Zhanyong Wan) // // Google C++ Testing and Mocking Framework definitions useful in production code. +GOOGLETEST_CM0003 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/googletest/include/gtest/internal/gtest-death-test-internal.h b/googletest/include/gtest/internal/gtest-death-test-internal.h index 949c429..719aee6 100644 --- a/googletest/include/gtest/internal/gtest-death-test-internal.h +++ b/googletest/include/gtest/internal/gtest-death-test-internal.h @@ -32,6 +32,7 @@ // // This header file defines internal utilities needed for implementing // death tests. They are subject to change without notice. +// GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ diff --git a/googletest/include/gtest/internal/gtest-filepath.h b/googletest/include/gtest/internal/gtest-filepath.h index 406597a..e18fe45 100644 --- a/googletest/include/gtest/internal/gtest-filepath.h +++ b/googletest/include/gtest/internal/gtest-filepath.h @@ -36,6 +36,8 @@ // This file is #included in gtest/internal/gtest-internal.h. // Do not include this header file separately! +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ diff --git a/googletest/include/gtest/internal/gtest-internal.h b/googletest/include/gtest/internal/gtest-internal.h index fc65b1f..45192e2 100644 --- a/googletest/include/gtest/internal/gtest-internal.h +++ b/googletest/include/gtest/internal/gtest-internal.h @@ -33,6 +33,8 @@ // This header file declares functions and macros used internally by // Google Test. They are subject to change without notice. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ diff --git a/googletest/include/gtest/internal/gtest-linked_ptr.h b/googletest/include/gtest/internal/gtest-linked_ptr.h index 3602942..8e1caa0 100644 --- a/googletest/include/gtest/internal/gtest-linked_ptr.h +++ b/googletest/include/gtest/internal/gtest-linked_ptr.h @@ -65,6 +65,8 @@ // TODO(wan@google.com): rename this to safe_linked_ptr to avoid // confusion with normal linked_ptr. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ diff --git a/googletest/include/gtest/internal/gtest-param-util-generated.h b/googletest/include/gtest/internal/gtest-param-util-generated.h index dcf90c2..ef22e89 100644 --- a/googletest/include/gtest/internal/gtest-param-util-generated.h +++ b/googletest/include/gtest/internal/gtest-param-util-generated.h @@ -43,6 +43,8 @@ // by the maximum arity of the implementation of tuple which is // currently set at 10. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/googletest/include/gtest/internal/gtest-param-util-generated.h.pump b/googletest/include/gtest/internal/gtest-param-util-generated.h.pump index d65086a..856caba 100644 --- a/googletest/include/gtest/internal/gtest-param-util-generated.h.pump +++ b/googletest/include/gtest/internal/gtest-param-util-generated.h.pump @@ -42,6 +42,8 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support. // by the maximum arity of the implementation of tuple which is // currently set at $maxtuple. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ diff --git a/googletest/include/gtest/internal/gtest-param-util.h b/googletest/include/gtest/internal/gtest-param-util.h index 3c80863..a69d5de 100644 --- a/googletest/include/gtest/internal/gtest-param-util.h +++ b/googletest/include/gtest/internal/gtest-param-util.h @@ -31,6 +31,8 @@ // Type and function utilities for implementing parameterized tests. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index dbe703b..1c0654c 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -40,6 +40,8 @@ // files are expected to #include this. Therefore, it cannot #include // any other Google Test header. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ diff --git a/googletest/include/gtest/internal/gtest-string.h b/googletest/include/gtest/internal/gtest-string.h index 64da26c..1d2436c 100644 --- a/googletest/include/gtest/internal/gtest-string.h +++ b/googletest/include/gtest/internal/gtest-string.h @@ -37,6 +37,8 @@ // This header file is #included by gtest-internal.h. // It should not be #included by other files. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ diff --git a/googletest/include/gtest/internal/gtest-tuple.h b/googletest/include/gtest/internal/gtest-tuple.h index e9b4053..e64cede 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h +++ b/googletest/include/gtest/internal/gtest-tuple.h @@ -35,6 +35,8 @@ // Implements a subset of TR1 tuple needed by Google Test and Google Mock. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/googletest/include/gtest/internal/gtest-tuple.h.pump b/googletest/include/gtest/internal/gtest-tuple.h.pump index 429ddfe..2736360 100644 --- a/googletest/include/gtest/internal/gtest-tuple.h.pump +++ b/googletest/include/gtest/internal/gtest-tuple.h.pump @@ -34,6 +34,8 @@ $$ This meta comment fixes auto-indentation in Emacs. }} // Implements a subset of TR1 tuple needed by Google Test and Google Mock. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ diff --git a/googletest/include/gtest/internal/gtest-type-util.h b/googletest/include/gtest/internal/gtest-type-util.h index 282b81f..2681dbb 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h +++ b/googletest/include/gtest/internal/gtest-type-util.h @@ -41,6 +41,8 @@ // Please contact googletestframework@googlegroups.com if you need // more. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ diff --git a/googletest/include/gtest/internal/gtest-type-util.h.pump b/googletest/include/gtest/internal/gtest-type-util.h.pump index eaa8880..8897795 100644 --- a/googletest/include/gtest/internal/gtest-type-util.h.pump +++ b/googletest/include/gtest/internal/gtest-type-util.h.pump @@ -39,6 +39,8 @@ $var n = 50 $$ Maximum length of type lists we want to support. // Please contact googletestframework@googlegroups.com if you need // more. +// GOOGLETEST_CM0001 DO NOT DELETE + #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ -- cgit v0.12 From ec13264af4595af8bae9be425ecf09ebf588dce3 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Fri, 27 Jul 2018 15:05:20 -0400 Subject: added missing comments --- googletest/include/gtest/gtest-spi.h | 2 +- googletest/include/gtest/gtest_prod.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/googletest/include/gtest/gtest-spi.h b/googletest/include/gtest/gtest-spi.h index 2a48cca..c21b029 100644 --- a/googletest/include/gtest/gtest-spi.h +++ b/googletest/include/gtest/gtest-spi.h @@ -32,7 +32,7 @@ // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). -GOOGLETEST_CM0004 DO NOT DELETE +// GOOGLETEST_CM0004 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/googletest/include/gtest/gtest_prod.h b/googletest/include/gtest/gtest_prod.h index 21e211e..71377f8 100644 --- a/googletest/include/gtest/gtest_prod.h +++ b/googletest/include/gtest/gtest_prod.h @@ -30,7 +30,7 @@ // Author: wan@google.com (Zhanyong Wan) // // Google C++ Testing and Mocking Framework definitions useful in production code. -GOOGLETEST_CM0003 DO NOT DELETE +// GOOGLETEST_CM0003 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -- cgit v0.12 From b7cb1bc6f9d63df7ec9c9b0897de047a8c728615 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Mon, 30 Jul 2018 13:31:46 -0400 Subject: small tweaks, OSS merge cl 206357486 --- googletest/src/gtest_main.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googletest/src/gtest_main.cc b/googletest/src/gtest_main.cc index 5e9c94c..f039d00 100644 --- a/googletest/src/gtest_main.cc +++ b/googletest/src/gtest_main.cc @@ -32,7 +32,7 @@ #include "gtest/gtest.h" GTEST_API_ int main(int argc, char **argv) { - printf("Running main() from gtest_main.cc\n"); + printf("Running main() from %s\n", __FILE__); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } -- cgit v0.12 From 539ee4bc549846e3bd98b77f85d0aff8410ef8c0 Mon Sep 17 00:00:00 2001 From: Gennadiy Civil Date: Wed, 1 Aug 2018 11:07:22 -0400 Subject: Formatting changes and upstreaming one test --- googlemock/test/gmock_leak_test.py | 2 - googlemock/test/gmock_output_test.py | 1 - googletest/test/BUILD.bazel | 8 ++ .../test/gtest_test_macro_stack_footprint_test.cc | 90 ++++++++++++++++++++++ 4 files changed, 98 insertions(+), 3 deletions(-) create mode 100644 googletest/test/gtest_test_macro_stack_footprint_test.cc diff --git a/googlemock/test/gmock_leak_test.py b/googlemock/test/gmock_leak_test.py index 997680c..a2fee4b 100755 --- a/googlemock/test/gmock_leak_test.py +++ b/googlemock/test/gmock_leak_test.py @@ -33,10 +33,8 @@ __author__ = 'wan@google.com (Zhanyong Wan)' - import gmock_test_utils - PROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_') TEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*'] TEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*'] diff --git a/googlemock/test/gmock_output_test.py b/googlemock/test/gmock_output_test.py index 9d73d57..8f57d46 100755 --- a/googlemock/test/gmock_output_test.py +++ b/googlemock/test/gmock_output_test.py @@ -43,7 +43,6 @@ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import sys - import gmock_test_utils diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel index 405feee..6888e4c 100644 --- a/googletest/test/BUILD.bazel +++ b/googletest/test/BUILD.bazel @@ -97,6 +97,14 @@ cc_test( deps = ["//:gtest_main"], ) + +cc_test( + name = "gtest_test_macro_stack_footprint_test", + size = "small", + srcs = ["gtest_test_macro_stack_footprint_test.cc"], + deps = ["//:gtest"], +) + #These googletest tests have their own main() cc_test( name = "gtest-listener_test", diff --git a/googletest/test/gtest_test_macro_stack_footprint_test.cc b/googletest/test/gtest_test_macro_stack_footprint_test.cc new file mode 100644 index 0000000..48958b8 --- /dev/null +++ b/googletest/test/gtest_test_macro_stack_footprint_test.cc @@ -0,0 +1,90 @@ +// Copyright 2013, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) +// +// Each TEST() expands to some static registration logic. GCC puts all +// such static initialization logic for a translation unit in a common, +// internal function. Since Google's build system restricts how much +// stack space a function can use, there's a limit on how many TEST()s +// one can put in a single C++ test file. This test ensures that a large +// number of TEST()s can be defined in the same translation unit. + +#include "gtest/gtest.h" + +// This macro defines 10 dummy tests. +#define TEN_TESTS_(test_case_name) \ + TEST(test_case_name, T0) {} \ + TEST(test_case_name, T1) {} \ + TEST(test_case_name, T2) {} \ + TEST(test_case_name, T3) {} \ + TEST(test_case_name, T4) {} \ + TEST(test_case_name, T5) {} \ + TEST(test_case_name, T6) {} \ + TEST(test_case_name, T7) {} \ + TEST(test_case_name, T8) {} \ + TEST(test_case_name, T9) {} + +// This macro defines 100 dummy tests. +#define HUNDRED_TESTS_(test_case_name_prefix) \ + TEN_TESTS_(test_case_name_prefix ## 0) \ + TEN_TESTS_(test_case_name_prefix ## 1) \ + TEN_TESTS_(test_case_name_prefix ## 2) \ + TEN_TESTS_(test_case_name_prefix ## 3) \ + TEN_TESTS_(test_case_name_prefix ## 4) \ + TEN_TESTS_(test_case_name_prefix ## 5) \ + TEN_TESTS_(test_case_name_prefix ## 6) \ + TEN_TESTS_(test_case_name_prefix ## 7) \ + TEN_TESTS_(test_case_name_prefix ## 8) \ + TEN_TESTS_(test_case_name_prefix ## 9) + +// This macro defines 1000 dummy tests. +#define THOUSAND_TESTS_(test_case_name_prefix) \ + HUNDRED_TESTS_(test_case_name_prefix ## 0) \ + HUNDRED_TESTS_(test_case_name_prefix ## 1) \ + HUNDRED_TESTS_(test_case_name_prefix ## 2) \ + HUNDRED_TESTS_(test_case_name_prefix ## 3) \ + HUNDRED_TESTS_(test_case_name_prefix ## 4) \ + HUNDRED_TESTS_(test_case_name_prefix ## 5) \ + HUNDRED_TESTS_(test_case_name_prefix ## 6) \ + HUNDRED_TESTS_(test_case_name_prefix ## 7) \ + HUNDRED_TESTS_(test_case_name_prefix ## 8) \ + HUNDRED_TESTS_(test_case_name_prefix ## 9) + +// Ensures that we can define 1000 TEST()s in the same translation +// unit. +THOUSAND_TESTS_(T) + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + + // We don't actually need to run the dummy tests - the purpose is to + // ensure that they compile. + return 0; +} -- cgit v0.12