diff --git a/.gitignore b/.gitignore index 74e7466a..da68162d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,10 @@ # Ignore CI build directory build/ xcuserdata +cmake-build-debug/ +.idea/ +bazel-bin +bazel-genfiles +bazel-googletest +bazel-out +bazel-testlogs diff --git a/BUILD.bazel b/BUILD.bazel new file mode 100644 index 00000000..a4423740 --- /dev/null +++ b/BUILD.bazel @@ -0,0 +1,147 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: misterg@google.com (Gennadiy Civil) +# +# Bazel Build for Google C++ Testing Framework(Google Test) + +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +config_setting( + name = "win", + values = {"cpu": "x64_windows_msvc"}, +) + +# Google Test including Google Mock +cc_library( + name = "gtest", + srcs = glob( + include = [ + "googletest/src/*.cc", + "googletest/src/*.h", + "googletest/include/gtest/**/*.h", + "googlemock/src/*.cc", + "googlemock/include/gmock/**/*.h", + ], + exclude = [ + "googletest/src/gtest-all.cc", + "googletest/src/gtest_main.cc", + "googlemock/src/gmock-all.cc", + "googlemock/src/gmock_main.cc", + ], + ), + hdrs =glob([ + "googletest/include/gtest/*.h", + "googlemock/include/gmock/*.h", + ]), + copts = select( + { + ":win": [], + "//conditions:default": ["-pthread"], + }, + ), + includes = [ + "googlemock", + "googlemock/include", + "googletest", + "googletest/include", + ], + linkopts = select({ + ":win": [], + "//conditions:default": [ + "-pthread", + ], + }), +) + +cc_library( + name = "gtest_main", + srcs = [ + "googlemock/src/gmock_main.cc", + ], + deps = ["//:gtest"], +) + +# The following rules build samples of how to use gTest. +cc_library( + name = "gtest_sample_lib", + srcs = [ + "googletest/samples/sample1.cc", + "googletest/samples/sample2.cc", + "googletest/samples/sample4.cc", + ], + hdrs = [ + "googletest/samples/prime_tables.h", + "googletest/samples/sample1.h", + "googletest/samples/sample2.h", + "googletest/samples/sample3-inl.h", + "googletest/samples/sample4.h", + ], +) + +cc_test( + name = "gtest_samples", + size = "small", + #All Samples except: + #sample9 ( main ) + #sample10 (main and takes a command line option and needs to be separate) + srcs = [ + "googletest/samples/sample1_unittest.cc", + "googletest/samples/sample2_unittest.cc", + "googletest/samples/sample3_unittest.cc", + "googletest/samples/sample4_unittest.cc", + "googletest/samples/sample5_unittest.cc", + "googletest/samples/sample6_unittest.cc", + "googletest/samples/sample7_unittest.cc", + "googletest/samples/sample8_unittest.cc", + ], + deps = [ + "gtest_sample_lib", + ":gtest_main", + ], +) + +cc_test( + name = "sample9_unittest", + size = "small", + srcs = ["googletest/samples/sample9_unittest.cc"], + deps = [":gtest"], +) + +cc_test( + name = "sample10_unittest", + size = "small", + srcs = ["googletest/samples/sample10_unittest.cc"], + deps = [ + ":gtest", + ], +) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5754992e..f8a97faa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,16 +1,33 @@ cmake_minimum_required(VERSION 2.6.4) +if (POLICY CMP0048) + cmake_policy(SET CMP0048 NEW) +endif (POLICY CMP0048) + project( googletest-distribution ) enable_testing() +include(CMakeDependentOption) +if (CMAKE_VERSION VERSION_LESS 2.8.5) + set(CMAKE_INSTALL_BINDIR "bin" CACHE STRING "User executables (bin)") + set(CMAKE_INSTALL_LIBDIR "lib${LIB_SUFFIX}" CACHE STRING "Object code libraries (lib)") + set(CMAKE_INSTALL_INCLUDEDIR "include" CACHE STRING "C header files (include)") + mark_as_advanced(CMAKE_INSTALL_BINDIR CMAKE_INSTALL_LIBDIR CMAKE_INSTALL_INCLUDEDIR) +else() + include(GNUInstallDirs) +endif() + option(BUILD_GTEST "Builds the googletest subproject" OFF) #Note that googlemock target already builds googletest option(BUILD_GMOCK "Builds the googlemock subproject" ON) +cmake_dependent_option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON "BUILD_GTEST OR BUILD_GMOCK" OFF) +cmake_dependent_option(INSTALL_GMOCK "Enable installation of googlemock. (Projects embedding googlemock may want to turn this OFF.)" ON "BUILD_GMOCK" OFF) + if(BUILD_GMOCK) add_subdirectory( googlemock ) elseif(BUILD_GTEST) add_subdirectory( googletest ) endif() diff --git a/README.md b/README.md index 076484e4..3efd2ebf 100644 --- a/README.md +++ b/README.md @@ -1,142 +1,148 @@ # Google Test # [![Build Status](https://travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest) -[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/BillyDonahue/googletest/branch/master) +[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) Welcome to **Google Test**, Google's C++ test framework! This repository is a merger of the formerly separate GoogleTest and GoogleMock projects. These were so closely related that it makes sense to maintain and release them together. Please see the project page above for more information as well as the mailing list for questions, discussions, and development. There is -also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please +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. **Google Mock** is an extension to Google Test for writing and using C++ mock classes. See the separate [Google Mock documentation](googlemock/README.md). More detailed documentation for googletest (including build instructions) are in its interior [googletest/README.md](googletest/README.md) file. ## Features ## * An [XUnit](https://en.wikipedia.org/wiki/XUnit) test framework. * Test discovery. * A rich set of assertions. * User-defined assertions. * Death tests. * Fatal and non-fatal failures. * Value-parameterized tests. * Type-parameterized tests. * Various options for running the tests. * XML test report generation. ## Platforms ## Google test has been used on a variety of platforms: * Linux * Mac OS X * Windows * Cygwin * MinGW * Windows Mobile * Symbian ## Who Is Using Google Test? ## In addition to many internal projects at Google, Google Test is also used by the following notable projects: * The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser and Chrome OS). * The [LLVM](http://llvm.org/) compiler. * [Protocol Buffers](https://github.com/google/protobuf), Google's data interchange format. * The [OpenCV](http://opencv.org/) computer vision library. + * [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only, dependency-free deep learning framework in C++11. ## Related Open Source Projects ## +[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based automated test-runner and Graphical User Interface with powerful features for Windows and Linux platforms. + [Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that runs your test binary, allows you to track its progress via a progress bar, and displays a list of test failures. Clicking on one shows failure text. Google Test UI is written in C#. [GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event listener for Google Test that implements the [TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test result output. If your test runner understands TAP, you may find it useful. +[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that +runs tests from your binary in parallel to provide significant speed-up. + ## Requirements ## Google Test is designed to have fairly minimal requirements to build and use with your projects, but there are some. Currently, we support Linux, Windows, Mac OS X, and Cygwin. We will also make our best effort to support other platforms (e.g. Solaris, AIX, and z/OS). However, since core members of the Google Test project have no access to these platforms, Google Test may have outstanding issues there. If you notice any problems on your platform, please notify -<googletestframework@googlegroups.com>. Patches for fixing them are +[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework). Patches for fixing them are even more welcome! ### Linux Requirements ### These are the base requirements to build and use Google Test from a source package (as described below): * GNU-compatible Make or gmake * POSIX-standard shell * POSIX(-2) Regular Expressions (regex.h) * A C++98-standard-compliant compiler ### Windows Requirements ### - * Microsoft Visual C++ v7.1 or newer + * Microsoft Visual C++ 2010 or newer ### Cygwin Requirements ### * Cygwin v1.5.25-14 or newer ### Mac OS X Requirements ### * Mac OS X v10.4 Tiger or newer * Xcode Developer Tools ### Requirements for Contributors ### We welcome patches. If you plan to contribute a patch, you need to build Google Test and its own tests from a git checkout (described below), which has further requirements: * [Python](https://www.python.org/) v2.3 or newer (for running some of the tests and re-generating certain source files from templates) * [CMake](https://cmake.org/) v2.6.4 or newer ## Regenerating Source Files ## Some of Google Test's source files are generated from templates (not in the C++ sense) using a script. For example, the file include/gtest/internal/gtest-type-util.h.pump is used to generate gtest-type-util.h in the same directory. You don't need to worry about regenerating the source files unless you need to modify them. You would then modify the corresponding `.pump` files and run the '[pump.py](googletest/scripts/pump.py)' generator script. See the [Pump Manual](googletest/docs/PumpManual.md). ### Contributing Code ### We welcome patches. Please read the [Developer's Guide](googletest/docs/DevGuide.md) for how you can contribute. In particular, make sure you have signed the Contributor License Agreement, or we won't be able to accept the patch. Happy testing! diff --git a/WORKSPACE b/WORKSPACE new file mode 100644 index 00000000..106b824e --- /dev/null +++ b/WORKSPACE @@ -0,0 +1 @@ +workspace(name = "com_google_googletest") diff --git a/googlemock/CHANGES b/googlemock/CHANGES index d6f2f760..4328ece3 100644 --- a/googlemock/CHANGES +++ b/googlemock/CHANGES @@ -1,126 +1,126 @@ Changes for 1.7.0: * All new improvements in Google Test 1.7.0. * New feature: matchers DoubleNear(), FloatNear(), NanSensitiveDoubleNear(), NanSensitiveFloatNear(), UnorderedElementsAre(), UnorderedElementsAreArray(), WhenSorted(), WhenSortedBy(), IsEmpty(), and SizeIs(). * Improvement: Google Mock can now be built as a DLL. * Improvement: when compiled by a C++11 compiler, matchers AllOf() and AnyOf() can accept an arbitrary number of matchers. * Improvement: when compiled by a C++11 compiler, matchers ElementsAreArray() can accept an initializer list. * Improvement: when exceptions are enabled, a mock method with no default action now throws instead crashing the test. * Improvement: added class testing::StringMatchResultListener to aid definition of composite matchers. * Improvement: function return types used in MOCK_METHOD*() macros can now contain unprotected commas. * Improvement (potentially breaking): EXPECT_THAT() and ASSERT_THAT() are now more strict in ensuring that the value type and the matcher type are compatible, catching potential bugs in tests. * Improvement: Pointee() now works on an optional<T>. * Improvement: the ElementsAreArray() matcher can now take a vector or iterator range as input, and makes a copy of its input elements before the conversion to a Matcher. * Improvement: the Google Mock Generator can now generate mocks for some class templates. * Bug fix: mock object destruction triggerred by another mock object's destruction no longer hangs. * Improvement: Google Mock Doctor works better with newer Clang and GCC now. * Compatibility fixes. * Bug/warning fixes. Changes for 1.6.0: * Compilation is much faster and uses much less memory, especially when the constructor and destructor of a mock class are moved out of the class body. * New matchers: Pointwise(), Each(). * New actions: ReturnPointee() and ReturnRefOfCopy(). * CMake support. * Project files for Visual Studio 2010. * AllOf() and AnyOf() can handle up-to 10 arguments now. * Google Mock doctor understands Clang error messages now. * SetArgPointee<> now accepts string literals. * gmock_gen.py handles storage specifier macros and template return types now. * Compatibility fixes. * Bug fixes and implementation clean-ups. * Potentially incompatible changes: disables the harmful 'make install' command in autotools. Potentially breaking changes: * The description string for MATCHER*() changes from Python-style interpolation to an ordinary C++ string expression. * SetArgumentPointee is deprecated in favor of SetArgPointee. * Some non-essential project files for Visual Studio 2005 are removed. Changes for 1.5.0: * New feature: Google Mock can be safely used in multi-threaded tests on platforms having pthreads. * New feature: function for printing a value of arbitrary type. * New feature: function ExplainMatchResult() for easy definition of composite matchers. * The new matcher API lets user-defined matchers generate custom explanations more directly and efficiently. * Better failure messages all around. * NotNull() and IsNull() now work with smart pointers. * Field() and Property() now work when the matcher argument is a pointer passed by reference. * Regular expression matchers on all platforms. * Added GCC 4.0 support for Google Mock Doctor. * Added gmock_all_test.cc for compiling most Google Mock tests in a single file. * Significantly cleaned up compiler warnings. * Bug fixes, better test coverage, and implementation clean-ups. Potentially breaking changes: * Custom matchers defined using MatcherInterface or MakePolymorphicMatcher() need to be updated after upgrading to Google Mock 1.5.0; matchers defined using MATCHER or MATCHER_P* aren't affected. * Dropped support for 'make install'. Changes for 1.4.0 (we skipped 1.2.* and 1.3.* to match the version of Google Test): * Works in more environments: Symbian and minGW, Visual C++ 7.1. * Lighter weight: comes with our own implementation of TR1 tuple (no more dependency on Boost!). * New feature: --gmock_catch_leaked_mocks for detecting leaked mocks. * New feature: ACTION_TEMPLATE for defining templatized actions. * New feature: the .After() clause for specifying expectation order. - * New feature: the .With() clause for for specifying inter-argument + * New feature: the .With() clause for specifying inter-argument constraints. * New feature: actions ReturnArg<k>(), ReturnNew<T>(...), and DeleteArg<k>(). * New feature: matchers Key(), Pair(), Args<...>(), AllArgs(), IsNull(), and Contains(). * New feature: utility class MockFunction<F>, useful for checkpoints, etc. * New feature: functions Value(x, m) and SafeMatcherCast<T>(m). * New feature: copying a mock object is rejected at compile time. * New feature: a script for fusing all Google Mock and Google Test source files for easy deployment. * Improved the Google Mock doctor to diagnose more diseases. * Improved the Google Mock generator script. * Compatibility fixes for Mac OS X and gcc. * Bug fixes and implementation clean-ups. Changes for 1.1.0: * New feature: ability to use Google Mock with any testing framework. * New feature: macros for easily defining new matchers * New feature: macros for easily defining new actions. * New feature: more container matchers. * New feature: actions for accessing function arguments and throwing exceptions. * Improved the Google Mock doctor script for diagnosing compiler errors. * Bug fixes and implementation clean-ups. Changes for 1.0.0: * Initial Open Source release of Google Mock diff --git a/googlemock/CMakeLists.txt b/googlemock/CMakeLists.txt index 9fb96a4b..bd759dfd 100644 --- a/googlemock/CMakeLists.txt +++ b/googlemock/CMakeLists.txt @@ -1,202 +1,223 @@ ######################################################################## # CMake build script for Google Mock. # # To run the tests for Google Mock itself on Linux, use 'make test' or # ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to # make it prominent in the GUI. option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) option(gmock_build_tests "Build all of Google Mock's own tests." OFF) # A directory to find Google Test sources. if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt") set(gtest_dir gtest) else() set(gtest_dir ../googletest) endif() # Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL) if (COMMAND pre_project_set_up_hermetic_build) # Google Test also calls hermetic setup functions from add_subdirectory, # although its changes will not affect things at the current scope. pre_project_set_up_hermetic_build() endif() ######################################################################## # # Project-wide settings # Name of the project. # # CMake files in this project can refer to the root source directory # as ${gmock_SOURCE_DIR} and to the root binary directory as # ${gmock_BINARY_DIR}. # Language "C" is required for find_package(Threads). -project(gmock CXX C) +if (CMAKE_VERSION VERSION_LESS 3.0) + project(gmock CXX C) +else() + cmake_policy(SET CMP0048 NEW) + project(gmock VERSION 1.9.0 LANGUAGES CXX C) +endif() cmake_minimum_required(VERSION 2.6.4) if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() # Instructs CMake to process Google Test's CMakeLists.txt and add its # targets to the current scope. We are placing Google Test's binary # directory in a subdirectory of our own as VC compilation may break # if they are the same (the default). add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/gtest") # Although Google Test's CMakeLists.txt calls this function, the # changes there don't affect the current scope. Therefore we have to # call it again here. config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake # Adds Google Mock's and Google Test's header directories to the search path. include_directories("${gmock_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}" "${gtest_SOURCE_DIR}/include" # This directory is needed to build directly from Google # Test sources. "${gtest_SOURCE_DIR}") # Summary of tuple support for Microsoft Visual Studio: # Compiler version(MS) version(cmake) Support # ---------- ----------- -------------- ----------------------------- # <= VS 2010 <= 10 <= 1600 Use Google Tests's own tuple. # VS 2012 11 1700 std::tr1::tuple + _VARIADIC_MAX=10 # VS 2013 12 1800 std::tr1::tuple if (MSVC AND MSVC_VERSION EQUAL 1700) add_definitions(/D _VARIADIC_MAX=10) endif() ######################################################################## # # Defines the gmock & gmock_main libraries. User tests should link # with one of them. # Google Mock libraries. We build them using more strict warnings than what # are used for other targets, to ensure that Google Mock can be compiled by # a user aggressive about warnings. cxx_library(gmock "${cxx_strict}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc) cxx_library(gmock_main "${cxx_strict}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) # If the CMake version supports it, attach header directory information # to the targets for when we are part of a parent build (ie being pulled # in via add_subdirectory() rather than being a standalone build). if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") target_include_directories(gmock INTERFACE "${gmock_SOURCE_DIR}/include") target_include_directories(gmock_main INTERFACE "${gmock_SOURCE_DIR}/include") endif() ######################################################################## # # Install rules -install(TARGETS gmock gmock_main - DESTINATION lib) -install(DIRECTORY ${gmock_SOURCE_DIR}/include/gmock - DESTINATION include) +if(INSTALL_GMOCK) + install(TARGETS gmock gmock_main + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) + install(DIRECTORY ${gmock_SOURCE_DIR}/include/gmock + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + + # configure and install pkgconfig files + configure_file( + cmake/gmock.pc.in + "${CMAKE_BINARY_DIR}/gmock.pc" + @ONLY) + configure_file( + cmake/gmock_main.pc.in + "${CMAKE_BINARY_DIR}/gmock_main.pc" + @ONLY) + install(FILES "${CMAKE_BINARY_DIR}/gmock.pc" "${CMAKE_BINARY_DIR}/gmock_main.pc" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") +endif() ######################################################################## # # Google Mock's own tests. # # You can skip this section if you aren't interested in testing # Google Mock itself. # # The tests are not built by default. To build them, set the # gmock_build_tests option to ON. You can do it by running ccmake # or specifying the -Dgmock_build_tests=ON flag when running cmake. if (gmock_build_tests) # This must be set in the root directory for the tests to be run by # 'make test' or ctest. enable_testing() ############################################################ # C++ tests built with standard compiler flags. cxx_test(gmock-actions_test gmock_main) cxx_test(gmock-cardinalities_test gmock_main) cxx_test(gmock_ex_test gmock_main) cxx_test(gmock-generated-actions_test gmock_main) cxx_test(gmock-generated-function-mockers_test gmock_main) cxx_test(gmock-generated-internal-utils_test gmock_main) cxx_test(gmock-generated-matchers_test gmock_main) cxx_test(gmock-internal-utils_test gmock_main) cxx_test(gmock-matchers_test gmock_main) cxx_test(gmock-more-actions_test gmock_main) cxx_test(gmock-nice-strict_test gmock_main) cxx_test(gmock-port_test gmock_main) cxx_test(gmock-spec-builders_test gmock_main) cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc) cxx_test(gmock_test gmock_main) if (CMAKE_USE_PTHREADS_INIT) cxx_test(gmock_stress_test gmock) endif() # gmock_all_test is commented to save time building and running tests. # Uncomment if necessary. # cxx_test(gmock_all_test gmock_main) ############################################################ # C++ tests built with non-standard compiler flags. cxx_library(gmock_main_no_exception "${cxx_no_exception}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) if (NOT MSVC OR MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010. # Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that # conflict with our own definitions. Therefore using our own tuple does not # work on those compilers. cxx_library(gmock_main_use_own_tuple "${cxx_use_own_tuple}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) cxx_test_with_flags(gmock_use_own_tuple_test "${cxx_use_own_tuple}" gmock_main_use_own_tuple test/gmock-spec-builders_test.cc) endif() cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" gmock_main_no_exception test/gmock-more-actions_test.cc) cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}" gmock_main_no_rtti test/gmock-spec-builders_test.cc) cxx_shared_library(shared_gmock_main "${cxx_default}" "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) # Tests that a binary can be built with Google Mock as a shared library. On # some system configurations, it may not possible to run the binary without # knowing more details about the system configurations. We do not try to run # this binary. To get a more robust shared library coverage, configure with # -DBUILD_SHARED_LIBS=ON. cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}" shared_gmock_main test/gmock-spec-builders_test.cc) set_target_properties(shared_gmock_test_ PROPERTIES COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") ############################################################ # Python tests. cxx_executable(gmock_leak_test_ test gmock_main) py_test(gmock_leak_test) cxx_executable(gmock_output_test_ test gmock) py_test(gmock_output_test) endif() diff --git a/googlemock/README.md b/googlemock/README.md index 7b13a6d3..f0ea6a0e 100644 --- a/googlemock/README.md +++ b/googlemock/README.md @@ -1,343 +1,376 @@ ## Google Mock ## The Google C++ mocking framework. ### Overview ### Google's framework for writing and using C++ mock classes. It can help you derive better designs of your system and write better tests. It is inspired by: * [jMock](http://www.jmock.org/), * [EasyMock](http://www.easymock.org/), and * [Hamcrest](http://code.google.com/p/hamcrest/), and designed with C++'s specifics in mind. Google mock: * lets you create mock classes trivially using simple macros. * supports a rich set of matchers and actions. * handles unordered, partially ordered, or completely ordered expectations. * is extensible by users. We hope you find it useful! ### Features ### * Provides a declarative syntax for defining mocks. * Can easily define partial (hybrid) mocks, which are a cross of real and mock objects. * Handles functions of arbitrary types and overloaded functions. * Comes with a rich set of matchers for validating function arguments. * Uses an intuitive syntax for controlling the behavior of a mock. * Does automatic verification of expectations (no record-and-replay needed). * Allows arbitrary (partial) ordering constraints on function calls to be expressed,. - * Lets a user extend it by defining new matchers and actions. + * Lets an user extend it by defining new matchers and actions. * Does not use exceptions. * Is easy to learn and use. Please see the project page above for more information as well as the mailing list for questions, discussions, and development. There is also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please join us! Please note that code under [scripts/generator](scripts/generator/) is from [cppclean](http://code.google.com/p/cppclean/) and released under the Apache License, which is different from Google Mock's license. ## Getting Started ## If you are new to the project, we suggest that you read the user documentation in the following order: * Learn the [basics](../../master/googletest/docs/Primer.md) of Google Test, if you choose to use Google Mock with it (recommended). * Read [Google Mock for Dummies](../../master/googlemock/docs/ForDummies.md). * Read the instructions below on how to build Google Mock. You can also watch Zhanyong's [talk](http://www.youtube.com/watch?v=sYpCyLI47rM) on Google Mock's usage and implementation. Once you understand the basics, check out the rest of the docs: * [CheatSheet](../../master/googlemock/docs/CheatSheet.md) - all the commonly used stuff at a glance. * [CookBook](../../master/googlemock/docs/CookBook.md) - recipes for getting things done, including advanced techniques. If you need help, please check the [KnownIssues](docs/KnownIssues.md) and [FrequentlyAskedQuestions](docs/FrequentlyAskedQuestions.md) before posting a question on the [discussion group](http://groups.google.com/group/googlemock). ### Using Google Mock Without Google Test ### Google Mock is not a testing framework itself. Instead, it needs a testing framework for writing tests. Google Mock works seamlessly with [Google Test](http://code.google.com/p/googletest/), but you can also use it with [any C++ testing framework](../../master/googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework). ### Requirements for End Users ### Google Mock is implemented on top of [Google Test]( http://github.com/google/googletest/), and depends on it. You must use the bundled version of Google Test when using Google Mock. You can also easily configure Google Mock to work with another testing framework, although it will still need Google Test. Please read ["Using_Google_Mock_with_Any_Testing_Framework"]( ../../master/googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework) for instructions. Google Mock depends on advanced C++ features and thus requires a more modern compiler. The following are needed to use Google Mock: #### Linux Requirements #### * GNU-compatible Make or "gmake" * POSIX-standard shell * POSIX(-2) Regular Expressions (regex.h) * C++98-standard-compliant compiler (e.g. GCC 3.4 or newer) #### Windows Requirements #### * Microsoft Visual C++ 8.0 SP1 or newer #### Mac OS X Requirements #### * Mac OS X 10.4 Tiger or newer * Developer Tools Installed ### Requirements for Contributors ### We welcome patches. If you plan to contribute a patch, you need to build Google Mock and its tests, which has further requirements: * Automake version 1.9 or newer * Autoconf version 2.59 or newer * Libtool / Libtoolize * Python version 2.3 or newer (for running some of the tests and re-generating certain source files from templates) ### Building Google Mock ### +#### Using CMake #### + If you have CMake available, it is recommended that you follow the [build instructions][gtest_cmakebuild] -as described for Google Test. If are using Google Mock with an +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. Otherwise, the following sections -detail how to build Google Mock without CMake. +may be of particular interest. +To make it work for Google Mock you will need to change + + target_link_libraries(example gtest_main) + +to + + target_link_libraries(example gmock_main) + +This works because `gmock_main` library is compiled with Google Test. +However, it does not automatically add Google Test includes. +Therefore you will also have to change + + if (CMAKE_VERSION VERSION_LESS 2.8.11) + include_directories("${gtest_SOURCE_DIR}/include") + endif() + +to + + if (CMAKE_VERSION VERSION_LESS 2.8.11) + include_directories(BEFORE SYSTEM + "${gtest_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}/include") + else() + target_include_directories(gmock_main SYSTEM BEFORE INTERFACE + "${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 +`-Wpedantic -Wall -Wextra -Wconversion`. + #### Preparing to Build (Unix only) #### If you are using a Unix system and plan to use the GNU Autotools build system to build Google Mock (described below), you'll need to configure it now. To prepare the Autotools build system: cd googlemock autoreconf -fvi To build Google Mock and your tests that use it, you need to tell your build system where to find its headers and source files. The exact way to do it depends on which build system you use, and is usually straightforward. This section shows how you can integrate Google Mock into your existing build system. Suppose you put Google Mock in directory `${GMOCK_DIR}` and Google Test in `${GTEST_DIR}` (the latter is `${GMOCK_DIR}/gtest` by default). To build Google Mock, create a library build target (or a project as called by Visual Studio and Xcode) to compile ${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc with ${GTEST_DIR}/include and ${GMOCK_DIR}/include in the system header search path, and ${GTEST_DIR} and ${GMOCK_DIR} in the normal header search path. Assuming a Linux-like system and gcc, something like the following will do: g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \ -pthread -c ${GTEST_DIR}/src/gtest-all.cc g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \ -pthread -c ${GMOCK_DIR}/src/gmock-all.cc ar -rv libgmock.a gtest-all.o gmock-all.o (We need -pthread as Google Test and Google Mock use threads.) Next, you should compile your test source file with ${GTEST\_DIR}/include and ${GMOCK\_DIR}/include in the header search path, and link it with gmock and any other necessary libraries: g++ -isystem ${GTEST_DIR}/include -isystem ${GMOCK_DIR}/include \ -pthread path/to/your_test.cc libgmock.a -o your_test As an example, the make/ directory contains a Makefile that you can use to build Google Mock on systems where GNU make is available (e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google Mock's own tests. Instead, it just builds the Google Mock library and a sample test. You can use it as a starting point for your own build script. If the default settings are correct for your environment, the following commands should succeed: cd ${GMOCK_DIR}/make make ./gmock_test If you see errors, try to tweak the contents of [make/Makefile](make/Makefile) to make them go away. ### Windows ### The msvc/2005 directory contains VC++ 2005 projects and the msvc/2010 directory contains VC++ 2010 projects for building Google Mock and selected tests. Change to the appropriate directory and run "msbuild gmock.sln" to build the library and tests (or open the gmock.sln in the MSVC IDE). If you want to create your own project to use with Google Mock, you'll have to configure it to use the `gmock_config` propety sheet. For that: * Open the Property Manager window (View | Other Windows | Property Manager) * Right-click on your project and select "Add Existing Property Sheet..." * Navigate to `gmock_config.vsprops` or `gmock_config.props` and select it. * In Project Properties | Configuration Properties | General | Additional Include Directories, type <path to Google Mock>/include. ### Tweaking Google Mock ### Google Mock can be used in diverse environments. The default configuration may not work (or may not work well) out of the box in some environments. However, you can easily tweak Google Mock by defining control macros on the compiler command line. Generally, these macros are named like `GTEST_XYZ` and you define them to either 1 or 0 to enable or disable a certain feature. We list the most frequently used macros below. For a complete list, see file [${GTEST\_DIR}/include/gtest/internal/gtest-port.h]( ../googletest/include/gtest/internal/gtest-port.h). ### Choosing a TR1 Tuple Library ### Google Mock uses the C++ Technical Report 1 (TR1) tuple library heavily. Unfortunately TR1 tuple is not yet widely available with all compilers. The good news is that Google Test 1.4.0+ implements a subset of TR1 tuple that's enough for Google Mock's need. Google Mock will automatically use that implementation when the compiler doesn't provide TR1 tuple. Usually you don't need to care about which tuple library Google Test and Google Mock use. However, if your project already uses TR1 tuple, you need to tell Google Test and Google Mock to use the same TR1 tuple library the rest of your project uses, or the two tuple implementations will clash. To do that, add -DGTEST_USE_OWN_TR1_TUPLE=0 to the compiler flags while compiling Google Test, Google Mock, and your tests. If you want to force Google Test and Google Mock to use their own tuple library, just add -DGTEST_USE_OWN_TR1_TUPLE=1 to the compiler flags instead. If you want to use Boost's TR1 tuple library with Google Mock, please refer to the Boost website (http://www.boost.org/) for how to obtain it and set it up. ### As a Shared Library (DLL) ### Google Mock is compact, so most users can build and link it as a static library for the simplicity. Google Mock can be used as a DLL, but the same DLL must contain Google Test as well. See [Google Test's README][gtest_readme] for instructions on how to set up necessary compiler settings. ### Tweaking Google Mock ### Most of Google Test's control macros apply to Google Mock as well. Please see [Google Test's README][gtest_readme] for how to tweak them. ### Upgrading from an Earlier Version ### We strive to keep Google Mock releases backward compatible. Sometimes, though, we have to make some breaking changes for the users' long-term benefits. This section describes what you'll need to do if you are upgrading from an earlier version of Google Mock. #### Upgrading from 1.1.0 or Earlier #### You may need to explicitly enable or disable Google Test's own TR1 tuple library. See the instructions in section "[Choosing a TR1 Tuple Library](../googletest/#choosing-a-tr1-tuple-library)". #### Upgrading from 1.4.0 or Earlier #### On platforms where the pthread library is available, Google Test and Google Mock use it in order to be thread-safe. For this to work, you may need to tweak your compiler and/or linker flags. Please see the "[Multi-threaded Tests](../googletest#multi-threaded-tests )" section in file Google Test's README for what you may need to do. If you have custom matchers defined using `MatcherInterface` or `MakePolymorphicMatcher()`, you'll need to update their definitions to use the new matcher API ( [monomorphic](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Monomorphic_Matchers), [polymorphic](http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Matchers)). Matchers defined using `MATCHER()` or `MATCHER_P*()` aren't affected. ### Developing Google Mock ### This section discusses how to make your own changes to Google Mock. #### Testing Google Mock Itself #### To make sure your changes work as intended and don't break existing functionality, you'll want to compile and run Google Test's own tests. For that you'll need Autotools. First, make sure you have followed the instructions above to configure Google Mock. Then, create a build output directory and enter it. Next, ${GMOCK_DIR}/configure # try --help for more info Once you have successfully configured Google Mock, the build steps are standard for GNU-style OSS packages. make # Standard makefile following GNU conventions make check # Builds and runs all tests - all should pass. Note that when building your project against Google Mock, you are building against Google Test as well. There is no need to configure Google Test separately. #### Contributing a Patch #### We welcome patches. Please read the [Developer's Guide](docs/DevGuide.md) for how you can contribute. In particular, make sure you have signed the Contributor License Agreement, or we won't be able to accept the patch. Happy testing! [gtest_readme]: ../googletest/README.md "googletest" [gtest_cmakebuild]: ../googletest/README.md#using-cmake "Using CMake" [gtest_incorpcmake]: ../googletest/README.md#incorporating-into-an-existing-cmake-project "Incorporating Into An Existing CMake Project" diff --git a/googlemock/cmake/gmock.pc.in b/googlemock/cmake/gmock.pc.in new file mode 100644 index 00000000..c4416426 --- /dev/null +++ b/googlemock/cmake/gmock.pc.in @@ -0,0 +1,9 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock +Description: GoogleMock (without main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/googlemock/cmake/gmock_main.pc.in b/googlemock/cmake/gmock_main.pc.in new file mode 100644 index 00000000..c377dba1 --- /dev/null +++ b/googlemock/cmake/gmock_main.pc.in @@ -0,0 +1,9 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gmock_main +Description: GoogleMock (with main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/googlemock/configure.ac b/googlemock/configure.ac index 3b740f20..edfd8963 100644 --- a/googlemock/configure.ac +++ b/googlemock/configure.ac @@ -1,146 +1,146 @@ m4_include(../googletest/m4/acx_pthread.m4) AC_INIT([Google C++ Mocking Framework], [1.7.0], [googlemock@googlegroups.com], [gmock]) # Provide various options to initialize the Autoconf and configure processes. AC_PREREQ([2.59]) AC_CONFIG_SRCDIR([./LICENSE]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_HEADERS([build-aux/config.h]) AC_CONFIG_FILES([Makefile]) AC_CONFIG_FILES([scripts/gmock-config], [chmod +x scripts/gmock-config]) # Initialize Automake with various options. We require at least v1.9, prevent # pedantic complaints about package files, and enable various distribution # targets. AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects]) # Check for programs used in building Google Test. AC_PROG_CC AC_PROG_CXX AC_LANG([C++]) AC_PROG_LIBTOOL # TODO(chandlerc@google.com): Currently we aren't running the Python tests # against the interpreter detected by AM_PATH_PYTHON, and so we condition # HAVE_PYTHON by requiring "python" to be in the PATH, and that interpreter's # version to be >= 2.3. This will allow the scripts to use a "/usr/bin/env" # hashbang. PYTHON= # We *do not* allow the user to specify a python interpreter AC_PATH_PROG([PYTHON],[python],[:]) AS_IF([test "$PYTHON" != ":"], [AM_PYTHON_CHECK_VERSION([$PYTHON],[2.3],[:],[PYTHON=":"])]) AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"]) # TODO(chandlerc@google.com) Check for the necessary system headers. # Configure pthreads. AC_ARG_WITH([pthreads], [AS_HELP_STRING([--with-pthreads], [use pthreads (default is yes)])], [with_pthreads=$withval], [with_pthreads=check]) have_pthreads=no AS_IF([test "x$with_pthreads" != "xno"], [ACX_PTHREAD( [], [AS_IF([test "x$with_pthreads" != "xcheck"], [AC_MSG_FAILURE( [--with-pthreads was specified, but unable to be used])])]) have_pthreads="$acx_pthread_ok"]) AM_CONDITIONAL([HAVE_PTHREADS],[test "x$have_pthreads" == "xyes"]) AC_SUBST(PTHREAD_CFLAGS) AC_SUBST(PTHREAD_LIBS) # GoogleMock currently has hard dependencies upon GoogleTest above and beyond # running its own test suite, so we both provide our own version in # a subdirectory and provide some logic to use a custom version or a system # installed version. AC_ARG_WITH([gtest], [AS_HELP_STRING([--with-gtest], [Specifies how to find the gtest package. If no arguments are given, the default behavior, a system installed gtest will be used if present, and an internal version built otherwise. If a path is provided, the gtest built or installed at that prefix will be used.])], [], [with_gtest=yes]) AC_ARG_ENABLE([external-gtest], [AS_HELP_STRING([--disable-external-gtest], [Disables any detection or use of a system installed or user provided gtest. Any option to '--with-gtest' is ignored. (Default is enabled.)]) ], [], [enable_external_gtest=yes]) AS_IF([test "x$with_gtest" == "xno"], [AC_MSG_ERROR([dnl Support for GoogleTest was explicitly disabled. Currently GoogleMock has a hard dependency upon GoogleTest to build, please provide a version, or allow GoogleMock to use any installed version and fall back upon its internal version.])]) # Setup various GTEST variables. TODO(chandlerc@google.com): When these are # used below, they should be used such that any pre-existing values always # trump values we set them to, so that they can be used to selectively override # details of the detection process. AC_ARG_VAR([GTEST_CONFIG], [The exact path of Google Test's 'gtest-config' script.]) AC_ARG_VAR([GTEST_CPPFLAGS], [C-like preprocessor flags for Google Test.]) AC_ARG_VAR([GTEST_CXXFLAGS], [C++ compile flags for Google Test.]) AC_ARG_VAR([GTEST_LDFLAGS], [Linker path and option flags for Google Test.]) AC_ARG_VAR([GTEST_LIBS], [Library linking flags for Google Test.]) AC_ARG_VAR([GTEST_VERSION], [The version of Google Test available.]) HAVE_BUILT_GTEST="no" GTEST_MIN_VERSION="1.7.0" AS_IF([test "x${enable_external_gtest}" = "xyes"], [# Begin filling in variables as we are able. AS_IF([test "x${with_gtest}" != "xyes"], [AS_IF([test -x "${with_gtest}/scripts/gtest-config"], [GTEST_CONFIG="${with_gtest}/scripts/gtest-config"], [GTEST_CONFIG="${with_gtest}/bin/gtest-config"]) AS_IF([test -x "${GTEST_CONFIG}"], [], [AC_MSG_ERROR([dnl Unable to locate either a built or installed Google Test at '${with_gtest}'.]) ])]) AS_IF([test -x "${GTEST_CONFIG}"], [], [AC_PATH_PROG([GTEST_CONFIG], [gtest-config])]) AS_IF([test -x "${GTEST_CONFIG}"], [AC_MSG_CHECKING([for Google Test version >= ${GTEST_MIN_VERSION}]) AS_IF([${GTEST_CONFIG} --min-version=${GTEST_MIN_VERSION}], [AC_MSG_RESULT([yes]) HAVE_BUILT_GTEST="yes"], [AC_MSG_RESULT([no])])])]) AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"], [GTEST_CPPFLAGS=`${GTEST_CONFIG} --cppflags` GTEST_CXXFLAGS=`${GTEST_CONFIG} --cxxflags` GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags` GTEST_LIBS=`${GTEST_CONFIG} --libs` GTEST_VERSION=`${GTEST_CONFIG} --version`], [AC_CONFIG_SUBDIRS([../googletest]) - # GTEST_CONFIG needs to be executable both in a Makefile environmont and + # GTEST_CONFIG needs to be executable both in a Makefile environment and # in a shell script environment, so resolve an absolute path for it here. GTEST_CONFIG="`pwd -P`/../googletest/scripts/gtest-config" GTEST_CPPFLAGS='-I$(top_srcdir)/../googletest/include' GTEST_CXXFLAGS='-g' GTEST_LDFLAGS='' GTEST_LIBS='$(top_builddir)/../googletest/lib/libgtest.la' GTEST_VERSION="${GTEST_MIN_VERSION}"]) # TODO(chandlerc@google.com) Check the types, structures, and other compiler # and architecture characteristics. # Output the generated files. No further autoconf macros may be used. AC_OUTPUT diff --git a/googlemock/docs/CookBook.md b/googlemock/docs/CookBook.md index 0460d357..6ea7f3a9 100644 --- a/googlemock/docs/CookBook.md +++ b/googlemock/docs/CookBook.md @@ -1,3675 +1,3679 @@ You can find recipes for using Google Mock here. If you haven't yet, please read the [ForDummies](ForDummies.md) document first to make sure you understand the basics. **Note:** Google Mock lives in the `testing` name space. For readability, it is recommended to write `using ::testing::Foo;` once in your file before using the name `Foo` defined by Google Mock. We omit such `using` statements in this page for brevity, but you should do it in your own code. # Creating Mock Classes # ## Mocking Private or Protected Methods ## You must always put a mock method definition (`MOCK_METHOD*`) in a `public:` section of the mock class, regardless of the method being mocked being `public`, `protected`, or `private` in the base class. This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: +from outside of the mock class. (Yes, C++ allows a subclass to specify +a different access level than the base class on a virtual function.) +Example: ``` class Foo { public: ... virtual bool Transform(Gadget* g) = 0; protected: virtual void Resume(); private: virtual int GetTimeOut(); }; class MockFoo : public Foo { public: ... MOCK_METHOD1(Transform, bool(Gadget* g)); // The following must be in the public section, even though the // methods are protected or private in the base class. MOCK_METHOD0(Resume, void()); MOCK_METHOD0(GetTimeOut, int()); }; ``` ## Mocking Overloaded Methods ## You can mock overloaded functions as usual. No special attention is required: ``` class Foo { ... // Must be virtual as we'll inherit from Foo. virtual ~Foo(); // Overloaded on the types and/or numbers of arguments. virtual int Add(Element x); virtual int Add(int times, Element x); // Overloaded on the const-ness of this object. virtual Bar& GetBar(); virtual const Bar& GetBar() const; }; class MockFoo : public Foo { ... MOCK_METHOD1(Add, int(Element x)); MOCK_METHOD2(Add, int(int times, Element x); MOCK_METHOD0(GetBar, Bar&()); MOCK_CONST_METHOD0(GetBar, const Bar&()); }; ``` **Note:** if you don't mock all versions of the overloaded method, the compiler will give you a warning about some methods in the base class being hidden. To fix that, use `using` to bring them in scope: ``` class MockFoo : public Foo { ... using Foo::Add; MOCK_METHOD1(Add, int(Element x)); // We don't want to mock int Add(int times, Element x); ... }; ``` ## Mocking Class Templates ## To mock a class template, append `_T` to the `MOCK_*` macros: ``` template <typename Elem> class StackInterface { ... // Must be virtual as we'll inherit from StackInterface. virtual ~StackInterface(); virtual int GetSize() const = 0; virtual void Push(const Elem& x) = 0; }; template <typename Elem> class MockStack : public StackInterface<Elem> { ... MOCK_CONST_METHOD0_T(GetSize, int()); MOCK_METHOD1_T(Push, void(const Elem& x)); }; ``` ## Mocking Nonvirtual Methods ## Google Mock can mock non-virtual functions to be used in what we call _hi-perf dependency injection_. In this case, instead of sharing a common base class with the real class, your mock class will be _unrelated_ to the real class, but contain methods with the same signatures. The syntax for mocking non-virtual methods is the _same_ as mocking virtual methods: ``` // A simple packet stream class. None of its members is virtual. class ConcretePacketStream { public: void AppendPacket(Packet* new_packet); const Packet* GetPacket(size_t packet_number) const; size_t NumberOfPackets() const; ... }; // A mock packet stream class. It inherits from no other, but defines // GetPacket() and NumberOfPackets(). class MockPacketStream { public: MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); MOCK_CONST_METHOD0(NumberOfPackets, size_t()); ... }; ``` Note that the mock class doesn't define `AppendPacket()`, unlike the real class. That's fine as long as the test doesn't need to call it. Next, you need a way to say that you want to use `ConcretePacketStream` in production code, and use `MockPacketStream` in tests. Since the functions are not virtual and the two classes are unrelated, you must specify your choice at _compile time_ (as opposed to run time). One way to do it is to templatize your code that needs to use a packet stream. More specifically, you will give your code a template type argument for the type of the packet stream. In production, you will instantiate your template with `ConcretePacketStream` as the type argument. In tests, you will instantiate the same template with `MockPacketStream`. For example, you may write: ``` template <class PacketStream> void CreateConnection(PacketStream* stream) { ... } template <class PacketStream> class PacketReader { public: void ReadPackets(PacketStream* stream, size_t packet_num); }; ``` Then you can use `CreateConnection<ConcretePacketStream>()` and `PacketReader<ConcretePacketStream>` in production code, and use `CreateConnection<MockPacketStream>()` and `PacketReader<MockPacketStream>` in tests. ``` MockPacketStream mock_stream; EXPECT_CALL(mock_stream, ...)...; .. set more expectations on mock_stream ... PacketReader<MockPacketStream> reader(&mock_stream); ... exercise reader ... ``` ## Mocking Free Functions ## It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class). Instead of calling a free function (say, `OpenFile`) directly, introduce an interface for it and have a concrete subclass that calls the free function: ``` class FileInterface { public: ... virtual bool Open(const char* path, const char* mode) = 0; }; class File : public FileInterface { public: ... virtual bool Open(const char* path, const char* mode) { return OpenFile(path, mode); } }; ``` Your code should talk to `FileInterface` to open a file. Now it's easy to mock out the function. This may seem much hassle, but in practice you often have multiple related functions that you can put in the same interface, so the per-function syntactic overhead will be much lower. If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for [mocking non-virtual methods](#mocking-nonvirtual-methods). ## The Nice, the Strict, and the Naggy ## If a mock method has no `EXPECT_CALL` spec but is called, Google Mock will print a warning about the "uninteresting call". The rationale is: * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. However, sometimes you may want to suppress all "uninteresting call" warnings, while sometimes you may want the opposite, i.e. to treat all of them as errors. Google Mock lets you make the decision on a per-mock-object basis. Suppose your test uses a mock class `MockFoo`: ``` TEST(...) { MockFoo mock_foo; EXPECT_CALL(mock_foo, DoThis()); ... code that uses mock_foo ... } ``` If a method of `mock_foo` other than `DoThis()` is called, it will be reported by Google Mock as a warning. However, if you rewrite your test to use `NiceMock<MockFoo>` instead, the warning will be gone, resulting in a cleaner test output: ``` using ::testing::NiceMock; TEST(...) { NiceMock<MockFoo> mock_foo; EXPECT_CALL(mock_foo, DoThis()); ... code that uses mock_foo ... } ``` `NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used wherever `MockFoo` is accepted. It also works if `MockFoo`'s constructor takes some arguments, as `NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: ``` using ::testing::NiceMock; TEST(...) { NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). EXPECT_CALL(mock_foo, DoThis()); ... code that uses mock_foo ... } ``` The usage of `StrictMock` is similar, except that it makes all uninteresting calls failures: ``` using ::testing::StrictMock; TEST(...) { StrictMock<MockFoo> mock_foo; EXPECT_CALL(mock_foo, DoThis()); ... code that uses mock_foo ... // The test will fail if a method of mock_foo other than DoThis() // is called. } ``` There are some caveats though (I don't like them just as much as the next guy, but sadly they are side effects of C++'s limitations): 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). + 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](https://google.github.io/styleguide/cppguide.html). 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort. ## Simplifying the Interface without Breaking Existing Code ## Sometimes a method has a long list of arguments that is mostly uninteresting. For example, ``` class LogSink { public: ... virtual void send(LogSeverity severity, const char* full_filename, const char* base_filename, int line, const struct tm* tm_time, const char* message, size_t message_len) = 0; }; ``` This method's argument list is lengthy and hard to work with (let's say that the `message` argument is not even 0-terminated). If we mock it as is, using the mock will be awkward. If, however, we try to simplify this interface, we'll need to fix all clients depending on it, which is often infeasible. The trick is to re-dispatch the method in the mock class: ``` class ScopedMockLog : public LogSink { public: ... virtual void send(LogSeverity severity, const char* full_filename, const char* base_filename, int line, const tm* tm_time, const char* message, size_t message_len) { // We are only interested in the log severity, full file name, and // log message. Log(severity, full_filename, std::string(message, message_len)); } // Implements the mock method: // // void Log(LogSeverity severity, // const string& file_path, // const string& message); MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, const string& message)); }; ``` By defining a new mock method with a trimmed argument list, we make the mock class much more user-friendly. ## Alternative to Mocking Concrete Classes ## Often you may find yourself using classes that don't implement interfaces. In order to test your code that uses such a class (let's call it `Concrete`), you may be tempted to make the methods of `Concrete` virtual and then mock it. Try not to do that. Making a non-virtual function virtual is a big decision. It creates an extension point where subclasses can tweak your class' behavior. This weakens your control on the class because now it's harder to maintain the class' invariants. You should make a function virtual only when there is a valid reason for a subclass to override it. Mocking concrete classes directly is problematic as it creates a tight coupling between the class and the tests - any small change in the class may invalidate your tests and make test maintenance a pain. To avoid such problems, many programmers have been practicing "coding to interfaces": instead of talking to the `Concrete` class, your code would define an interface and talk to it. Then you implement that interface as an adaptor on top of `Concrete`. In tests, you can easily mock that interface to observe how your code is doing. This technique incurs some overhead: * You pay the cost of virtual function calls (usually not a problem). * There is more abstraction for the programmers to learn. However, it can also bring significant benefits in addition to better testability: * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. Some people worry that if everyone is practicing this technique, they will end up writing lots of redundant code. This concern is totally understandable. However, there are two reasons why it may not be the case: * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. You need to weigh the pros and cons carefully for your particular problem, but I'd like to assure you that the Java community has been practicing this for a long time and it's a proven effective technique applicable in a wide variety of situations. :-) ## Delegating Calls to a Fake ## Some times you have a non-trivial fake implementation of an interface. For example: ``` class Foo { public: virtual ~Foo() {} virtual char DoThis(int n) = 0; virtual void DoThat(const char* s, int* p) = 0; }; class FakeFoo : public Foo { public: virtual char DoThis(int n) { return (n > 0) ? '+' : (n < 0) ? '-' : '0'; } virtual void DoThat(const char* s, int* p) { *p = strlen(s); } }; ``` Now you want to mock this interface such that you can set expectations on it. However, you also want to use `FakeFoo` for the default behavior, as duplicating it in the mock object is, well, a lot of work. When you define the mock class using Google Mock, you can have it delegate its default action to a fake class you already have, using this pattern: ``` using ::testing::_; using ::testing::Invoke; class MockFoo : public Foo { public: // Normal mock method definitions using Google Mock. MOCK_METHOD1(DoThis, char(int n)); MOCK_METHOD2(DoThat, void(const char* s, int* p)); // Delegates the default actions of the methods to a FakeFoo object. // This must be called *before* the custom ON_CALL() statements. void DelegateToFake() { ON_CALL(*this, DoThis(_)) .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); ON_CALL(*this, DoThat(_, _)) .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); } private: FakeFoo fake_; // Keeps an instance of the fake in the mock. }; ``` With that, you can use `MockFoo` in your tests as usual. Just remember that if you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the fake will be called upon to do it: ``` using ::testing::_; TEST(AbcTest, Xyz) { MockFoo foo; foo.DelegateToFake(); // Enables the fake for delegation. // Put your ON_CALL(foo, ...)s here, if any. // No action specified, meaning to use the default action. EXPECT_CALL(foo, DoThis(5)); EXPECT_CALL(foo, DoThat(_, _)); int n = 0; EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. EXPECT_EQ(2, n); } ``` **Some tips:** * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double) const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()` method.). * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. Regarding the tip on mixing a mock and a fake, here's an example on why it may be a bad sign: Suppose you have a class `System` for low-level system operations. In particular, it does file and I/O operations. And suppose you want to test how your code uses `System` to do I/O, and you just want the file operations to work normally. If you mock out the entire `System` class, you'll have to provide a fake implementation for the file operation part, which suggests that `System` is taking on too many roles. Instead, you can define a `FileOps` interface and an `IOOps` interface and split `System`'s functionalities into the two. Then you can mock `IOOps` without mocking `FileOps`. ## Delegating Calls to a Real Object ## When using testing doubles (mocks, fakes, stubs, and etc), sometimes their behaviors will differ from those of the real objects. This difference could be either intentional (as in simulating an error such that you can test the error handling code) or unintentional. If your mocks have different behaviors than the real objects by mistake, you could end up with code that passes the tests but fails in production. You can use the _delegating-to-real_ technique to ensure that your mock has the same behavior as the real object while retaining the ability to validate calls. This technique is very similar to the delegating-to-fake technique, the difference being that we use a real object instead of a fake. Here's an example: ``` using ::testing::_; using ::testing::AtLeast; using ::testing::Invoke; class MockFoo : public Foo { public: MockFoo() { // By default, all calls are delegated to the real object. ON_CALL(*this, DoThis()) .WillByDefault(Invoke(&real_, &Foo::DoThis)); ON_CALL(*this, DoThat(_)) .WillByDefault(Invoke(&real_, &Foo::DoThat)); ... } MOCK_METHOD0(DoThis, ...); MOCK_METHOD1(DoThat, ...); ... private: Foo real_; }; ... MockFoo mock; EXPECT_CALL(mock, DoThis()) .Times(3); EXPECT_CALL(mock, DoThat("Hi")) .Times(AtLeast(1)); ... use mock in test ... ``` With this, Google Mock will verify that your code made the right calls (with the right arguments, in the right order, called the right number of times, etc), and a real object will answer the calls (so the behavior will be the same as in production). This gives you the best of both worlds. ## Delegating Calls to a Parent Class ## Ideally, you should code to interfaces, whose methods are all pure virtual. In reality, sometimes you do need to mock a virtual method that is not pure (i.e, it already has an implementation). For example: ``` class Foo { public: virtual ~Foo(); virtual void Pure(int n) = 0; virtual int Concrete(const char* str) { ... } }; class MockFoo : public Foo { public: // Mocking a pure method. MOCK_METHOD1(Pure, void(int n)); // Mocking a concrete method. Foo::Concrete() is shadowed. MOCK_METHOD1(Concrete, int(const char* str)); }; ``` Sometimes you may want to call `Foo::Concrete()` instead of `MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or perhaps your test doesn't need to mock `Concrete()` at all (but it would be oh-so painful to have to define a new mock class whenever you don't need to mock one of its methods). The trick is to leave a back door in your mock class for accessing the real methods in the base class: ``` class MockFoo : public Foo { public: // Mocking a pure method. MOCK_METHOD1(Pure, void(int n)); // Mocking a concrete method. Foo::Concrete() is shadowed. MOCK_METHOD1(Concrete, int(const char* str)); // Use this to call Concrete() defined in Foo. int FooConcrete(const char* str) { return Foo::Concrete(str); } }; ``` Now, you can call `Foo::Concrete()` inside an action by: ``` using ::testing::_; using ::testing::Invoke; ... EXPECT_CALL(foo, Concrete(_)) .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); ``` or tell the mock object that you don't want to mock `Concrete()`: ``` using ::testing::Invoke; ... ON_CALL(foo, Concrete(_)) .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); ``` (Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do that, `MockFoo::Concrete()` will be called (and cause an infinite recursion) since `Foo::Concrete()` is virtual. That's just how C++ works.) # Using Matchers # ## Matching Argument Values Exactly ## You can specify exactly which arguments a mock method is expecting: ``` using ::testing::Return; ... EXPECT_CALL(foo, DoThis(5)) .WillOnce(Return('a')); EXPECT_CALL(foo, DoThat("Hello", bar)); ``` ## Using Simple Matchers ## You can use matchers to match arguments that have a certain property: ``` using ::testing::Ge; using ::testing::NotNull; using ::testing::Return; ... EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. .WillOnce(Return('a')); EXPECT_CALL(foo, DoThat("Hello", NotNull())); // The second argument must not be NULL. ``` A frequently used matcher is `_`, which matches anything: ``` using ::testing::_; using ::testing::NotNull; ... EXPECT_CALL(foo, DoThat(_, NotNull())); ``` ## Combining Matchers ## You can build complex matchers from existing ones using `AllOf()`, `AnyOf()`, and `Not()`: ``` using ::testing::AllOf; using ::testing::Gt; using ::testing::HasSubstr; using ::testing::Ne; using ::testing::Not; ... // The argument must be > 5 and != 10. EXPECT_CALL(foo, DoThis(AllOf(Gt(5), Ne(10)))); // The first argument must not contain sub-string "blah". EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), NULL)); ``` ## Casting Matchers ## Google Mock matchers are statically typed, meaning that the compiler can catch your mistake if you use a matcher of the wrong type (for example, if you use `Eq(5)` to match a `string` argument). Good for you! Sometimes, however, you know what you're doing and want the compiler to give you some slack. One example is that you have a matcher for `long` and the argument you want to match is `int`. While the two types aren't exactly the same, there is nothing really wrong with using a `Matcher<long>` to match an `int` - after all, we can first convert the `int` argument to a `long` before giving it to the matcher. To support this need, Google Mock gives you the `SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type `Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the type `m` accepts): 1. Type `T` can be implicitly cast to type `U`; 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). The code won't compile if any of these conditions isn't met. Here's one example: ``` using ::testing::SafeMatcherCast; // A base class and a child class. class Base { ... }; class Derived : public Base { ... }; class MockFoo : public Foo { public: MOCK_METHOD1(DoThis, void(Derived* derived)); }; ... MockFoo foo; // m is a Matcher<Base*> we got from somewhere. EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); ``` If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works as long as you can `static_cast` type `T` to type `U`. `MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't always safe as it could throw away information, for example), so be careful not to misuse/abuse it. ## Selecting Between Overloaded Functions ## If you expect an overloaded function to be called, the compiler may need some help on which overloaded version it is. To disambiguate functions overloaded on the const-ness of this object, use the `Const()` argument wrapper. ``` using ::testing::ReturnRef; class MockFoo : public Foo { ... MOCK_METHOD0(GetBar, Bar&()); MOCK_CONST_METHOD0(GetBar, const Bar&()); }; ... MockFoo foo; Bar bar1, bar2; EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). .WillOnce(ReturnRef(bar1)); EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). .WillOnce(ReturnRef(bar2)); ``` (`Const()` is defined by Google Mock and returns a `const` reference to its argument.) To disambiguate overloaded functions with the same number of arguments but different argument types, you may need to specify the exact type of a matcher, either by wrapping your matcher in `Matcher<type>()`, or using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, etc): ``` using ::testing::An; using ::testing::Lt; using ::testing::Matcher; using ::testing::TypedEq; class MockPrinter : public Printer { public: MOCK_METHOD1(Print, void(int n)); MOCK_METHOD1(Print, void(char c)); }; TEST(PrinterTest, Print) { MockPrinter printer; EXPECT_CALL(printer, Print(An<int>())); // void Print(int); EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); printer.Print(3); printer.Print(6); printer.Print('a'); } ``` ## Performing Different Actions Based on the Arguments ## When a mock method is called, the _last_ matching expectation that's still active will be selected (think "newer overrides older"). So, you can make a method do different things depending on its argument values like this: ``` using ::testing::_; using ::testing::Lt; using ::testing::Return; ... // The default case. EXPECT_CALL(foo, DoThis(_)) .WillRepeatedly(Return('b')); // The more specific case. EXPECT_CALL(foo, DoThis(Lt(5))) .WillRepeatedly(Return('a')); ``` Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will be returned; otherwise `'b'` will be returned. ## Matching Multiple Arguments as a Whole ## Sometimes it's not enough to match the arguments individually. For example, we may want to say that the first argument must be less than the second argument. The `With()` clause allows us to match all arguments of a mock function as a whole. For example, ``` using ::testing::_; using ::testing::Lt; using ::testing::Ne; ... EXPECT_CALL(foo, InRange(Ne(0), _)) .With(Lt()); ``` says that the first argument of `InRange()` must not be 0, and must be less than the second argument. The expression inside `With()` must be a matcher of type `Matcher< ::testing::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the types of the function arguments. You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`. You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments (as a tuple) against `m`. For example, ``` using ::testing::_; using ::testing::AllOf; using ::testing::Args; using ::testing::Lt; ... EXPECT_CALL(foo, Blah(_, _, _)) .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); ``` says that `Blah()` will be called with arguments `x`, `y`, and `z` where `x < y < z`. As a convenience and example, Google Mock provides some matchers for 2-tuples, including the `Lt()` matcher above. See the [CheatSheet](CheatSheet.md) for the complete list. Note that if you want to pass the arguments to a predicate of your own (e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to take a `::testing::tuple` as its argument; Google Mock will pass the `n` selected arguments as _one_ single tuple to the predicate. ## Using Matchers as Predicates ## Have you noticed that a matcher is just a fancy predicate that also knows how to describe itself? Many existing algorithms take predicates as arguments (e.g. those defined in STL's `<algorithm>` header), and it would be a shame if Google Mock matchers are not allowed to participate. Luckily, you can use a matcher where a unary predicate functor is expected by wrapping it inside the `Matches()` function. For example, ``` #include <algorithm> #include <vector> std::vector<int> v; ... // How many elements in v are >= 10? const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); ``` Since you can build complex matchers from simpler ones easily using Google Mock, this gives you a way to conveniently construct composite predicates (doing the same using STL's `<functional>` header is just painful). For example, here's a predicate that's satisfied by any number that is >= 0, <= 100, and != 50: ``` Matches(AllOf(Ge(0), Le(100), Ne(50))) ``` ## Using Matchers in Google Test Assertions ## Since matchers are basically predicates that also know how to describe themselves, there is a way to take advantage of them in [Google Test](../../googletest/) assertions. It's called `ASSERT_THAT` and `EXPECT_THAT`: ``` ASSERT_THAT(value, matcher); // Asserts that value matches matcher. EXPECT_THAT(value, matcher); // The non-fatal version. ``` For example, in a Google Test test you can write: ``` #include "gmock/gmock.h" using ::testing::AllOf; using ::testing::Ge; using ::testing::Le; using ::testing::MatchesRegex; using ::testing::StartsWith; ... EXPECT_THAT(Foo(), StartsWith("Hello")); EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); ``` which (as you can probably guess) executes `Foo()`, `Bar()`, and `Baz()`, and verifies that: * `Foo()` returns a string that starts with `"Hello"`. * `Bar()` returns a string that matches regular expression `"Line \\d+"`. * `Baz()` returns a number in the range [5, 10]. The nice thing about these macros is that _they read like English_. They generate informative messages too. For example, if the first `EXPECT_THAT()` above fails, the message will be something like: ``` Value of: Foo() Actual: "Hi, world!" Expected: starts with "Hello" ``` **Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the [Hamcrest](https://github.com/hamcrest/) project, which adds `assertThat()` to JUnit. ## Using Predicates as Matchers ## Google Mock provides a built-in set of matchers. In case you find them lacking, you can use an arbitray unary predicate function or functor as a matcher - as long as the predicate accepts a value of the type you want. You do this by wrapping the predicate inside the `Truly()` function, for example: ``` using ::testing::Truly; int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } ... // Bar() must be called with an even number. EXPECT_CALL(foo, Bar(Truly(IsEven))); ``` Note that the predicate function / functor doesn't have to return `bool`. It works as long as the return value can be used as the condition in statement `if (condition) ...`. ## Matching Arguments that Are Not Copyable ## When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves away a copy of `bar`. When `Foo()` is called later, Google Mock compares the argument to `Foo()` with the saved copy of `bar`. This way, you don't need to worry about `bar` being modified or destroyed after the `EXPECT_CALL()` is executed. The same is true when you use matchers like `Eq(bar)`, `Le(bar)`, and so on. But what if `bar` cannot be copied (i.e. has no copy constructor)? You could define your own matcher function and use it with `Truly()`, as the previous couple of recipes have shown. Or, you may be able to get away from it if you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is executed. Just tell Google Mock that it should save a reference to `bar`, instead of a copy of it. Here's how: ``` using ::testing::Eq; using ::testing::ByRef; using ::testing::Lt; ... // Expects that Foo()'s argument == bar. EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); // Expects that Foo()'s argument < bar. EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); ``` Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the result is undefined. ## Validating a Member of an Object ## Often a mock function takes a reference to object as an argument. When matching the argument, you may not want to compare the entire object against a fixed object, as that may be over-specification. Instead, you may need to validate a certain member variable or the result of a certain getter method of the object. You can do this with `Field()` and `Property()`. More specifically, ``` Field(&Foo::bar, m) ``` is a matcher that matches a `Foo` object whose `bar` member variable satisfies matcher `m`. ``` Property(&Foo::baz, m) ``` is a matcher that matches a `Foo` object whose `baz()` method returns a value that satisfies matcher `m`. For example: -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| Expression | Description | |:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | +| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | +| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument and be declared as `const`. BTW, `Field()` and `Property()` can also match plain pointers to objects. For instance, ``` Field(&Foo::number, Ge(3)) ``` matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match will always fail regardless of the inner matcher. What if you want to validate more than one members at the same time? Remember that there is `AllOf()`. ## Validating the Value Pointed to by a Pointer Argument ## C++ functions often take pointers as arguments. You can use matchers like `IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but what if you want to make sure the value _pointed to_ by the pointer, instead of the pointer itself, has a certain property? Well, you can use the `Pointee(m)` matcher. `Pointee(m)` matches a pointer iff `m` matches the value the pointer points to. For example: ``` using ::testing::Ge; using ::testing::Pointee; ... EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); ``` expects `foo.Bar()` to be called with a pointer that points to a value greater than or equal to 3. One nice thing about `Pointee()` is that it treats a `NULL` pointer as a match failure, so you can write `Pointee(m)` instead of ``` AllOf(NotNull(), Pointee(m)) ``` without worrying that a `NULL` pointer will crash your test. Also, did we tell you that `Pointee()` works with both raw pointers **and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and etc)? What if you have a pointer to pointer? You guessed it - you can use nested `Pointee()` to probe deeper inside the value. For example, `Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points to a number less than 3 (what a mouthful...). ## Testing a Certain Property of an Object ## Sometimes you want to specify that an object argument has a certain property, but there is no existing matcher that does this. If you want good error messages, you should define a matcher. If you want to do it quick and dirty, you could get away with writing an ordinary function. Let's say you have a mock function that takes an object of type `Foo`, which has an `int bar()` method and an `int baz()` method, and you want to constrain that the argument's `bar()` value plus its `baz()` value is a given number. Here's how you can define a matcher to do it: ``` using ::testing::MatcherInterface; using ::testing::MatchResultListener; class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> { public: explicit BarPlusBazEqMatcher(int expected_sum) : expected_sum_(expected_sum) {} virtual bool MatchAndExplain(const Foo& foo, MatchResultListener* listener) const { return (foo.bar() + foo.baz()) == expected_sum_; } virtual void DescribeTo(::std::ostream* os) const { *os << "bar() + baz() equals " << expected_sum_; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "bar() + baz() does not equal " << expected_sum_; } private: const int expected_sum_; }; inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) { return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); } ... EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; ``` ## Matching Containers ## Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock function and you may want to validate it. Since most STL containers support the `==` operator, you can write `Eq(expected_container)` or simply `expected_container` to match a container exactly. Sometimes, though, you may want to be more flexible (for example, the first element must be an exact match, but the second element can be any positive number, and so on). Also, containers used in tests often have a small number of elements, and having to define the expected container out-of-line is a bit of a hassle. You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such cases: ``` using ::testing::_; using ::testing::ElementsAre; using ::testing::Gt; ... MOCK_METHOD1(Foo, void(const vector<int>& numbers)); ... EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); ``` The above matcher says that the container must have 4 elements, which must be 1, greater than 0, anything, and 5 respectively. If you instead write: ``` using ::testing::_; using ::testing::Gt; using ::testing::UnorderedElementsAre; ... MOCK_METHOD1(Foo, void(const vector<int>& numbers)); ... EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); ``` It means that the container must have 4 elements, which under some permutation must be 1, greater than 0, anything, and 5 respectively. `ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0 to 10 arguments. If more are needed, you can place them in a C-style array and use `ElementsAreArray()` or `UnorderedElementsAreArray()` instead: ``` using ::testing::ElementsAreArray; ... // ElementsAreArray accepts an array of element values. const int expected_vector1[] = { 1, 5, 2, 4, ... }; EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); // Or, an array of element matchers. Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... }; EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); ``` In case the array needs to be dynamically created (and therefore the array size cannot be inferred by the compiler), you can give `ElementsAreArray()` an additional argument to specify the array size: ``` using ::testing::ElementsAreArray; ... int* const expected_vector3 = new int[count]; ... fill expected_vector3 with values ... EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); ``` **Tips:** * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers. * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). ## Sharing Matchers ## Under the hood, a Google Mock matcher object consists of a pointer to a ref-counted implementation object. Copying matchers is allowed and very efficient, as only the pointer is copied. When the last matcher that references the implementation object dies, the implementation object will be deleted. Therefore, if you have some complex matcher that you want to use again and again, there is no need to build it everytime. Just assign it to a matcher variable and use that variable repeatedly! For example, ``` Matcher<int> in_range = AllOf(Gt(5), Le(10)); ... use in_range as a matcher in multiple EXPECT_CALLs ... ``` # Setting Expectations # ## Knowing When to Expect ## `ON_CALL` is likely the single most under-utilized construct in Google Mock. There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too). Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints. This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests? The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed. Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself. So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them). If you are bothered by the "Uninteresting mock function call" message printed when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` instead to suppress all such messages for the mock object, or suppress the message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test that's a pain to maintain. ## Ignoring Uninteresting Calls ## If you are not interested in how a mock method is called, just don't say anything about it. In this case, if the method is ever called, Google Mock will perform its default action to allow the test program to continue. If you are not happy with the default action taken by Google Mock, you can override it using `DefaultValue<T>::Set()` (described later in this document) or `ON_CALL()`. Please note that once you expressed interest in a particular mock method (via `EXPECT_CALL()`), all invocations to it must match some expectation. If this function is called but the arguments don't match any `EXPECT_CALL()` statement, it will be an error. ## Disallowing Unexpected Calls ## If a mock method shouldn't be called at all, explicitly say so: ``` using ::testing::_; ... EXPECT_CALL(foo, Bar(_)) .Times(0); ``` If some calls to the method are allowed, but the rest are not, just list all the expected calls: ``` using ::testing::AnyNumber; using ::testing::Gt; ... EXPECT_CALL(foo, Bar(5)); EXPECT_CALL(foo, Bar(Gt(10))) .Times(AnyNumber()); ``` A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements will be an error. ## Understanding Uninteresting vs Unexpected Calls ## _Uninteresting_ calls and _unexpected_ calls are different concepts in Google Mock. _Very_ different. A call `x.Y(...)` is **uninteresting** if there's _not even a single_ `EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the `x.Y()` method at all, as evident in that the test doesn't care to say anything about it. A call `x.Y(...)` is **unexpected** if there are some `EXPECT_CALL(x, Y(...))s` set, but none of them matches the call. Put another way, the test is interested in the `x.Y()` method (therefore it _explicitly_ sets some `EXPECT_CALL` to verify how it's called); however, the verification fails as the test doesn't expect this particular call to happen. **An unexpected call is always an error,** as the code under test doesn't behave the way the test expects it to behave. **By default, an uninteresting call is not an error,** as it violates no constraint specified by the test. (Google Mock's philosophy is that saying nothing means there is no constraint.) However, it leads to a warning, as it _might_ indicate a problem (e.g. the test author might have forgotten to specify a constraint). In Google Mock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or "strict". How does this affect uninteresting calls and unexpected calls? A **nice mock** suppresses uninteresting call warnings. It is less chatty than the default mock, but otherwise is the same. If a test fails with a default mock, it will also fail using a nice mock instead. And vice versa. Don't expect making a mock nice to change the test's result. A **strict mock** turns uninteresting call warnings into errors. So making a mock strict may change the test's result. Let's look at an example: ``` TEST(...) { NiceMock<MockDomainRegistry> mock_registry; EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) .WillRepeatedly(Return("Larry Page")); // Use mock_registry in code under test. ... &mock_registry ... } ``` The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have `"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it will be an unexpected call, and thus an error. Having a nice mock doesn't change the severity of an unexpected call. So how do we tell Google Mock that `GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: ``` EXPECT_CALL(mock_registry, GetDomainOwner(_)) .Times(AnyNumber()); // catches all other calls to this method. EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) .WillRepeatedly(Return("Larry Page")); ``` Remember that `_` is the wildcard matcher that matches anything. With this, if `GetDomainOwner("google.com")` is called, it will do what the second `EXPECT_CALL` says; if it is called with a different argument, it will do what the first `EXPECT_CALL` says. Note that the order of the two `EXPECT_CALLs` is important, as a newer `EXPECT_CALL` takes precedence over an older one. For more on uninteresting calls, nice mocks, and strict mocks, read ["The Nice, the Strict, and the Naggy"](#the-nice-the-strict-and-the-naggy). ## Expecting Ordered Calls ## Although an `EXPECT_CALL()` statement defined earlier takes precedence when Google Mock tries to match a function call with an expectation, by default calls don't have to happen in the order `EXPECT_CALL()` statements are written. For example, if the arguments match the matchers in the third `EXPECT_CALL()`, but not those in the first two, then the third expectation will be used. If you would rather have all calls occur in the order of the expectations, put the `EXPECT_CALL()` statements in a block where you define a variable of type `InSequence`: ``` using ::testing::_; using ::testing::InSequence; { InSequence s; EXPECT_CALL(foo, DoThis(5)); EXPECT_CALL(bar, DoThat(_)) .Times(2); EXPECT_CALL(foo, DoThis(6)); } ``` In this example, we expect a call to `foo.DoThis(5)`, followed by two calls to `bar.DoThat()` where the argument can be anything, which are in turn followed by a call to `foo.DoThis(6)`. If a call occurred out-of-order, Google Mock will report an error. ## Expecting Partially Ordered Calls ## Sometimes requiring everything to occur in a predetermined order can lead to brittle tests. For example, we may care about `A` occurring before both `B` and `C`, but aren't interested in the relative order of `B` and `C`. In this case, the test should reflect our real intent, instead of being overly constraining. Google Mock allows you to impose an arbitrary DAG (directed acyclic graph) on the calls. One way to express the DAG is to use the [After](CheatSheet.md#the-after-clause) clause of `EXPECT_CALL`. Another way is via the `InSequence()` clause (not the same as the `InSequence` class), which we borrowed from jMock 2. It's less flexible than `After()`, but more convenient when you have long chains of sequential calls, as it doesn't require you to come up with different names for the expectations in the chains. Here's how it works: If we view `EXPECT_CALL()` statements as nodes in a graph, and add an edge from node A to node B wherever A must occur before B, we can get a DAG. We use the term "sequence" to mean a directed path in this DAG. Now, if we decompose the DAG into sequences, we just need to know which sequences each `EXPECT_CALL()` belongs to in order to be able to reconstruct the orginal DAG. So, to specify the partial order on the expectations we need to do two things: first to define some `Sequence` objects, and then for each `EXPECT_CALL()` say which `Sequence` objects it is part of. Expectations in the same sequence must occur in the order they are written. For example, ``` using ::testing::Sequence; Sequence s1, s2; EXPECT_CALL(foo, A()) .InSequence(s1, s2); EXPECT_CALL(bar, B()) .InSequence(s1); EXPECT_CALL(bar, C()) .InSequence(s2); EXPECT_CALL(foo, D()) .InSequence(s2); ``` specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`): ``` +---> B | A ---| | +---> C ---> D ``` This means that A must occur before B and C, and C must occur before D. There's no restriction about the order other than these. ## Controlling When an Expectation Retires ## When a mock method is called, Google Mock only consider expectations that are still active. An expectation is active when created, and becomes inactive (aka _retires_) when a call that has to occur later has occurred. For example, in ``` using ::testing::_; using ::testing::Sequence; Sequence s1, s2; EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 .Times(AnyNumber()) .InSequence(s1, s2); EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 .InSequence(s1); EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 .InSequence(s2); ``` as soon as either #2 or #3 is matched, #1 will retire. If a warning `"File too large."` is logged after this, it will be an error. Note that an expectation doesn't retire automatically when it's saturated. For example, ``` using ::testing::_; ... EXPECT_CALL(log, Log(WARNING, _, _)); // #1 EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 ``` says that there will be exactly one warning with the message `"File too large."`. If the second warning contains this message too, #2 will match again and result in an upper-bound-violated error. If this is not what you want, you can ask an expectation to retire as soon as it becomes saturated: ``` using ::testing::_; ... EXPECT_CALL(log, Log(WARNING, _, _)); // #1 EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 .RetiresOnSaturation(); ``` Here #2 can be used only once, so if you have two warnings with the message `"File too large."`, the first will match #2 and the second will match #1 - there will be no error. # Using Actions # ## Returning References from Mock Methods ## If a mock function's return type is a reference, you need to use `ReturnRef()` instead of `Return()` to return a result: ``` using ::testing::ReturnRef; class MockFoo : public Foo { public: MOCK_METHOD0(GetBar, Bar&()); }; ... MockFoo foo; Bar bar; EXPECT_CALL(foo, GetBar()) .WillOnce(ReturnRef(bar)); ``` ## Returning Live Values from Mock Methods ## The `Return(x)` action saves a copy of `x` when the action is _created_, and always returns the same value whenever it's executed. Sometimes you may want to instead return the _live_ value of `x` (i.e. its value at the time when the action is _executed_.). If the mock function's return type is a reference, you can do it using `ReturnRef(x)`, as shown in the previous recipe ("Returning References from Mock Methods"). However, Google Mock doesn't let you use `ReturnRef()` in a mock function whose return type is not a reference, as doing that usually indicates a user error. So, what shall you do? You may be tempted to try `ByRef()`: ``` using testing::ByRef; using testing::Return; class MockFoo : public Foo { public: MOCK_METHOD0(GetValue, int()); }; ... int x = 0; MockFoo foo; EXPECT_CALL(foo, GetValue()) .WillRepeatedly(Return(ByRef(x))); x = 42; EXPECT_EQ(42, foo.GetValue()); ``` Unfortunately, it doesn't work here. The above code will fail with error: ``` Value of: foo.GetValue() Actual: 0 Expected: 42 ``` The reason is that `Return(value)` converts `value` to the actual return type of the mock function at the time when the action is _created_, not when it is _executed_. (This behavior was chosen for the action to be safe when `value` is a proxy object that references some temporary objects.) As a result, `ByRef(x)` is converted to an `int` value (instead of a `const int&`) when the expectation is set, and `Return(ByRef(x))` will always return 0. `ReturnPointee(pointer)` was provided to solve this problem specifically. It returns the value pointed to by `pointer` at the time the action is _executed_: ``` using testing::ReturnPointee; ... int x = 0; MockFoo foo; EXPECT_CALL(foo, GetValue()) .WillRepeatedly(ReturnPointee(&x)); // Note the & here. x = 42; EXPECT_EQ(42, foo.GetValue()); // This will succeed now. ``` ## Combining Actions ## Want to do more than one thing when a function is called? That's fine. `DoAll()` allow you to do sequence of actions every time. Only the return value of the last action in the sequence will be used. ``` using ::testing::DoAll; class MockFoo : public Foo { public: MOCK_METHOD1(Bar, bool(int n)); }; ... EXPECT_CALL(foo, Bar(_)) .WillOnce(DoAll(action_1, action_2, ... action_n)); ``` ## Mocking Side Effects ## Sometimes a method exhibits its effect not via returning a value but via side effects. For example, it may change some global state or modify an output argument. To mock side effects, in general you can define your own action by implementing `::testing::ActionInterface`. If all you need to do is to change an output argument, the built-in `SetArgPointee()` action is convenient: ``` using ::testing::SetArgPointee; class MockMutator : public Mutator { public: MOCK_METHOD2(Mutate, void(bool mutate, int* value)); ... }; ... MockMutator mutator; EXPECT_CALL(mutator, Mutate(true, _)) .WillOnce(SetArgPointee<1>(5)); ``` In this example, when `mutator.Mutate()` is called, we will assign 5 to the `int` variable pointed to by argument #1 (0-based). `SetArgPointee()` conveniently makes an internal copy of the value you pass to it, removing the need to keep the value in scope and alive. The implication however is that the value must have a copy constructor and assignment operator. If the mock method also needs to return a value as well, you can chain `SetArgPointee()` with `Return()` using `DoAll()`: ``` using ::testing::_; using ::testing::Return; using ::testing::SetArgPointee; class MockMutator : public Mutator { public: ... MOCK_METHOD1(MutateInt, bool(int* value)); }; ... MockMutator mutator; EXPECT_CALL(mutator, MutateInt(_)) .WillOnce(DoAll(SetArgPointee<0>(5), Return(true))); ``` If the output argument is an array, use the `SetArrayArgument<N>(first, last)` action instead. It copies the elements in source range `[first, last)` to the array pointed to by the `N`-th (0-based) argument: ``` using ::testing::NotNull; using ::testing::SetArrayArgument; class MockArrayMutator : public ArrayMutator { public: MOCK_METHOD2(Mutate, void(int* values, int num_values)); ... }; ... MockArrayMutator mutator; int values[5] = { 1, 2, 3, 4, 5 }; EXPECT_CALL(mutator, Mutate(NotNull(), 5)) .WillOnce(SetArrayArgument<0>(values, values + 5)); ``` This also works when the argument is an output iterator: ``` using ::testing::_; -using ::testing::SeArrayArgument; +using ::testing::SetArrayArgument; class MockRolodex : public Rolodex { public: MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >)); ... }; ... MockRolodex rolodex; vector<string> names; names.push_back("George"); names.push_back("John"); names.push_back("Thomas"); EXPECT_CALL(rolodex, GetNames(_)) .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); ``` ## Changing a Mock Object's Behavior Based on the State ## If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: ``` using ::testing::InSequence; using ::testing::Return; ... { InSequence seq; EXPECT_CALL(my_mock, IsDirty()) .WillRepeatedly(Return(true)); EXPECT_CALL(my_mock, Flush()); EXPECT_CALL(my_mock, IsDirty()) .WillRepeatedly(Return(false)); } my_mock.FlushIfDirty(); ``` This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: ``` using ::testing::_; using ::testing::SaveArg; using ::testing::Return; ACTION_P(ReturnPointee, p) { return *p; } ... int previous_value = 0; EXPECT_CALL(my_mock, GetPrevValue()) .WillRepeatedly(ReturnPointee(&previous_value)); EXPECT_CALL(my_mock, UpdateValue(_)) .WillRepeatedly(SaveArg<0>(&previous_value)); my_mock.DoSomethingToUpdateValue(); ``` Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. ## Setting the Default Value for a Return Type ## If a mock method's return type is a built-in C++ type or pointer, by default it will return 0 when invoked. Also, in C++ 11 and above, a mock method whose return type has a default constructor will return a default-constructed value by default. You only need to specify an action if this default value doesn't work for you. Sometimes, you may want to change this default value, or you may want to specify a default value for types Google Mock doesn't know about. You can do this using the `::testing::DefaultValue` class template: ``` class MockFoo : public Foo { public: MOCK_METHOD0(CalculateBar, Bar()); }; ... Bar default_bar; // Sets the default return value for type Bar. DefaultValue<Bar>::Set(default_bar); MockFoo foo; // We don't need to specify an action here, as the default // return value works for us. EXPECT_CALL(foo, CalculateBar()); foo.CalculateBar(); // This should return default_bar. // Unsets the default return value. DefaultValue<Bar>::Clear(); ``` Please note that changing the default value for a type can make you tests hard to understand. We recommend you to use this feature judiciously. For example, you may want to make sure the `Set()` and `Clear()` calls are right next to the code that uses your mock. ## Setting the Default Actions for a Mock Method ## You've learned how to change the default value of a given type. However, this may be too coarse for your purpose: perhaps you have two mock methods with the same return type and you want them to have different behaviors. The `ON_CALL()` macro allows you to customize your mock's behavior at the method level: ``` using ::testing::_; using ::testing::AnyNumber; using ::testing::Gt; using ::testing::Return; ... ON_CALL(foo, Sign(_)) .WillByDefault(Return(-1)); ON_CALL(foo, Sign(0)) .WillByDefault(Return(0)); ON_CALL(foo, Sign(Gt(0))) .WillByDefault(Return(1)); EXPECT_CALL(foo, Sign(_)) .Times(AnyNumber()); foo.Sign(5); // This should return 1. foo.Sign(-9); // This should return -1. foo.Sign(0); // This should return 0. ``` As you may have guessed, when there are more than one `ON_CALL()` statements, the news order take precedence over the older ones. In other words, the **last** one that matches the function arguments will be used. This matching order allows you to set up the common behavior in a mock object's constructor or the test fixture's set-up phase and specialize the mock's behavior later. ## Using Functions/Methods/Functors as Actions ## If the built-in actions don't suit you, you can easily use an existing function, method, or functor as an action: ``` using ::testing::_; using ::testing::Invoke; class MockFoo : public Foo { public: MOCK_METHOD2(Sum, int(int x, int y)); MOCK_METHOD1(ComplexJob, bool(int x)); }; int CalculateSum(int x, int y) { return x + y; } class Helper { public: bool ComplexJob(int x); }; ... MockFoo foo; Helper helper; EXPECT_CALL(foo, Sum(_, _)) .WillOnce(Invoke(CalculateSum)); EXPECT_CALL(foo, ComplexJob(_)) .WillOnce(Invoke(&helper, &Helper::ComplexJob)); foo.Sum(5, 6); // Invokes CalculateSum(5, 6). foo.ComplexJob(10); // Invokes helper.ComplexJob(10); ``` The only requirement is that the type of the function, etc must be _compatible_ with the signature of the mock function, meaning that the latter's arguments can be implicitly converted to the corresponding arguments of the former, and the former's return type can be implicitly converted to that of the latter. So, you can invoke something whose type is _not_ exactly the same as the mock function, as long as it's safe to do so - nice, huh? ## Invoking a Function/Method/Functor Without Arguments ## `Invoke()` is very useful for doing actions that are more complex. It passes the mock function's arguments to the function or functor being invoked such that the callee has the full context of the call to work with. If the invoked function is not interested in some or all of the arguments, it can simply ignore them. Yet, a common pattern is that a test author wants to invoke a function without the arguments of the mock function. `Invoke()` allows her to do that using a wrapper function that throws away the arguments before invoking an underlining nullary function. Needless to say, this can be tedious and obscures the intent of the test. `InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except that it doesn't pass the mock function's arguments to the callee. Here's an example: ``` using ::testing::_; using ::testing::InvokeWithoutArgs; class MockFoo : public Foo { public: MOCK_METHOD1(ComplexJob, bool(int n)); }; bool Job1() { ... } ... MockFoo foo; EXPECT_CALL(foo, ComplexJob(_)) .WillOnce(InvokeWithoutArgs(Job1)); foo.ComplexJob(10); // Invokes Job1(). ``` ## Invoking an Argument of the Mock Function ## Sometimes a mock function will receive a function pointer or a functor (in other words, a "callable") as an argument, e.g. ``` class MockFoo : public Foo { public: MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); }; ``` and you may want to invoke this callable argument: ``` using ::testing::_; ... MockFoo foo; EXPECT_CALL(foo, DoThis(_, _)) .WillOnce(...); // Will execute (*fp)(5), where fp is the // second argument DoThis() receives. ``` -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? +Arghh, you need to refer to a mock function argument but your version +of C++ has no lambdas, so you have to define your own action. :-( +Or do you really? Well, Google Mock has an action to solve _exactly_ this problem: ``` InvokeArgument<N>(arg_1, arg_2, ..., arg_m) ``` will invoke the `N`-th (0-based) argument the mock function receives, with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is a function pointer or a functor, Google Mock handles them both. With that, you could write: ``` using ::testing::_; using ::testing::InvokeArgument; ... EXPECT_CALL(foo, DoThis(_, _)) .WillOnce(InvokeArgument<1>(5)); // Will execute (*fp)(5), where fp is the // second argument DoThis() receives. ``` What if the callable takes an argument by reference? No problem - just wrap it inside `ByRef()`: ``` ... MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); ... using ::testing::_; using ::testing::ByRef; using ::testing::InvokeArgument; ... MockFoo foo; Helper helper; ... EXPECT_CALL(foo, Bar(_)) .WillOnce(InvokeArgument<0>(5, ByRef(helper))); // ByRef(helper) guarantees that a reference to helper, not a copy of it, // will be passed to the callable. ``` What if the callable takes an argument by reference and we do **not** wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a copy_ of the argument, and pass a _reference to the copy_, instead of a reference to the original value, to the callable. This is especially handy when the argument is a temporary value: ``` ... MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); ... using ::testing::_; using ::testing::InvokeArgument; ... MockFoo foo; ... EXPECT_CALL(foo, DoThat(_)) .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); // Will execute (*f)(5.0, string("Hi")), where f is the function pointer // DoThat() receives. Note that the values 5.0 and string("Hi") are // temporary and dead once the EXPECT_CALL() statement finishes. Yet // it's fine to perform this action later, since a copy of the values // are kept inside the InvokeArgument action. ``` ## Ignoring an Action's Result ## Sometimes you have an action that returns _something_, but you need an action that returns `void` (perhaps you want to use it in a mock function that returns `void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the list). `IgnoreResult()` lets you do that. For example: ``` using ::testing::_; using ::testing::Invoke; using ::testing::Return; int Process(const MyData& data); string DoSomething(); class MockFoo : public Foo { public: MOCK_METHOD1(Abc, void(const MyData& data)); MOCK_METHOD0(Xyz, bool()); }; ... MockFoo foo; EXPECT_CALL(foo, Abc(_)) // .WillOnce(Invoke(Process)); // The above line won't compile as Process() returns int but Abc() needs // to return void. .WillOnce(IgnoreResult(Invoke(Process))); EXPECT_CALL(foo, Xyz()) .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), // Ignores the string DoSomething() returns. Return(true))); ``` Note that you **cannot** use `IgnoreResult()` on an action that already returns `void`. Doing so will lead to ugly compiler errors. ## Selecting an Action's Arguments ## Say you have a mock function `Foo()` that takes seven arguments, and you have a custom action that you want to invoke when `Foo()` is called. Trouble is, the custom action only wants three arguments: ``` using ::testing::_; using ::testing::Invoke; ... MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, const map<pair<int, int>, double>& weight, double min_weight, double max_wight)); ... bool IsVisibleInQuadrant1(bool visible, int x, int y) { return visible && x >= 0 && y >= 0; } ... EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( ``` To please the compiler God, you can to define an "adaptor" that has the same signature as `Foo()` and calls the custom action with the right arguments: ``` using ::testing::_; using ::testing::Invoke; bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, const map<pair<int, int>, double>& weight, double min_weight, double max_wight) { return IsVisibleInQuadrant1(visible, x, y); } ... EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. ``` But isn't this awkward? Google Mock provides a generic _action adaptor_, so you can spend your time minding more important business than writing your own adaptors. Here's the syntax: ``` WithArgs<N1, N2, ..., Nk>(action) ``` creates an action that passes the arguments of the mock function at the given indices (0-based) to the inner `action` and performs it. Using `WithArgs`, our original example can be written as: ``` using ::testing::_; using ::testing::Invoke; using ::testing::WithArgs; ... EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); // No need to define your own adaptor. ``` For better readability, Google Mock also gives you: * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. As you may have realized, `InvokeWithoutArgs(...)` is just syntactic sugar for `WithoutArgs(Invoke(...))`. Here are more tips: * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. ## Ignoring Arguments in Action Functions ## The selecting-an-action's-arguments recipe showed us one way to make a mock function and an action with incompatible argument lists fit together. The downside is that wrapping the action in `WithArgs<...>()` can get tedious for people writing the tests. If you are defining a function, method, or functor to be used with `Invoke*()`, and you are not interested in some of its arguments, an alternative to `WithArgs` is to declare the uninteresting arguments as `Unused`. This makes the definition less cluttered and less fragile in case the types of the uninteresting arguments change. It could also increase the chance the action function can be reused. For example, given ``` MOCK_METHOD3(Foo, double(const string& label, double x, double y)); MOCK_METHOD3(Bar, double(int index, double x, double y)); ``` instead of ``` using ::testing::_; using ::testing::Invoke; double DistanceToOriginWithLabel(const string& label, double x, double y) { return sqrt(x*x + y*y); } double DistanceToOriginWithIndex(int index, double x, double y) { return sqrt(x*x + y*y); } ... EXEPCT_CALL(mock, Foo("abc", _, _)) .WillOnce(Invoke(DistanceToOriginWithLabel)); EXEPCT_CALL(mock, Bar(5, _, _)) .WillOnce(Invoke(DistanceToOriginWithIndex)); ``` you could write ``` using ::testing::_; using ::testing::Invoke; using ::testing::Unused; double DistanceToOrigin(Unused, double x, double y) { return sqrt(x*x + y*y); } ... EXEPCT_CALL(mock, Foo("abc", _, _)) .WillOnce(Invoke(DistanceToOrigin)); EXEPCT_CALL(mock, Bar(5, _, _)) .WillOnce(Invoke(DistanceToOrigin)); ``` ## Sharing Actions ## Just like matchers, a Google Mock action object consists of a pointer to a ref-counted implementation object. Therefore copying actions is also allowed and very efficient. When the last action that references the implementation object dies, the implementation object will be deleted. If you have some complex action that you want to use again and again, you may not have to build it from scratch everytime. If the action doesn't have an internal state (i.e. if it always does the same thing no matter how many times it has been called), you can assign it to an action variable and use that variable repeatedly. For example: ``` Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5), Return(true)); ... use set_flag in .WillOnce() and .WillRepeatedly() ... ``` However, if the action has its own state, you may be surprised if you share the action object. Suppose you have an action factory `IncrementCounter(init)` which creates an action that increments and returns a counter whose initial value is `init`, using two actions created from the same expression and using a shared action will exihibit different behaviors. Example: ``` EXPECT_CALL(foo, DoThis()) .WillRepeatedly(IncrementCounter(0)); EXPECT_CALL(foo, DoThat()) .WillRepeatedly(IncrementCounter(0)); foo.DoThis(); // Returns 1. foo.DoThis(); // Returns 2. foo.DoThat(); // Returns 1 - Blah() uses a different // counter than Bar()'s. ``` versus ``` Action<int()> increment = IncrementCounter(0); EXPECT_CALL(foo, DoThis()) .WillRepeatedly(increment); EXPECT_CALL(foo, DoThat()) .WillRepeatedly(increment); foo.DoThis(); // Returns 1. foo.DoThis(); // Returns 2. foo.DoThat(); // Returns 3 - the counter is shared. ``` # Misc Recipes on Using Google Mock # ## Mocking Methods That Use Move-Only Types ## C++11 introduced <em>move-only types</em>. A move-only-typed value can be moved from one object to another, but cannot be copied. `std::unique_ptr<T>` is probably the most commonly used move-only type. Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable. This recipe shows you how you can do it. Let’s say we are working on a fictional project that lets one post and share snippets called “buzzes”. Your code uses these types: ``` enum class AccessLevel { kInternal, kPublic }; class Buzz { public: explicit Buzz(AccessLevel access) { … } ... }; class Buzzer { public: virtual ~Buzzer() {} virtual std::unique_ptr<Buzz> MakeBuzz(const std::string& text) = 0; virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) = 0; ... }; ``` A `Buzz` object represents a snippet being posted. A class that implements the `Buzzer` interface is capable of creating and sharing `Buzz`. Methods in `Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`. Now we need to mock `Buzzer` in our tests. To mock a method that returns a move-only type, you just use the familiar `MOCK_METHOD` syntax as usual: ``` class MockBuzzer : public Buzzer { public: MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text)); … }; ``` However, if you attempt to use the same `MOCK_METHOD` pattern to mock a method that takes a move-only parameter, you’ll get a compiler error currently: ``` // Does NOT compile! MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr<Buzz> buzz, Time timestamp)); ``` While it’s highly desirable to make this syntax just work, it’s not trivial and the work hasn’t been done yet. Fortunately, there is a trick you can apply today to get something that works nearly as well as this. The trick, is to delegate the `ShareBuzz()` method to a mock method (let’s call it `DoShareBuzz()`) that does not take move-only parameters: ``` class MockBuzzer : public Buzzer { public: MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text)); MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) { return DoShareBuzz(buzz.get(), timestamp); } }; ``` Note that there's no need to define or declare `DoShareBuzz()` in a base class. You only need to define it as a `MOCK_METHOD` in the mock class. Now that we have the mock class defined, we can use it in tests. In the following code examples, we assume that we have defined a `MockBuzzer` object named `mock_buzzer_`: ``` MockBuzzer mock_buzzer_; ``` First let’s see how we can set expectations on the `MakeBuzz()` method, which returns a `unique_ptr<Buzz>`. As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or `.WillRepeated()` clause), when that expectation fires, the default action for that method will be taken. Since `unique_ptr<>` has a default constructor that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an action: ``` // Use the default action. EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); // Triggers the previous EXPECT_CALL. EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); ``` If you are not happy with the default action, you can tweak it. Depending on what you need, you may either tweak the default action for a specific (mock object, mock method) combination using `ON_CALL()`, or you may tweak the default action for all mock methods that return a specific type. The usage of `ON_CALL()` is similar to `EXPECT_CALL()`, so we’ll skip it and just explain how to do the latter (tweaking the default action for a specific return type). You do this via the `DefaultValue<>::SetFactory()` and `DefaultValue<>::Clear()` API: ``` // Sets the default action for return type std::unique_ptr<Buzz> to // creating a new Buzz every time. DefaultValue<std::unique_ptr<Buzz>>::SetFactory( [] { return MakeUnique<Buzz>(AccessLevel::kInternal); }); // When this fires, the default action of MakeBuzz() will run, which // will return a new Buzz object. EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); auto buzz1 = mock_buzzer_.MakeBuzz("hello"); auto buzz2 = mock_buzzer_.MakeBuzz("hello"); EXPECT_NE(nullptr, buzz1); EXPECT_NE(nullptr, buzz2); EXPECT_NE(buzz1, buzz2); // Resets the default action for return type std::unique_ptr<Buzz>, // to avoid interfere with other tests. DefaultValue<std::unique_ptr<Buzz>>::Clear(); ``` What if you want the method to do something other than the default action? If you just need to return a pre-defined move-only value, you can use the `Return(ByMove(...))` action: ``` // When this fires, the unique_ptr<> specified by ByMove(...) will // be returned. EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) .WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal)))); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world")); ``` Note that `ByMove()` is essential here - if you drop it, the code won’t compile. Quiz time! What do you think will happen if a `Return(ByMove(...))` action is performed more than once (e.g. you write `….WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from -- you’ll get a run-time error that `Return(ByMove(...))` can only be run once. If you need your mock method to do more than just moving a pre-defined value, remember that you can always use `Invoke()` to call a lambda or a callable object, which can do pretty much anything you want: ``` EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) .WillRepeatedly(Invoke([](const std::string& text) { return std::make_unique<Buzz>(AccessLevel::kInternal); })); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); ``` Every time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created and returned. You cannot do this with `Return(ByMove(...))`. Now there’s one topic we haven’t covered: how do you set expectations on `ShareBuzz()`, which takes a move-only-typed parameter? The answer is you don’t. Instead, you set expectations on the `DoShareBuzz()` mock method (remember that we defined a `MOCK_METHOD` for `DoShareBuzz()`, not `ShareBuzz()`): ``` EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); // When one calls ShareBuzz() on the MockBuzzer like this, the call is // forwarded to DoShareBuzz(), which is mocked. Therefore this statement // will trigger the above EXPECT_CALL. - mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), + mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), ::base::Now()); ``` Some of you may have spotted one problem with this approach: the `DoShareBuzz()` mock method differs from the real `ShareBuzz()` method in that it cannot take ownership of the buzz parameter - `ShareBuzz()` will always delete buzz after `DoShareBuzz()` returns. What if you need to save the buzz object somewhere for later use when `ShareBuzz()` is called? Indeed, you'd be stuck. Another problem with the `DoShareBuzz()` we had is that it can surprise people reading or maintaining the test, as one would expect that `DoShareBuzz()` has (logically) the same contract as `ShareBuzz()`. Fortunately, these problems can be fixed with a bit more code. Let's try to get it right this time: ``` class MockBuzzer : public Buzzer { public: MockBuzzer() { // Since DoShareBuzz(buzz, time) is supposed to take ownership of // buzz, define a default behavior for DoShareBuzz(buzz, time) to // delete buzz. ON_CALL(*this, DoShareBuzz(_, _)) .WillByDefault(Invoke([](Buzz* buzz, Time timestamp) { delete buzz; return true; })); } MOCK_METHOD1(MakeBuzz, std::unique_ptr<Buzz>(const std::string& text)); // Takes ownership of buzz. MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) { return DoShareBuzz(buzz.release(), timestamp); } }; ``` Now, the mock `DoShareBuzz()` method is free to save the buzz argument for later use if this is what you want: ``` std::unique_ptr<Buzz> intercepted_buzz; EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)) - .WillOnce(Invoke([&intercepted_buzz](Buzz* buzz, Time timestamp) { + .WillOnce(Invoke([&intercepted_buzz](Buzz* buzz, Time timestamp) { // Save buzz in intercepted_buzz for analysis later. intercepted_buzz.reset(buzz); return false; })); mock_buzzer_.ShareBuzz(std::make_unique<Buzz>(AccessLevel::kInternal), Now()); EXPECT_NE(nullptr, intercepted_buzz); ``` Using the tricks covered in this recipe, you are now able to mock methods that take and/or return move-only types. Put your newly-acquired power to good use - when you design a new API, you can now feel comfortable using `unique_ptrs` as appropriate, without fearing that doing so will compromise your tests. ## Making the Compilation Faster ## Believe it or not, the _vast majority_ of the time spent on compiling a mock class is in generating its constructor and destructor, as they perform non-trivial tasks (e.g. verification of the expectations). What's more, mock methods with different signatures have different types and thus their constructors/destructors need to be generated by the compiler separately. As a result, if you mock many different types of methods, compiling your mock class can get really slow. If you are experiencing slow compilation, you can move the definition of your mock class' constructor and destructor out of the class body and into a `.cpp` file. This way, even if you `#include` your mock class in N files, the compiler only needs to generate its constructor and destructor once, resulting in a much faster compilation. Let's illustrate the idea using an example. Here's the definition of a mock class before applying this recipe: ``` // File mock_foo.h. ... class MockFoo : public Foo { public: // Since we don't declare the constructor or the destructor, // the compiler will generate them in every translation unit // where this mock class is used. MOCK_METHOD0(DoThis, int()); MOCK_METHOD1(DoThat, bool(const char* str)); ... more mock methods ... }; ``` After the change, it would look like: ``` // File mock_foo.h. ... class MockFoo : public Foo { public: // The constructor and destructor are declared, but not defined, here. MockFoo(); virtual ~MockFoo(); MOCK_METHOD0(DoThis, int()); MOCK_METHOD1(DoThat, bool(const char* str)); ... more mock methods ... }; ``` and ``` // File mock_foo.cpp. #include "path/to/mock_foo.h" // The definitions may appear trivial, but the functions actually do a // lot of things through the constructors/destructors of the member // variables used to implement the mock methods. MockFoo::MockFoo() {} MockFoo::~MockFoo() {} ``` ## Forcing a Verification ## -When it's being destoyed, your friendly mock object will automatically +When it's being destroyed, your friendly mock object will automatically verify that all expectations on it have been satisfied, and will generate [Google Test](../../googletest/) failures if not. This is convenient as it leaves you with one less thing to worry about. That is, unless you are not sure if your mock object will -be destoyed. +be destroyed. How could it be that your mock object won't eventually be destroyed? Well, it might be created on the heap and owned by the code you are testing. Suppose there's a bug in that code and it doesn't delete the mock object properly - you could end up with a passing test when there's actually a bug. Using a heap checker is a good idea and can alleviate the concern, but its implementation may not be 100% reliable. So, sometimes you do want to _force_ Google Mock to verify a mock object before it is (hopefully) destructed. You can do this with `Mock::VerifyAndClearExpectations(&mock_object)`: ``` TEST(MyServerTest, ProcessesRequest) { using ::testing::Mock; MockFoo* const foo = new MockFoo; EXPECT_CALL(*foo, ...)...; // ... other expectations ... // server now owns foo. MyServer server(foo); server.ProcessRequest(...); // In case that server's destructor will forget to delete foo, // this will verify the expectations anyway. Mock::VerifyAndClearExpectations(foo); } // server is destroyed when it goes out of scope here. ``` **Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to indicate whether the verification was successful (`true` for yes), so you can wrap that function call inside a `ASSERT_TRUE()` if there is no point going further when the verification has failed. ## Using Check Points ## Sometimes you may want to "reset" a mock object at various check points in your test: at each check point, you verify that all existing expectations on the mock object have been satisfied, and then you set some new expectations on it as if it's newly created. This allows you to work with a mock object in "phases" whose sizes are each manageable. One such scenario is that in your test's `SetUp()` function, you may want to put the object you are testing into a certain state, with the help from a mock object. Once in the desired state, you want to clear all expectations on the mock, such that in the `TEST_F` body you can set fresh expectations on it. As you may have figured out, the `Mock::VerifyAndClearExpectations()` function we saw in the previous recipe can help you here. Or, if you are using `ON_CALL()` to set default actions on the mock object and want to clear the default actions as well, use `Mock::VerifyAndClear(&mock_object)` instead. This function does what `Mock::VerifyAndClearExpectations(&mock_object)` does and returns the same `bool`, **plus** it clears the `ON_CALL()` statements on `mock_object` too. Another trick you can use to achieve the same effect is to put the expectations in sequences and insert calls to a dummy "check-point" function at specific places. Then you can verify that the mock function calls do happen at the right time. For example, if you are exercising code: ``` Foo(1); Foo(2); Foo(3); ``` and want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: ``` using ::testing::MockFunction; TEST(FooTest, InvokesBarCorrectly) { MyMock mock; // Class MockFunction<F> has exactly one mock method. It is named // Call() and has type F. MockFunction<void(string check_point_name)> check; { InSequence s; EXPECT_CALL(mock, Bar("a")); EXPECT_CALL(check, Call("1")); EXPECT_CALL(check, Call("2")); EXPECT_CALL(mock, Bar("a")); } Foo(1); check.Call("1"); Foo(2); check.Call("2"); Foo(3); } ``` The expectation spec says that the first `Bar("a")` must happen before check point "1", the second `Bar("a")` must happen after check point "2", and nothing should happen between the two check points. The explicit check points make it easy to tell which `Bar("a")` is called by which call to `Foo()`. ## Mocking Destructors ## Sometimes you want to make sure a mock object is destructed at the right time, e.g. after `bar->A()` is called but before `bar->B()` is called. We already know that you can specify constraints on the order of mock function calls, so all we need to do is to mock the destructor of the mock function. This sounds simple, except for one problem: a destructor is a special function with special syntax and special semantics, and the `MOCK_METHOD0` macro doesn't work for it: ``` MOCK_METHOD0(~MockFoo, void()); // Won't compile! ``` The good news is that you can use a simple pattern to achieve the same effect. First, add a mock function `Die()` to your mock class and call it in the destructor, like this: ``` class MockFoo : public Foo { ... // Add the following two lines to the mock class. MOCK_METHOD0(Die, void()); virtual ~MockFoo() { Die(); } }; ``` (If the name `Die()` clashes with an existing symbol, choose another name.) Now, we have translated the problem of testing when a `MockFoo` object dies to testing when its `Die()` method is called: ``` MockFoo* foo = new MockFoo; MockBar* bar = new MockBar; ... { InSequence s; // Expects *foo to die after bar->A() and before bar->B(). EXPECT_CALL(*bar, A()); EXPECT_CALL(*foo, Die()); EXPECT_CALL(*bar, B()); } ``` And that's that. ## Using Google Mock and Threads ## **IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on platforms where Google Mock is thread-safe. Currently these are only platforms that support the pthreads library (this includes Linux and Mac). To make it thread-safe on other platforms we only need to implement some synchronization operations in `"gtest/internal/gtest-port.h"`. In a **unit** test, it's best if you could isolate and test a piece of code in a single-threaded context. That avoids race conditions and dead locks, and makes debugging your test much easier. Yet many programs are multi-threaded, and sometimes to test something we need to pound on it from more than one thread. Google Mock works for this purpose too. Remember the steps for using a mock: 1. Create a mock object `foo`. 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. 1. The code under test calls methods of `foo`. 1. Optionally, verify and reset the mock. 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. If you follow the following simple rules, your mocks and threads can live happily together: * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. * Obviously, you can do step #1 without locking. * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. If you violate the rules (for example, if you set expectations on a mock while another thread is calling its methods), you get undefined behavior. That's not fun, so don't do it. Google Mock guarantees that the action for a mock function is done in the same thread that called the mock function. For example, in ``` EXPECT_CALL(mock, Foo(1)) .WillOnce(action1); EXPECT_CALL(mock, Foo(2)) .WillOnce(action2); ``` if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, Google Mock will execute `action1` in thread 1 and `action2` in thread 2. Google Mock does _not_ impose a sequence on actions performed in different threads (doing so may create deadlocks as the actions may need to cooperate). This means that the execution of `action1` and `action2` in the above example _may_ interleave. If this is a problem, you should add proper synchronization logic to `action1` and `action2` to make the test thread-safe. Also, remember that `DefaultValue<T>` is a global resource that potentially affects _all_ living mock objects in your program. Naturally, you won't want to mess with it from multiple threads or when there still are mocks in action. ## Controlling How Much Information Google Mock Prints ## When Google Mock sees something that has the potential of being an error (e.g. a mock function with no expectation is called, a.k.a. an uninteresting call, which is allowed but perhaps you forgot to explicitly ban the call), it prints some warning messages, including the arguments of the function and the return value. Hopefully this will remind you to take a look and see if there is indeed a problem. Sometimes you are confident that your tests are correct and may not appreciate such friendly messages. Some other times, you are debugging your tests or learning about the behavior of the code you are testing, and wish you could observe every mock call that happens (including argument values and the return value). Clearly, one size doesn't fit all. You can control how much Google Mock tells you using the `--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string with three possible values: * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. * `error`: Google Mock will print errors only (least verbose). Alternatively, you can adjust the value of that flag from within your tests like so: ``` ::testing::FLAGS_gmock_verbose = "error"; ``` Now, judiciously use the right flag to enable Google Mock serve you better! ## Gaining Super Vision into Mock Calls ## You have a test using Google Mock. It fails: Google Mock tells you that some expectations aren't satisfied. However, you aren't sure why: Is there a typo somewhere in the matchers? Did you mess up the order of the `EXPECT_CALL`s? Or is the code under test doing something wrong? How can you find out the cause? Won't it be nice if you have X-ray vision and can actually see the trace of all `EXPECT_CALL`s and mock method calls as they are made? For each call, would you like to see its actual argument values and which `EXPECT_CALL` Google Mock thinks it matches? You can unlock this power by running your test with the `--gmock_verbose=info` flag. For example, given the test program: ``` using testing::_; using testing::HasSubstr; using testing::Return; class MockFoo { public: MOCK_METHOD2(F, void(const string& x, const string& y)); }; TEST(Foo, Bar) { MockFoo mock; EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); EXPECT_CALL(mock, F("a", "b")); EXPECT_CALL(mock, F("c", HasSubstr("d"))); mock.F("a", "good"); mock.F("a", "b"); } ``` if you run it with `--gmock_verbose=info`, you will see this output: ``` [ RUN ] Foo.Bar foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good") foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b") foo_test.cc:16: Failure Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... Expected: to be called once Actual: never called - unsatisfied and active [ FAILED ] Foo.Bar ``` Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo and should actually be `"a"`. With the above message, you should see that the actual `F("a", "good")` call is matched by the first `EXPECT_CALL`, not the third as you thought. From that it should be obvious that the third `EXPECT_CALL` is written wrong. Case solved. ## Running Tests in Emacs ## If you build and run your tests in Emacs, the source file locations of Google Mock and [Google Test](../../googletest/) errors will be highlighted. Just press `<Enter>` on one of them and you'll be taken to the offending line. Or, you can just type `C-x `` to jump to the next error. To make it even easier, you can add the following lines to your `~/.emacs` file: ``` (global-set-key "\M-m" 'compile) ; m is for make (global-set-key [M-down] 'next-error) (global-set-key [M-up] '(lambda () (interactive) (next-error -1))) ``` Then you can type `M-m` to start a build, or `M-up`/`M-down` to move back and forth between errors. ## Fusing Google Mock Source Files ## Google Mock's implementation consists of dozens of files (excluding its own tests). Sometimes you may want them to be packaged up in fewer files 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_gmock_files.py` in the `scripts/` directory (starting with release 1.2.0). Assuming you have Python 2.4 or above installed on your machine, just go to that directory and run ``` python fuse_gmock_files.py OUTPUT_DIR ``` and you should see an `OUTPUT_DIR` directory being created with files `gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. These three files contain everything you need to use Google Mock (and Google Test). Just copy them to anywhere you want and you are ready to write tests and use mocks. You can use the [scrpts/test/Makefile](../scripts/test/Makefile) file as an example on how to compile your tests against them. # Extending Google Mock # ## Writing New Matchers Quickly ## The `MATCHER*` family of macros can be used to define custom matchers easily. The syntax: ``` MATCHER(name, description_string_expression) { statements; } ``` will define a matcher with the given name that executes the statements, which must return a `bool` to indicate if the match succeeds. Inside the statements, you can refer to the value being matched by `arg`, and refer to its type by `arg_type`. The description string is a `string`-typed expression that documents what the matcher does, and is used to generate the failure message when the match fails. It can (and should) reference the special `bool` variable `negation`, and should evaluate to the description of the matcher when `negation` is `false`, or that of the matcher's negation when `negation` is `true`. For convenience, we allow the description string to be empty (`""`), in which case Google Mock will use the sequence of words in the matcher name as the description. For example: ``` MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } ``` allows you to write ``` // Expects mock_foo.Bar(n) to be called where n is divisible by 7. EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); ``` or, ``` using ::testing::Not; ... EXPECT_THAT(some_expression, IsDivisibleBy7()); EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); ``` If the above assertions fail, they will print something like: ``` Value of: some_expression Expected: is divisible by 7 Actual: 27 ... Value of: some_other_expression Expected: not (is divisible by 7) Actual: 21 ``` where the descriptions `"is divisible by 7"` and `"not (is divisible by 7)"` are automatically calculated from the matcher name `IsDivisibleBy7`. As you may have noticed, the auto-generated descriptions (especially those for the negation) may not be so great. You can always override them with a string expression of your own: ``` MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + " divisible by 7") { return (arg % 7) == 0; } ``` Optionally, you can stream additional information to a hidden argument named `result_listener` to explain the match result. For example, a better definition of `IsDivisibleBy7` is: ``` MATCHER(IsDivisibleBy7, "") { if ((arg % 7) == 0) return true; *result_listener << "the remainder is " << (arg % 7); return false; } ``` With this definition, the above assertion will give a better message: ``` Value of: some_expression Expected: is divisible by 7 Actual: 27 (the remainder is 6) ``` You should let `MatchAndExplain()` print _any additional information_ that can help a user understand the match result. Note that it should explain why the match succeeds in case of a success (unless it's obvious) - this is useful when the matcher is used inside `Not()`. There is no need to print the argument value itself, as Google Mock already prints it for you. **Notes:** 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. ## Writing New Parameterized Matchers Quickly ## Sometimes you'll want to define a matcher that has parameters. For that you can use the macro: ``` MATCHER_P(name, param_name, description_string) { statements; } ``` where the description string can be either `""` or a string expression that references `negation` and `param_name`. For example: ``` MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } ``` will allow you to write: ``` EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); ``` which may lead to this message (assuming `n` is 10): ``` Value of: Blah("a") Expected: has absolute value 10 Actual: -9 ``` Note that both the matcher description and its parameter are printed, making the message human-friendly. In the matcher definition body, you can write `foo_type` to reference the type of a parameter named `foo`. For example, in the body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write `value_type` to refer to the type of `value`. Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to support multi-parameter matchers: ``` MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } ``` Please note that the custom description string is for a particular **instance** of the matcher, where the parameters have been bound to actual values. Therefore usually you'll want the parameter values to be part of the description. Google Mock lets you do that by referencing the matcher parameters in the description string expression. For example, ``` using ::testing::PrintToString; MATCHER_P2(InClosedRange, low, hi, std::string(negation ? "isn't" : "is") + " in range [" + PrintToString(low) + ", " + PrintToString(hi) + "]") { return low <= arg && arg <= hi; } ... EXPECT_THAT(3, InClosedRange(4, 6)); ``` would generate a failure that contains the message: ``` Expected: is in range [4, 6] ``` If you specify `""` as the description, the failure message will contain the sequence of words in the matcher name followed by the parameter values printed as a tuple. For example, ``` MATCHER_P2(InClosedRange, low, hi, "") { ... } ... EXPECT_THAT(3, InClosedRange(4, 6)); ``` would generate a failure that contains the text: ``` Expected: in closed range (4, 6) ``` For the purpose of typing, you can view ``` MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } ``` as shorthand for ``` template <typename p1_type, ..., typename pk_type> FooMatcherPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... } ``` When you write `Foo(v1, ..., vk)`, the compiler infers the types of the parameters `v1`, ..., and `vk` for you. If you are not happy with the result of the type inference, you can specify the types by explicitly instantiating the template, as in `Foo<long, bool>(5, false)`. As said earlier, you don't get to (or need to) specify `arg_type` as that's determined by the context in which the matcher is used. You can assign the result of expression `Foo(p1, ..., pk)` to a variable of type `FooMatcherPk<p1_type, ..., pk_type>`. This can be useful when composing matchers. Matchers that don't have a parameter or have only one parameter have special types: you can assign `Foo()` to a `FooMatcher`-typed variable, and assign `Foo(p)` to a `FooMatcherP<p_type>`-typed variable. While you can instantiate a matcher template with reference types, passing the parameters by pointer usually makes your code more readable. If, however, you still want to pass a parameter by reference, be aware that in the failure message generated by the matcher you will see the value of the referenced object but not its address. You can overload matchers with different numbers of parameters: ``` MATCHER_P(Blah, a, description_string_1) { ... } MATCHER_P2(Blah, a, b, description_string_2) { ... } ``` While it's tempting to always use the `MATCHER*` macros when defining a new matcher, you should also consider implementing `MatcherInterface` or using `MakePolymorphicMatcher()` instead (see the recipes that follow), especially if you need to use the matcher a lot. While these approaches require more work, they give you more control on the types of the value being matched and the matcher parameters, which in general leads to better compiler error messages that pay off in the long run. They also allow overloading matchers based on parameter types (as opposed to just based on the number of parameters). ## Writing New Monomorphic Matchers ## A matcher of argument type `T` implements `::testing::MatcherInterface<T>` and does two things: it tests whether a value of type `T` matches the matcher, and can describe what kind of values it matches. The latter ability is used for generating readable error messages when expectations are violated. The interface looks like this: ``` class MatchResultListener { public: ... // Streams x to the underlying ostream; does nothing if the ostream // is NULL. template <typename T> MatchResultListener& operator<<(const T& x); // Returns the underlying ostream. ::std::ostream* stream(); }; template <typename T> class MatcherInterface { public: virtual ~MatcherInterface(); // Returns true iff the matcher matches x; also explains the match // result to 'listener'. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; // Describes this matcher to an ostream. virtual void DescribeTo(::std::ostream* os) const = 0; // Describes the negation of this matcher to an ostream. virtual void DescribeNegationTo(::std::ostream* os) const; }; ``` If you need a custom matcher but `Truly()` is not a good option (for example, you may not be happy with the way `Truly(predicate)` describes itself, or you may want your matcher to be polymorphic as `Eq(value)` is), you can define a matcher to do whatever you want in two steps: first implement the matcher interface, and then define a factory function to create a matcher instance. The second step is not strictly needed but it makes the syntax of using the matcher nicer. For example, you can define a matcher to test whether an `int` is divisible by 7 and then use it like this: ``` using ::testing::MakeMatcher; using ::testing::Matcher; using ::testing::MatcherInterface; using ::testing::MatchResultListener; class DivisibleBy7Matcher : public MatcherInterface<int> { public: virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { return (n % 7) == 0; } virtual void DescribeTo(::std::ostream* os) const { *os << "is divisible by 7"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "is not divisible by 7"; } }; inline Matcher<int> DivisibleBy7() { return MakeMatcher(new DivisibleBy7Matcher); } ... EXPECT_CALL(foo, Bar(DivisibleBy7())); ``` You may improve the matcher message by streaming additional information to the `listener` argument in `MatchAndExplain()`: ``` class DivisibleBy7Matcher : public MatcherInterface<int> { public: virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { const int remainder = n % 7; if (remainder != 0) { *listener << "the remainder is " << remainder; } return remainder == 0; } ... }; ``` Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: ``` Value of: x Expected: is divisible by 7 Actual: 23 (the remainder is 2) ``` ## Writing New Polymorphic Matchers ## You've learned how to write your own matchers in the previous recipe. Just one problem: a matcher created using `MakeMatcher()` only works for one particular type of arguments. If you want a _polymorphic_ matcher that works with arguments of several types (for instance, `Eq(x)` can be used to match a `value` as long as `value` == `x` compiles -- `value` and `x` don't have to share the same type), you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit involved. Fortunately, most of the time you can define a polymorphic matcher easily with the help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as an example: ``` using ::testing::MakePolymorphicMatcher; using ::testing::MatchResultListener; using ::testing::NotNull; using ::testing::PolymorphicMatcher; class NotNullMatcher { public: // To implement a polymorphic matcher, first define a COPYABLE class // that has three members MatchAndExplain(), DescribeTo(), and // DescribeNegationTo(), like the following. // In this example, we want to use NotNull() with any pointer, so // MatchAndExplain() accepts a pointer of any type as its first argument. // In general, you can define MatchAndExplain() as an ordinary method or // a method template, or even overload it. template <typename T> bool MatchAndExplain(T* p, MatchResultListener* /* listener */) const { return p != NULL; } // Describes the property of a value matching this matcher. void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } // Describes the property of a value NOT matching this matcher. void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } }; // To construct a polymorphic matcher, pass an instance of the class // to MakePolymorphicMatcher(). Note the return type. inline PolymorphicMatcher<NotNullMatcher> NotNull() { return MakePolymorphicMatcher(NotNullMatcher()); } ... EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. ``` **Note:** Your polymorphic matcher class does **not** need to inherit from `MatcherInterface` or any other class, and its methods do **not** need to be virtual. Like in a monomorphic matcher, you may explain the match result by streaming additional information to the `listener` argument in `MatchAndExplain()`. ## Writing New Cardinalities ## A cardinality is used in `Times()` to tell Google Mock how many times you expect a call to occur. It doesn't have to be exact. For example, you can say `AtLeast(5)` or `Between(2, 4)`. If the built-in set of cardinalities doesn't suit you, you are free to define your own by implementing the following interface (in namespace `testing`): ``` class CardinalityInterface { public: virtual ~CardinalityInterface(); // Returns true iff call_count calls will satisfy this cardinality. virtual bool IsSatisfiedByCallCount(int call_count) const = 0; // Returns true iff call_count calls will saturate this cardinality. virtual bool IsSaturatedByCallCount(int call_count) const = 0; // Describes self to an ostream. virtual void DescribeTo(::std::ostream* os) const = 0; }; ``` For example, to specify that a call must occur even number of times, you can write ``` using ::testing::Cardinality; using ::testing::CardinalityInterface; using ::testing::MakeCardinality; class EvenNumberCardinality : public CardinalityInterface { public: virtual bool IsSatisfiedByCallCount(int call_count) const { return (call_count % 2) == 0; } virtual bool IsSaturatedByCallCount(int call_count) const { return false; } virtual void DescribeTo(::std::ostream* os) const { *os << "called even number of times"; } }; Cardinality EvenNumber() { return MakeCardinality(new EvenNumberCardinality); } ... EXPECT_CALL(foo, Bar(3)) .Times(EvenNumber()); ``` ## Writing New Actions Quickly ## If the built-in actions don't work for you, and you find it inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` family to quickly define a new action that can be used in your code as if it's a built-in action. By writing ``` ACTION(name) { statements; } ``` in a namespace scope (i.e. not inside a class or function), you will define an action with the given name that executes the statements. The value returned by `statements` will be used as the return value of the action. Inside the statements, you can refer to the K-th (0-based) argument of the mock function as `argK`. For example: ``` ACTION(IncrementArg1) { return ++(*arg1); } ``` allows you to write ``` ... WillOnce(IncrementArg1()); ``` Note that you don't need to specify the types of the mock function arguments. Rest assured that your code is type-safe though: you'll get a compiler error if `*arg1` doesn't support the `++` operator, or if the type of `++(*arg1)` isn't compatible with the mock function's return type. Another example: ``` ACTION(Foo) { (*arg2)(5); Blah(); *arg1 = 0; return arg0; } ``` defines an action `Foo()` that invokes argument #2 (a function pointer) with 5, calls function `Blah()`, sets the value pointed to by argument #1 to 0, and returns argument #0. For more convenience and flexibility, you can also use the following pre-defined symbols in the body of `ACTION`: | `argK_type` | The type of the K-th (0-based) argument of the mock function | |:------------|:-------------------------------------------------------------| | `args` | All arguments of the mock function as a tuple | | `args_type` | The type of all arguments of the mock function as a tuple | | `return_type` | The return type of the mock function | | `function_type` | The type of the mock function | For example, when using an `ACTION` as a stub action for mock function: ``` int DoSomething(bool flag, int* ptr); ``` we have: + | **Pre-defined Symbol** | **Is Bound To** | |:-----------------------|:----------------| | `arg0` | the value of `flag` | | `arg0_type` | the type `bool` | | `arg1` | the value of `ptr` | | `arg1_type` | the type `int*` | | `args` | the tuple `(flag, ptr)` | | `args_type` | the type `::testing::tuple<bool, int*>` | | `return_type` | the type `int` | | `function_type` | the type `int(bool, int*)` | ## Writing New Parameterized Actions Quickly ## Sometimes you'll want to parameterize an action you define. For that we have another macro ``` ACTION_P(name, param) { statements; } ``` For example, ``` ACTION_P(Add, n) { return arg0 + n; } ``` will allow you to write ``` // Returns argument #0 + 5. ... WillOnce(Add(5)); ``` For convenience, we use the term _arguments_ for the values used to invoke the mock function, and the term _parameters_ for the values used to instantiate an action. Note that you don't need to provide the type of the parameter either. Suppose the parameter is named `param`, you can also use the Google-Mock-defined symbol `param_type` to refer to the type of the parameter as inferred by the compiler. For example, in the body of `ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter actions. For example, ``` ACTION_P2(ReturnDistanceTo, x, y) { double dx = arg0 - x; double dy = arg1 - y; return sqrt(dx*dx + dy*dy); } ``` lets you write ``` ... WillOnce(ReturnDistanceTo(5.0, 26.5)); ``` You can view `ACTION` as a degenerated parameterized action where the number of parameters is 0. You can also easily define actions overloaded on the number of parameters: ``` ACTION_P(Plus, a) { ... } ACTION_P2(Plus, a, b) { ... } ``` ## Restricting the Type of an Argument or Parameter in an ACTION ## For maximum brevity and reusability, the `ACTION*` macros don't ask you to provide the types of the mock function arguments and the action parameters. Instead, we let the compiler infer the types for us. Sometimes, however, we may want to be more explicit about the types. There are several tricks to do that. For example: ``` ACTION(Foo) { // Makes sure arg0 can be converted to int. int n = arg0; ... use n instead of arg0 here ... } ACTION_P(Bar, param) { // Makes sure the type of arg1 is const char*. ::testing::StaticAssertTypeEq<const char*, arg1_type>(); // Makes sure param can be converted to bool. bool flag = param; } ``` where `StaticAssertTypeEq` is a compile-time assertion in Google Test that verifies two types are the same. ## Writing New Action Templates Quickly ## Sometimes you want to give an action explicit template parameters that cannot be inferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be viewed as an extension to `ACTION()` and `ACTION_P*()`. The syntax: ``` ACTION_TEMPLATE(ActionName, HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } ``` defines an action template that takes _m_ explicit template parameters and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is between 0 and 10. `name_i` is the name of the i-th template parameter, and `kind_i` specifies whether it's a `typename`, an integral constant, or a template. `p_i` is the name of the i-th value parameter. Example: ``` // DuplicateArg<k, T>(output) converts the k-th argument of the mock // function to type T and copies it to *output. ACTION_TEMPLATE(DuplicateArg, // Note the comma between int and k: HAS_2_TEMPLATE_PARAMS(int, k, typename, T), AND_1_VALUE_PARAMS(output)) { *output = T(::testing::get<k>(args)); } ``` To create an instance of an action template, write: ``` ActionName<t1, ..., t_m>(v1, ..., v_n) ``` where the `t`s are the template arguments and the `v`s are the value arguments. The value argument types are inferred by the compiler. For example: ``` using ::testing::_; ... int n; EXPECT_CALL(mock, Foo(_, _)) .WillOnce(DuplicateArg<1, unsigned char>(&n)); ``` If you want to explicitly specify the value argument types, you can provide additional template arguments: ``` ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) ``` where `u_i` is the desired type of `v_i`. `ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the number of value parameters, but not on the number of template parameters. Without the restriction, the meaning of the following is unclear: ``` OverloadedAction<int, bool>(x); ``` Are we using a single-template-parameter action where `bool` refers to the type of `x`, or a two-template-parameter action where the compiler is asked to infer the type of `x`? ## Using the ACTION Object's Type ## If you are writing a function that returns an `ACTION` object, you'll need to know its type. The type depends on the macro used to define the action and the parameter types. The rule is relatively simple: + | **Given Definition** | **Expression** | **Has Type** | |:---------------------|:---------------|:-------------| | `ACTION(Foo)` | `Foo()` | `FooAction` | | `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | | `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | | `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | | `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | +| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))`| `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | | ... | ... | ... | Note that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`, and etc) for actions with different numbers of value parameters, or the action definitions cannot be overloaded on the number of them. ## Writing New Monomorphic Actions ## While the `ACTION*` macros are very convenient, sometimes they are inappropriate. For example, despite the tricks shown in the previous recipes, they don't let you directly specify the types of the mock function arguments and the action parameters, which in general leads to unoptimized compiler error messages that can baffle unfamiliar users. They also don't allow overloading actions based on parameter types without jumping through some hoops. An alternative to the `ACTION*` macros is to implement `::testing::ActionInterface<F>`, where `F` is the type of the mock function in which the action will be used. For example: ``` template <typename F>class ActionInterface { public: virtual ~ActionInterface(); // Performs the action. Result is the return type of function type // F, and ArgumentTuple is the tuple of arguments of F. // // For example, if F is int(bool, const string&), then Result would // be int, and ArgumentTuple would be ::testing::tuple<bool, const string&>. virtual Result Perform(const ArgumentTuple& args) = 0; }; using ::testing::_; using ::testing::Action; using ::testing::ActionInterface; using ::testing::MakeAction; typedef int IncrementMethod(int*); class IncrementArgumentAction : public ActionInterface<IncrementMethod> { public: virtual int Perform(const ::testing::tuple<int*>& args) { int* p = ::testing::get<0>(args); // Grabs the first argument. return *p++; } }; Action<IncrementMethod> IncrementArgument() { return MakeAction(new IncrementArgumentAction); } ... EXPECT_CALL(foo, Baz(_)) .WillOnce(IncrementArgument()); int n = 5; foo.Baz(&n); // Should return 5 and change n to 6. ``` ## Writing New Polymorphic Actions ## The previous recipe showed you how to define your own action. This is all good, except that you need to know the type of the function in which the action will be used. Sometimes that can be a problem. For example, if you want to use the action in functions with _different_ types (e.g. like `Return()` and `SetArgPointee()`). If an action can be used in several types of mock functions, we say it's _polymorphic_. The `MakePolymorphicAction()` function template makes it easy to define such an action: ``` namespace testing { template <typename Impl> PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); } // namespace testing ``` As an example, let's define an action that returns the second argument in the mock function's argument list. The first step is to define an implementation class: ``` class ReturnSecondArgumentAction { public: template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& args) const { // To get the i-th (0-based) argument, use ::testing::get<i>(args). return ::testing::get<1>(args); } }; ``` This implementation class does _not_ need to inherit from any particular class. What matters is that it must have a `Perform()` method template. This method template takes the mock function's arguments as a tuple in a **single** argument, and returns the result of the action. It can be either `const` or not, but must be invokable with exactly one template argument, which is the result type. In other words, you must be able to call `Perform<R>(args)` where `R` is the mock function's return type and `args` is its arguments in a tuple. Next, we use `MakePolymorphicAction()` to turn an instance of the implementation class into the polymorphic action we need. It will be convenient to have a wrapper for this: ``` using ::testing::MakePolymorphicAction; using ::testing::PolymorphicAction; PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { return MakePolymorphicAction(ReturnSecondArgumentAction()); } ``` Now, you can use this polymorphic action the same way you use the built-in ones: ``` using ::testing::_; class MockFoo : public Foo { public: MOCK_METHOD2(DoThis, int(bool flag, int n)); MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); }; ... MockFoo foo; EXPECT_CALL(foo, DoThis(_, _)) .WillOnce(ReturnSecondArgument()); EXPECT_CALL(foo, DoThat(_, _, _)) .WillOnce(ReturnSecondArgument()); ... foo.DoThis(true, 5); // Will return 5. foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". ``` ## Teaching Google Mock How to Print Your Values ## When an uninteresting or unexpected call occurs, Google Mock prints the argument values and the stack trace to help you debug. Assertion macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in question when the assertion fails. Google Mock and Google Test do this using Google Test's 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. [Google Test's advanced guide](../../googletest/docs/AdvancedGuide.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/DevGuide.md b/googlemock/docs/DevGuide.md index f4bab75c..adb74fe1 100644 --- a/googlemock/docs/DevGuide.md +++ b/googlemock/docs/DevGuide.md @@ -1,132 +1,132 @@ If you are interested in understanding the internals of Google Mock, building from source, or contributing ideas or modifications to the project, then this document is for you. # Introduction # First, let's give you some background of the project. ## Licensing ## All Google Mock source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php). ## The Google Mock Community ## The Google Mock community exists primarily through the [discussion group](http://groups.google.com/group/googlemock), the [issue tracker](https://github.com/google/googletest/issues) and, to a lesser extent, the [source control repository](../). You are definitely encouraged to contribute to the discussion and you can also help us to keep the effectiveness of the group high by following and promoting the guidelines listed here. ### Please Be Friendly ### Showing courtesy and respect to others is a vital part of the Google culture, and we strongly encourage everyone participating in Google Mock development to join us in accepting nothing less. Of course, being courteous is not the same as failing to constructively disagree with each other, but it does mean that we should be respectful of each other when enumerating the 42 technical reasons that a particular proposal may not be the best choice. There's never a reason to be antagonistic or dismissive toward anyone who is sincerely trying to contribute to a discussion. Sure, C++ testing is serious business and all that, but it's also a lot of fun. Let's keep it that way. Let's strive to be one of the friendliest communities in all of open source. ### Where to Discuss Google Mock ### As always, discuss Google Mock in the official [Google C++ Mocking Framework discussion group](http://groups.google.com/group/googlemock). You don't have to actually submit code in order to sign up. Your participation itself is a valuable contribution. # Working with the Code # If you want to get your hands dirty with the code inside Google Mock, this is the section for you. ## Checking Out the Source from Subversion ## Checking out the Google Mock source is most useful if you plan to tweak it yourself. You check out the source for Google Mock using a [Subversion](http://subversion.tigris.org/) client as you would for any other project hosted on Google Code. Please see the instruction on the [source code access page](../) for how to do it. ## Compiling from Source ## Once you check out the code, you can find instructions on how to compile it in the [README](../README.md) file. ## Testing ## A mocking framework is of no good if itself is not thoroughly tested. Tests should be written for any new code, and changes should be verified to not break existing tests before they are submitted for review. To perform the tests, follow the instructions in [README](http://code.google.com/p/googlemock/source/browse/trunk/README) and verify that there are no failures. # Contributing Code # We are excited that Google Mock is now open source, and hope to get great patches from the community. Before you fire up your favorite IDE and begin hammering away at that new feature, though, please take the time to read this section and understand the process. While it seems rigorous, we want to keep a high standard of quality in the code base. ## Contributor License Agreements ## You must sign a Contributor License Agreement (CLA) before we can accept any code. The CLA protects you and us. * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). * If you work for a company that wants to allow you to contribute your work to Google Mock, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. ## Coding Style ## To keep the source consistent, readable, diffable and easy to merge, we use a fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project. All patches will be expected -to conform to the style outlined [here](https://github.com/google/styleguide/blob/gh-pages/cppguide.xml). +to conform to the style outlined [here](https://google.github.io/styleguide/cppguide.html). ## Submitting Patches ## Please do submit code. Here's what you need to do: 1. Normally you should make your change against the SVN trunk instead of a branch or a tag, as the latter two are for release control and should be treated mostly as read-only. 1. Decide which code you want to submit. A submission should be a set of changes that addresses one issue in the [Google Mock issue tracker](http://code.google.com/p/googlemock/issues/list). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one. 1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches. 1. Ensure that your code adheres to the [Google Mock source code style](#Coding_Style.md). 1. Ensure that there are unit tests for your code. 1. Sign a Contributor License Agreement. 1. Create a patch file using `svn diff`. 1. We use [Rietveld](http://codereview.appspot.com/) to do web-based code reviews. You can read about the tool [here](https://github.com/rietveld-codereview/rietveld/wiki). When you are ready, upload your patch via Rietveld and notify `googlemock@googlegroups.com` to review it. There are several ways to upload the patch. We recommend using the [upload\_gmock.py](../scripts/upload_gmock.py) script, which you can find in the `scripts/` folder in the SVN trunk. ## Google Mock Committers ## The current members of the Google Mock engineering team are the only committers at present. In the great tradition of eating one's own dogfood, we will be requiring each new Google Mock engineering team member to earn the right to become a committer by following the procedures in this document, writing consistently great code, and demonstrating repeatedly that he or she truly gets the zen of Google Mock. # Release Process # We follow the typical release process for Subversion-based projects: 1. A release branch named `release-X.Y` is created. 1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable. 1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch. 1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time). 1. Go back to step 1 to create another release branch and so on. --- This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project. Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/). diff --git a/googlemock/docs/Documentation.md b/googlemock/docs/Documentation.md index 444151ee..a0311871 100644 --- a/googlemock/docs/Documentation.md +++ b/googlemock/docs/Documentation.md @@ -1,12 +1,15 @@ -This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)** -- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** +This page lists all documentation markdown files for Google Mock **(the +current git version)** +-- **if you use a former version of Google Mock, please read the +documentation for that specific version instead (e.g. by checking out +the respective git branch/tag).** * [ForDummies](ForDummies.md) -- start here if you are new to Google Mock. * [CheatSheet](CheatSheet.md) -- a quick reference. * [CookBook](CookBook.md) -- recipes for doing various tasks using Google Mock. * [FrequentlyAskedQuestions](FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. To contribute code to Google Mock, read: * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [Pump Manual](../googletest/docs/PumpManual.md) -- how we generate some of Google Mock's source files. + * [Pump Manual](../../googletest/docs/PumpManual.md) -- how we generate some of Google Mock's source files. diff --git a/googlemock/docs/ForDummies.md b/googlemock/docs/ForDummies.md index 0da4cbe2..0bf528e9 100644 --- a/googlemock/docs/ForDummies.md +++ b/googlemock/docs/ForDummies.md @@ -1,439 +1,439 @@ (**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](FrequentlyAskedQuestions.md#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors).) # What Is Google C++ Mocking Framework? # When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). **Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. **Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. Using Google Mock involves three basic steps: 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. # Why Google Mock? # While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. + * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distances to avoid it. + * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad-hoc restrictions. * The knowledge you gained from using one mock doesn't transfer to the next. In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). * Your tests are brittle as some resources they use are unreliable (e.g. the network). * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. We encourage you to use Google Mock as: * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. # Getting Started # Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. # A Case for Mock Turtles # Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: ``` class Turtle { ... virtual ~Turtle() {} virtual void PenUp() = 0; virtual void PenDown() = 0; virtual void Forward(int distance) = 0; virtual void Turn(int degrees) = 0; virtual void GoTo(int x, int y) = 0; virtual int GetX() const = 0; virtual int GetY() const = 0; }; ``` (Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. # Writing the Mock Class # If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) ## How to Define It ## Using the `Turtle` interface as example, here are the simple steps you need to follow: 1. Derive a class `MockTurtle` from `Turtle`. 1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](CookBook.md#mocking-nonvirtual-methods), it's much more involved). Count how many arguments it has. 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). 1. Repeat until all virtual functions you want to mock are done. After the process, you should have something like: ``` #include "gmock/gmock.h" // Brings in Google Mock. class MockTurtle : public Turtle { public: ... MOCK_METHOD0(PenUp, void()); MOCK_METHOD0(PenDown, void()); MOCK_METHOD1(Forward, void(int distance)); MOCK_METHOD1(Turn, void(int degrees)); MOCK_METHOD2(GoTo, void(int x, int y)); MOCK_CONST_METHOD0(GetX, int()); MOCK_CONST_METHOD0(GetY, int()); }; ``` You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. **Tip:** If even this is too much work for you, you'll find the `gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, and it will print the definition of the mock class for you. Due to the complexity of the C++ language, this script may not always work, but it can be quite handy when it does. For more details, read the [user documentation](../scripts/generator/README). ## Where to Put It ## When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. # Using Mocks in Tests # Once you have a mock class, using it is easy. The typical work flow is: 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). 1. Create some mock objects. 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. Here's an example: ``` #include "path/to/mock-turtle.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using ::testing::AtLeast; // #1 TEST(PainterTest, CanDrawSomething) { MockTurtle turtle; // #2 EXPECT_CALL(turtle, PenDown()) // #3 .Times(AtLeast(1)); Painter painter(&turtle); // #4 EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); } // #5 int main(int argc, char** argv) { // The following line must be executed to initialize Google Mock // (and Google Test) before running the tests. ::testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } ``` As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: ``` path/to/my_test.cc:119: Failure Actual function call count doesn't match this expectation: Actually: never called; Expected: called at least once. ``` **Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. **Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. **Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. ## Using Google Mock with Any Testing Framework ## If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or [CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: ``` int main(int argc, char** argv) { // The following line causes Google Mock to throw an exception on failure, // which will be interpreted by your testing framework as a test failure. ::testing::GTEST_FLAG(throw_on_failure) = true; ::testing::InitGoogleMock(&argc, argv); ... whatever your testing framework requires ... } ``` This approach has a catch: it makes Google Mock throw an exception from a mock object's destructor sometimes. With some compilers, this sometimes causes the test program to crash. You'll still be able to notice that the test has failed, but it's not a graceful failure. A better solution is to use Google Test's [event listener API](../../googletest/docs/AdvancedGuide.md#extending-google-test-by-handling-test-events) to report a test failure to your testing framework properly. You'll need to implement the `OnTestPartResult()` method of the event listener interface, but it should be straightforward. If this turns out to be too much work, we suggest that you stick with Google Test, which works with Google Mock seamlessly (in fact, it is technically part of Google Mock.). If there is a reason that you cannot use Google Test, please let us know. # Setting Expectations # The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." ## General Syntax ## In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: ``` EXPECT_CALL(mock_object, method(matchers)) .Times(cardinality) .WillOnce(action) .WillRepeatedly(action); ``` The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. This syntax is designed to make an expectation read like English. For example, you can probably guess that ``` using ::testing::Return;... EXPECT_CALL(turtle, GetX()) .Times(5) .WillOnce(Return(100)) .WillOnce(Return(150)) .WillRepeatedly(Return(200)); ``` says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). **Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. ## Matchers: What Arguments Do We Expect? ## When a mock function takes arguments, we must specify what arguments we are expecting; for example: ``` // Expects the turtle to move forward by 100 units. EXPECT_CALL(turtle, Forward(100)); ``` Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": ``` using ::testing::_; ... // Expects the turtle to move forward. EXPECT_CALL(turtle, Forward(_)); ``` `_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: ``` using ::testing::Ge;... EXPECT_CALL(turtle, Forward(Ge(100))); ``` This checks that the turtle will be told to go forward by at least 100 units. ## Cardinalities: How Many Times Will It Be Called? ## The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](CheatSheet.md). The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. **Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? ## Actions: What Should It Do? ## Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). In addition, in C++ 11 and above, a mock function whose return type is default-constructible (i.e. has a default constructor) has a default action of returning a default-constructed value. If you don't say anything, this behavior will be used. Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, ``` using ::testing::Return;... EXPECT_CALL(turtle, GetX()) .WillOnce(Return(100)) .WillOnce(Return(200)) .WillOnce(Return(300)); ``` This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. ``` using ::testing::Return;... EXPECT_CALL(turtle, GetY()) .WillOnce(Return(100)) .WillOnce(Return(200)) .WillRepeatedly(Return(300)); ``` says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](CheatSheet.md#actions). **Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: ``` int n = 100; EXPECT_CALL(turtle, GetX()) .Times(4) .WillRepeatedly(Return(n++)); ``` Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](CookBook.md). Time for another quiz! What do you think the following means? ``` using ::testing::Return;... EXPECT_CALL(turtle, GetY()) .Times(4) .WillOnce(Return(100)); ``` Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. ## Using Multiple Expectations ## So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: ``` using ::testing::_;... EXPECT_CALL(turtle, Forward(_)); // #1 EXPECT_CALL(turtle, Forward(10)) // #2 .Times(2); ``` If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. **Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. ## Ordered vs Unordered Calls ## By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: ``` using ::testing::InSequence;... TEST(FooTest, DrawsLineSegment) { ... { InSequence dummy; EXPECT_CALL(turtle, PenDown()); EXPECT_CALL(turtle, Forward(100)); EXPECT_CALL(turtle, PenUp()); } Foo(); } ``` By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook#Expecting_Partially_Ordered_Calls.md).) +(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook.md#expecting-partially-ordered-calls).) ## All Expectations Are Sticky (Unless Said Otherwise) ## Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): ``` using ::testing::_;... EXPECT_CALL(turtle, GoTo(_, _)) // #1 .Times(AnyNumber()); EXPECT_CALL(turtle, GoTo(0, 0)) // #2 .Times(2); ``` Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). Simple? Let's see if you've really understood it: what does the following code say? ``` using ::testing::Return; ... for (int i = n; i > 0; i--) { EXPECT_CALL(turtle, GetX()) .WillOnce(Return(10*i)); } ``` If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: ``` using ::testing::Return; ... for (int i = n; i > 0; i--) { EXPECT_CALL(turtle, GetX()) .WillOnce(Return(10*i)) .RetiresOnSaturation(); } ``` And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: ``` using ::testing::InSequence; using ::testing::Return; ... { InSequence s; for (int i = 1; i <= n; i++) { EXPECT_CALL(turtle, GetX()) .WillOnce(Return(10*i)) .RetiresOnSaturation(); } } ``` By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). ## Uninteresting Calls ## A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. # What Now? # Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. diff --git a/googlemock/docs/v1_5/CheatSheet.md b/googlemock/docs/v1_5/CheatSheet.md deleted file mode 100644 index 3c7bed4c..00000000 --- a/googlemock/docs/v1_5/CheatSheet.md +++ /dev/null @@ -1,525 +0,0 @@ - - -# Defining a Mock Class # - -## Mocking a Normal Class ## - -Given -``` -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` -(note that `~Foo()` **must** be virtual) we can define its mock as -``` -#include <gmock/gmock.h> - -class MockFoo : public Foo { - MOCK_CONST_METHOD0(GetSize, int()); - MOCK_METHOD1(Describe, string(const char* name)); - MOCK_METHOD1(Describe, string(int type)); - MOCK_METHOD2(Process, bool(Bar elem, int count)); -}; -``` - -To create a "nice" mock object which ignores all uninteresting calls, -or a "strict" mock object, which treats them as failures: -``` -NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. -StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. -``` - -## Mocking a Class Template ## - -To mock -``` -template <typename Elem> -class StackInterface { - public: - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` -(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -``` -template <typename Elem> -class MockStack : public StackInterface<Elem> { - public: - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Specifying Calling Conventions for Mock Functions ## - -If your mock function doesn't use the default calling convention, you -can specify it by appending `_WITH_CALLTYPE` to any of the macros -described in the previous two sections and supplying the calling -convention as the first argument to the macro. For example, -``` - MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); - MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); -``` -where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. - -# Using Mocks in Tests # - -The typical flow is: - 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. - 1. Create the mock objects. - 1. Optionally, set the default actions of the mock objects. - 1. Set your expectations on the mock objects (How will they be called? What wil they do?). - 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. - 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. - -Here is an example: -``` -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -# Setting Default Actions # - -Google Mock has a **built-in default action** for any function that -returns `void`, `bool`, a numeric value, or a pointer. - -To customize the default action for functions with return type `T` globally: -``` -using ::testing::DefaultValue; - -DefaultValue<T>::Set(value); // Sets the default value to be returned. -// ... use the mocks ... -DefaultValue<T>::Clear(); // Resets the default value. -``` - -To customize the default action for a particular method, use `ON_CALL()`: -``` -ON_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .WillByDefault(action); -``` - -# Setting Expectations # - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be -called? What will it do?): -``` -EXPECT_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -If `Times()` is omitted, the cardinality is assumed to be: - - * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; - * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or - * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. - -# Matchers # - -A **matcher** matches a _single_ argument. You can use it inside -`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value -directly: - -| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -|:------------------------------|:----------------------------------------| -| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | - -Built-in matchers (where `argument` is the function argument) are -divided into several categories: - -## Wildcard ## -|`_`|`argument` can be any value of the correct type.| -|:--|:-----------------------------------------------| -|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | - -## Generic Comparison ## - -|`Eq(value)` or `value`|`argument == value`| -|:---------------------|:------------------| -|`Ge(value)` |`argument >= value`| -|`Gt(value)` |`argument > value` | -|`Le(value)` |`argument <= value`| -|`Lt(value)` |`argument < value` | -|`Ne(value)` |`argument != value`| -|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| -|`NotNull()` |`argument` is a non-null pointer (raw or smart).| -|`Ref(variable)` |`argument` is a reference to `variable`.| -|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| - -Except `Ref()`, these matchers make a _copy_ of `value` in case it's -modified or destructed later. If the compiler complains that `value` -doesn't have a public copy constructor, try wrap it in `ByRef()`, -e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure -`non_copyable_value` is not changed afterwards, or the meaning of your -matcher will be changed. - -## Floating-Point Matchers ## - -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| -|:-------------------|:----------------------------------------------------------------------------------------------| -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | - -The above matchers use ULP-based comparison (the same as used in -[Google Test](http://code.google.com/p/googletest/)). They -automatically pick a reasonable error bound based on the absolute -value of the expected value. `DoubleEq()` and `FloatEq()` conform to -the IEEE standard, which requires comparing two NaNs for equality to -return false. The `NanSensitive*` version instead treats two NaNs as -equal, which is often what a user wants. - -## String Matchers ## - -The `argument` can be either a C string or a C++ string object: - -|`ContainsRegex(string)`|`argument` matches the given regular expression.| -|:----------------------|:-----------------------------------------------| -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | -|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | -|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | - -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide -strings as well. - -## Container Matchers ## - -Most STL-style containers support `==`, so you can use -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. If you want to write the elements in-line, -match them more flexibly, or get more informative messages, you can use: - -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -|:--------------|:-------------------------------------------------------------------------------------------| -|`ElementsAre(e0, e1, ..., en)`|`argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed.| -|`ElementsAreArray(array)` or `ElementsAreArray(array, count)`|The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array.| -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | - -These matchers can also match: - - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). - -where the array may be multi-dimensional (i.e. its elements can be arrays). - -## Member Matchers ## - -|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| -|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | -|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| - -## Matching the Result of a Function or Functor ## - -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| -|:---------------|:---------------------------------------------------------------------| - -## Pointer Matchers ## - -|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|:-----------|:-----------------------------------------------------------------------------------------------| - -## Multiargument Matchers ## - -These are matchers on tuple types. They can be used in -`.With()`. The following can be used on functions with <i>two<br> -arguments</i> `x` and `y`: - -|`Eq()`|`x == y`| -|:-----|:-------| -|`Ge()`|`x >= y`| -|`Gt()`|`x > y` | -|`Le()`|`x <= y`| -|`Lt()`|`x < y` | -|`Ne()`|`x != y`| - -You can use the following selectors to pick a subset of the arguments -(or reorder them) to participate in the matching: - -|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|:-----------|:-------------------------------------------------------------------| -|`Args<N1, N2, ..., Nk>(m)`|The `k` selected (using 0-based indices) arguments match `m`, e.g. `Args<1, 2>(Contains(5))`.| - -## Composite Matchers ## - -You can make a matcher from one or more other matchers: - -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| -|:-----------------------|:---------------------------------------------------| -|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | - -## Adapters for Matchers ## - -|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| -|:------------------|:--------------------------------------| -|`SafeMatcherCast<T>(m)`| [safely casts](V1_5_CookBook#Casting_Matchers.md) matcher `m` to type `Matcher<T>`. | -|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| - -## Matchers as Predicates ## - -|`Matches(m)`|a unary functor that returns `true` if the argument matches `m`.| -|:-----------|:---------------------------------------------------------------| -|`ExplainMatchResult(m, value, result_listener)`|returns `true` if `value` matches `m`, explaining the result to `result_listener`.| -|`Value(x, m)`|returns `true` if the value of `x` matches `m`. | - -## Defining Matchers ## - -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -|:-------------------------------------------------|:------------------------------------------------------| -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, "is between %(a)s and %(b)s") { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - -**Notes:** - - 1. The `MATCHER*` macros cannot be used inside a function or class. - 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). - 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. - -## Matchers as Test Assertions ## - -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/GoogleTestPrimer#Assertions) if the value of `expression` doesn't match matcher `m`.| -|:---------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | - -# Actions # - -**Actions** specify what a mock function should do when invoked. - -## Returning a Value ## - -|`Return()`|Return from a `void` mock function.| -|:---------|:----------------------------------| -|`Return(value)`|Return `value`. | -|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| -|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer. | -|`ReturnRef(variable)`|Return a reference to `variable`. | - -## Side Effects ## - -|`Assign(&variable, value)`|Assign `value` to variable.| -|:-------------------------|:--------------------------| -| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -|`SetArgumentPointee<N>(value)`|Assign `value` to the variable pointed by the `N`-th (0-based) argument.| -|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| -|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| - -## Using a Function or a Functor as an Action ## - -|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|:----------|:-----------------------------------------------------------------------------------------------------------------| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | -|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| - -The return value of the invoked function is used as the return value -of the action. - -When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -``` - double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } - ... - EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -``` - InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. - -## Default Action ## - -|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| -|:------------|:--------------------------------------------------------------------| - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. - -## Composite Actions ## - -|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | - -## Defining Actions ## - -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -|:--------------------------------------|:---------------------------------------------------------------------------------------| -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - -The `ACTION*` macros cannot be used inside a function or class. - -# Cardinalities # - -These are used in `Times()` to specify how many times a mock function will be called: - -|`AnyNumber()`|The function can be called any number of times.| -|:------------|:----------------------------------------------| -|`AtLeast(n)` |The call is expected at least `n` times. | -|`AtMost(n)` |The call is expected at most `n` times. | -|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| -|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| - -# Expectation Order # - -By default, the expectations can be matched in _any_ order. If some -or all expectations must be matched in a given order, there are two -ways to specify it. They can be used either independently or -together. - -## The After Clause ## - -``` -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` -says that `Bar()` can be called only after both `InitX()` and -`InitY()` have been called. - -If you don't know how many pre-requisites an expectation has when you -write it, you can use an `ExpectationSet` to collect them: - -``` -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` -says that `Bar()` can be called only after all elements have been -initialized (but we don't care about which elements get initialized -before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't -affect the meaning of the `.After()`. - -## Sequences ## - -When you have a long chain of sequential expectations, it's easier to -specify the order using **sequences**, which don't require you to given -each expectation in the chain a different name. <i>All expected<br> -calls</i> in the same sequence must occur in the order they are -specified. - -``` -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A<const char*>())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` -says that `Reset()` must be called before _both_ `GetSize()` _and_ -`Describe()`, and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: -``` -using ::testing::InSequence; -{ - InSequence dummy; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` -says that all expected calls in the scope of `dummy` must occur in -strict order. The name `dummy` is irrelevant.) - -# Verifying and Resetting a Mock # - -Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -``` -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true iff successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true iff successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell Google Mock that a mock object can be leaked and doesn't -need to be verified: -``` -Mock::AllowLeak(&mock_obj); -``` - -# Mock Classes # - -Google Mock defines a convenient mock class template -``` -class MockFunction<R(A1, ..., An)> { - public: - MOCK_METHODn(Call, R(A1, ..., An)); -}; -``` -See this [recipe](V1_5_CookBook#Using_Check_Points.md) for one application of it. - -# Flags # - -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -|:-------------------------------|:----------------------------------------------| -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | \ No newline at end of file diff --git a/googlemock/docs/v1_5/CookBook.md b/googlemock/docs/v1_5/CookBook.md deleted file mode 100644 index 26e153c6..00000000 --- a/googlemock/docs/v1_5/CookBook.md +++ /dev/null @@ -1,3250 +0,0 @@ - - -You can find recipes for using Google Mock here. If you haven't yet, -please read the [ForDummies](V1_5_ForDummies.md) document first to make sure you understand -the basics. - -**Note:** Google Mock lives in the `testing` name space. For -readability, it is recommended to write `using ::testing::Foo;` once in -your file before using the name `Foo` defined by Google Mock. We omit -such `using` statements in this page for brevity, but you should do it -in your own code. - -# Creating Mock Classes # - -## Mocking Private or Protected Methods ## - -You must always put a mock method definition (`MOCK_METHOD*`) in a -`public:` section of the mock class, regardless of the method being -mocked being `public`, `protected`, or `private` in the base class. -This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: - -``` -class Foo { - public: - ... - virtual bool Transform(Gadget* g) = 0; - - protected: - virtual void Resume(); - - private: - virtual int GetTimeOut(); -}; - -class MockFoo : public Foo { - public: - ... - MOCK_METHOD1(Transform, bool(Gadget* g)); - - // The following must be in the public section, even though the - // methods are protected or private in the base class. - MOCK_METHOD0(Resume, void()); - MOCK_METHOD0(GetTimeOut, int()); -}; -``` - -## Mocking Overloaded Methods ## - -You can mock overloaded functions as usual. No special attention is required: - -``` -class Foo { - ... - - // Must be virtual as we'll inherit from Foo. - virtual ~Foo(); - - // Overloaded on the types and/or numbers of arguments. - virtual int Add(Element x); - virtual int Add(int times, Element x); - - // Overloaded on the const-ness of this object. - virtual Bar& GetBar(); - virtual const Bar& GetBar() const; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Add, int(Element x)); - MOCK_METHOD2(Add, int(int times, Element x); - - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -``` - -**Note:** if you don't mock all versions of the overloaded method, the -compiler will give you a warning about some methods in the base class -being hidden. To fix that, use `using` to bring them in scope: - -``` -class MockFoo : public Foo { - ... - using Foo::Add; - MOCK_METHOD1(Add, int(Element x)); - // We don't want to mock int Add(int times, Element x); - ... -}; -``` - -## Mocking Class Templates ## - -To mock a class template, append `_T` to the `MOCK_*` macros: - -``` -template <typename Elem> -class StackInterface { - ... - // Must be virtual as we'll inherit from StackInterface. - virtual ~StackInterface(); - - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; - -template <typename Elem> -class MockStack : public StackInterface<Elem> { - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Mocking Nonvirtual Methods ## - -Google Mock can mock non-virtual functions to be used in what we call _hi-perf -dependency injection_. - -In this case, instead of sharing a common base class with the real -class, your mock class will be _unrelated_ to the real class, but -contain methods with the same signatures. The syntax for mocking -non-virtual methods is the _same_ as mocking virtual methods: - -``` -// A simple packet stream class. None of its members is virtual. -class ConcretePacketStream { - public: - void AppendPacket(Packet* new_packet); - const Packet* GetPacket(size_t packet_number) const; - size_t NumberOfPackets() const; - ... -}; - -// A mock packet stream class. It inherits from no other, but defines -// GetPacket() and NumberOfPackets(). -class MockPacketStream { - public: - MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); - MOCK_CONST_METHOD0(NumberOfPackets, size_t()); - ... -}; -``` - -Note that the mock class doesn't define `AppendPacket()`, unlike the -real class. That's fine as long as the test doesn't need to call it. - -Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` -in tests. Since the functions are not virtual and the two classes are -unrelated, you must specify your choice at _compile time_ (as opposed -to run time). - -One way to do it is to templatize your code that needs to use a packet -stream. More specifically, you will give your code a template type -argument for the type of the packet stream. In production, you will -instantiate your template with `ConcretePacketStream` as the type -argument. In tests, you will instantiate the same template with -`MockPacketStream`. For example, you may write: - -``` -template <class PacketStream> -void CreateConnection(PacketStream* stream) { ... } - -template <class PacketStream> -class PacketReader { - public: - void ReadPackets(PacketStream* stream, size_t packet_num); -}; -``` - -Then you can use `CreateConnection<ConcretePacketStream>()` and -`PacketReader<ConcretePacketStream>` in production code, and use -`CreateConnection<MockPacketStream>()` and -`PacketReader<MockPacketStream>` in tests. - -``` - MockPacketStream mock_stream; - EXPECT_CALL(mock_stream, ...)...; - .. set more expectations on mock_stream ... - PacketReader<MockPacketStream> reader(&mock_stream); - ... exercise reader ... -``` - -## Mocking Free Functions ## - -It's possible to use Google Mock to mock a free function (i.e. a -C-style function or a static method). You just need to rewrite your -code to use an interface (abstract class). - -Instead of calling a free function (say, `OpenFile`) directly, -introduce an interface for it and have a concrete subclass that calls -the free function: - -``` -class FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) = 0; -}; - -class File : public FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) { - return OpenFile(path, mode); - } -}; -``` - -Your code should talk to `FileInterface` to open a file. Now it's -easy to mock out the function. - -This may seem much hassle, but in practice you often have multiple -related functions that you can put in the same interface, so the -per-function syntactic overhead will be much lower. - -If you are concerned about the performance overhead incurred by -virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md). - -## Nice Mocks and Strict Mocks ## - -If a mock method has no `EXPECT_CALL` spec but is called, Google Mock -will print a warning about the "uninteresting call". The rationale is: - - * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. - -However, sometimes you may want to suppress all "uninteresting call" -warnings, while sometimes you may want the opposite, i.e. to treat all -of them as errors. Google Mock lets you make the decision on a -per-mock-object basis. - -Suppose your test uses a mock class `MockFoo`: - -``` -TEST(...) { - MockFoo mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -If a method of `mock_foo` other than `DoThis()` is called, it will be -reported by Google Mock as a warning. However, if you rewrite your -test to use `NiceMock<MockFoo>` instead, the warning will be gone, -resulting in a cleaner test output: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used -wherever `MockFoo` is accepted. - -It also works if `MockFoo`'s constructor takes some arguments, as -`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -The usage of `StrictMock` is similar, except that it makes all -uninteresting calls failures: - -``` -using ::testing::StrictMock; - -TEST(...) { - StrictMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... - - // The test will fail if a method of mock_foo other than DoThis() - // is called. -} -``` - -There are some caveats though (I don't like them just as much as the -next guy, but sadly they are side effects of C++'s limitations): - - 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). - 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) - -Finally, you should be **very cautious** when using this feature, as the -decision you make applies to **all** future changes to the mock -class. If an important change is made in the interface you are mocking -(and thus in the mock class), it could break your tests (if you use -`StrictMock`) or let bugs pass through without a warning (if you use -`NiceMock`). Therefore, try to specify the mock's behavior using -explicit `EXPECT_CALL` first, and only turn to `NiceMock` or -`StrictMock` as the last resort. - -## Simplifying the Interface without Breaking Existing Code ## - -Sometimes a method has a long list of arguments that is mostly -uninteresting. For example, - -``` -class LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) = 0; -}; -``` - -This method's argument list is lengthy and hard to work with (let's -say that the `message` argument is not even 0-terminated). If we mock -it as is, using the mock will be awkward. If, however, we try to -simplify this interface, we'll need to fix all clients depending on -it, which is often infeasible. - -The trick is to re-dispatch the method in the mock class: - -``` -class ScopedMockLog : public LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - Log(severity, full_filename, std::string(message, message_len)); - } - - // Implements the mock method: - // - // void Log(LogSeverity severity, - // const string& file_path, - // const string& message); - MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, - const string& message)); -}; -``` - -By defining a new mock method with a trimmed argument list, we make -the mock class much more user-friendly. - -## Alternative to Mocking Concrete Classes ## - -Often you may find yourself using classes that don't implement -interfaces. In order to test your code that uses such a class (let's -call it `Concrete`), you may be tempted to make the methods of -`Concrete` virtual and then mock it. - -Try not to do that. - -Making a non-virtual function virtual is a big decision. It creates an -extension point where subclasses can tweak your class' behavior. This -weakens your control on the class because now it's harder to maintain -the class' invariants. You should make a function virtual only when -there is a valid reason for a subclass to override it. - -Mocking concrete classes directly is problematic as it creates a tight -coupling between the class and the tests - any small change in the -class may invalidate your tests and make test maintenance a pain. - -To avoid such problems, many programmers have been practicing "coding -to interfaces": instead of talking to the `Concrete` class, your code -would define an interface and talk to it. Then you implement that -interface as an adaptor on top of `Concrete`. In tests, you can easily -mock that interface to observe how your code is doing. - -This technique incurs some overhead: - - * You pay the cost of virtual function calls (usually not a problem). - * There is more abstraction for the programmers to learn. - -However, it can also bring significant benefits in addition to better -testability: - - * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. - * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. - -Some people worry that if everyone is practicing this technique, they -will end up writing lots of redundant code. This concern is totally -understandable. However, there are two reasons why it may not be the -case: - - * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. - * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. - -You need to weigh the pros and cons carefully for your particular -problem, but I'd like to assure you that the Java community has been -practicing this for a long time and it's a proven effective technique -applicable in a wide variety of situations. :-) - -## Delegating Calls to a Fake ## - -Some times you have a non-trivial fake implementation of an -interface. For example: - -``` -class Foo { - public: - virtual ~Foo() {} - virtual char DoThis(int n) = 0; - virtual void DoThat(const char* s, int* p) = 0; -}; - -class FakeFoo : public Foo { - public: - virtual char DoThis(int n) { - return (n > 0) ? '+' : - (n < 0) ? '-' : '0'; - } - - virtual void DoThat(const char* s, int* p) { - *p = strlen(s); - } -}; -``` - -Now you want to mock this interface such that you can set expectations -on it. However, you also want to use `FakeFoo` for the default -behavior, as duplicating it in the mock object is, well, a lot of -work. - -When you define the mock class using Google Mock, you can have it -delegate its default action to a fake class you already have, using -this pattern: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - // Normal mock method definitions using Google Mock. - MOCK_METHOD1(DoThis, char(int n)); - MOCK_METHOD2(DoThat, void(const char* s, int* p)); - - // Delegates the default actions of the methods to a FakeFoo object. - // This must be called *before* the custom ON_CALL() statements. - void DelegateToFake() { - ON_CALL(*this, DoThis(_)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); - ON_CALL(*this, DoThat(_, _)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); - } - private: - FakeFoo fake_; // Keeps an instance of the fake in the mock. -}; -``` - -With that, you can use `MockFoo` in your tests as usual. Just remember -that if you don't explicitly set an action in an `ON_CALL()` or -`EXPECT_CALL()`, the fake will be called upon to do it: - -``` -using ::testing::_; - -TEST(AbcTest, Xyz) { - MockFoo foo; - foo.DelegateToFake(); // Enables the fake for delegation. - - // Put your ON_CALL(foo, ...)s here, if any. - - // No action specified, meaning to use the default action. - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(foo, DoThat(_, _)); - - int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. - foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); -} -``` - -**Some tips:** - - * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. - * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. - * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. - * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. - -Regarding the tip on mixing a mock and a fake, here's an example on -why it may be a bad sign: Suppose you have a class `System` for -low-level system operations. In particular, it does file and I/O -operations. And suppose you want to test how your code uses `System` -to do I/O, and you just want the file operations to work normally. If -you mock out the entire `System` class, you'll have to provide a fake -implementation for the file operation part, which suggests that -`System` is taking on too many roles. - -Instead, you can define a `FileOps` interface and an `IOOps` interface -and split `System`'s functionalities into the two. Then you can mock -`IOOps` without mocking `FileOps`. - -## Delegating Calls to a Real Object ## - -When using testing doubles (mocks, fakes, stubs, and etc), sometimes -their behaviors will differ from those of the real objects. This -difference could be either intentional (as in simulating an error such -that you can test the error handling code) or unintentional. If your -mocks have different behaviors than the real objects by mistake, you -could end up with code that passes the tests but fails in production. - -You can use the _delegating-to-real_ technique to ensure that your -mock has the same behavior as the real object while retaining the -ability to validate calls. This technique is very similar to the -delegating-to-fake technique, the difference being that we use a real -object instead of a fake. Here's an example: - -``` -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MockFoo() { - // By default, all calls are delegated to the real object. - ON_CALL(*this, DoThis()) - .WillByDefault(Invoke(&real_, &Foo::DoThis)); - ON_CALL(*this, DoThat(_)) - .WillByDefault(Invoke(&real_, &Foo::DoThat)); - ... - } - MOCK_METHOD0(DoThis, ...); - MOCK_METHOD1(DoThat, ...); - ... - private: - Foo real_; -}; -... - - MockFoo mock; - - EXPECT_CALL(mock, DoThis()) - .Times(3); - EXPECT_CALL(mock, DoThat("Hi")) - .Times(AtLeast(1)); - ... use mock in test ... -``` - -With this, Google Mock will verify that your code made the right calls -(with the right arguments, in the right order, called the right number -of times, etc), and a real object will answer the calls (so the -behavior will be the same as in production). This gives you the best -of both worlds. - -## Delegating Calls to a Parent Class ## - -Ideally, you should code to interfaces, whose methods are all pure -virtual. In reality, sometimes you do need to mock a virtual method -that is not pure (i.e, it already has an implementation). For example: - -``` -class Foo { - public: - virtual ~Foo(); - - virtual void Pure(int n) = 0; - virtual int Concrete(const char* str) { ... } -}; - -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); -}; -``` - -Sometimes you may want to call `Foo::Concrete()` instead of -`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub -action, or perhaps your test doesn't need to mock `Concrete()` at all -(but it would be oh-so painful to have to define a new mock class -whenever you don't need to mock one of its methods). - -The trick is to leave a back door in your mock class for accessing the -real methods in the base class: - -``` -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: - -``` -using ::testing::_; -using ::testing::Invoke; -... - EXPECT_CALL(foo, Concrete(_)) - .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -or tell the mock object that you don't want to mock `Concrete()`: - -``` -using ::testing::Invoke; -... - ON_CALL(foo, Concrete(_)) - .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do -that, `MockFoo::Concrete()` will be called (and cause an infinite -recursion) since `Foo::Concrete()` is virtual. That's just how C++ -works.) - -# Using Matchers # - -## Matching Argument Values Exactly ## - -You can specify exactly which arguments a mock method is expecting: - -``` -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(5)) - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", bar)); -``` - -## Using Simple Matchers ## - -You can use matchers to match arguments that have a certain property: - -``` -using ::testing::Ge; -using ::testing::NotNull; -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", NotNull())); - // The second argument must not be NULL. -``` - -A frequently used matcher is `_`, which matches anything: - -``` -using ::testing::_; -using ::testing::NotNull; -... - EXPECT_CALL(foo, DoThat(_, NotNull())); -``` - -## Combining Matchers ## - -You can build complex matchers from existing ones using `AllOf()`, -`AnyOf()`, and `Not()`: - -``` -using ::testing::AllOf; -using ::testing::Gt; -using ::testing::HasSubstr; -using ::testing::Ne; -using ::testing::Not; -... - // The argument must be > 5 and != 10. - EXPECT_CALL(foo, DoThis(AllOf(Gt(5), - Ne(10)))); - - // The first argument must not contain sub-string "blah". - EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), - NULL)); -``` - -## Casting Matchers ## - -Google Mock matchers are statically typed, meaning that the compiler -can catch your mistake if you use a matcher of the wrong type (for -example, if you use `Eq(5)` to match a `string` argument). Good for -you! - -Sometimes, however, you know what you're doing and want the compiler -to give you some slack. One example is that you have a matcher for -`long` and the argument you want to match is `int`. While the two -types aren't exactly the same, there is nothing really wrong with -using a `Matcher<long>` to match an `int` - after all, we can first -convert the `int` argument to a `long` before giving it to the -matcher. - -To support this need, Google Mock gives you the -`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type -`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the -type `m` accepts): - - 1. Type `T` can be implicitly cast to type `U`; - 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and - 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). - -The code won't compile if any of these conditions isn't met. - -Here's one example: - -``` -using ::testing::SafeMatcherCast; - -// A base class and a child class. -class Base { ... }; -class Derived : public Base { ... }; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(DoThis, void(Derived* derived)); -}; -... - - MockFoo foo; - // m is a Matcher<Base*> we got from somewhere. - EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); -``` - -If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar -function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works -as long as you can `static_cast` type `T` to type `U`. - -`MatcherCast` essentially lets you bypass C++'s type system -(`static_cast` isn't always safe as it could throw away information, -for example), so be careful not to misuse/abuse it. - -## Selecting Between Overloaded Functions ## - -If you expect an overloaded function to be called, the compiler may -need some help on which overloaded version it is. - -To disambiguate functions overloaded on the const-ness of this object, -use the `Const()` argument wrapper. - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - ... - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -... - - MockFoo foo; - Bar bar1, bar2; - EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). - .WillOnce(ReturnRef(bar1)); - EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). - .WillOnce(ReturnRef(bar2)); -``` - -(`Const()` is defined by Google Mock and returns a `const` reference -to its argument.) - -To disambiguate overloaded functions with the same number of arguments -but different argument types, you may need to specify the exact type -of a matcher, either by wrapping your matcher in `Matcher<type>()`, or -using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, -etc): - -``` -using ::testing::An; -using ::testing::Lt; -using ::testing::Matcher; -using ::testing::TypedEq; - -class MockPrinter : public Printer { - public: - MOCK_METHOD1(Print, void(int n)); - MOCK_METHOD1(Print, void(char c)); -}; - -TEST(PrinterTest, Print) { - MockPrinter printer; - - EXPECT_CALL(printer, Print(An<int>())); // void Print(int); - EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); - EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); - - printer.Print(3); - printer.Print(6); - printer.Print('a'); -} -``` - -## Performing Different Actions Based on the Arguments ## - -When a mock method is called, the _last_ matching expectation that's -still active will be selected (think "newer overrides older"). So, you -can make a method do different things depending on its argument values -like this: - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Return; -... - // The default case. - EXPECT_CALL(foo, DoThis(_)) - .WillRepeatedly(Return('b')); - - // The more specific case. - EXPECT_CALL(foo, DoThis(Lt(5))) - .WillRepeatedly(Return('a')); -``` - -Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will -be returned; otherwise `'b'` will be returned. - -## Matching Multiple Arguments as a Whole ## - -Sometimes it's not enough to match the arguments individually. For -example, we may want to say that the first argument must be less than -the second argument. The `With()` clause allows us to match -all arguments of a mock function as a whole. For example, - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Ne; -... - EXPECT_CALL(foo, InRange(Ne(0), _)) - .With(Lt()); -``` - -says that the first argument of `InRange()` must not be 0, and must be -less than the second argument. - -The expression inside `With()` must be a matcher of type -`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the -types of the function arguments. - -You can also write `AllArgs(m)` instead of `m` inside `.With()`. The -two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable -than `.With(Lt())`. - -You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments -against `m`. For example, - -``` -using ::testing::_; -using ::testing::AllOf; -using ::testing::Args; -using ::testing::Lt; -... - EXPECT_CALL(foo, Blah(_, _, _)) - .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); -``` - -says that `Blah()` will be called with arguments `x`, `y`, and `z` where -`x < y < z`. - -As a convenience and example, Google Mock provides some matchers for -2-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_5_CheatSheet.md) for -the complete list. - -## Using Matchers as Predicates ## - -Have you noticed that a matcher is just a fancy predicate that also -knows how to describe itself? Many existing algorithms take predicates -as arguments (e.g. those defined in STL's `<algorithm>` header), and -it would be a shame if Google Mock matchers are not allowed to -participate. - -Luckily, you can use a matcher where a unary predicate functor is -expected by wrapping it inside the `Matches()` function. For example, - -``` -#include <algorithm> -#include <vector> - -std::vector<int> v; -... -// How many elements in v are >= 10? -const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); -``` - -Since you can build complex matchers from simpler ones easily using -Google Mock, this gives you a way to conveniently construct composite -predicates (doing the same using STL's `<functional>` header is just -painful). For example, here's a predicate that's satisfied by any -number that is >= 0, <= 100, and != 50: - -``` -Matches(AllOf(Ge(0), Le(100), Ne(50))) -``` - -## Using Matchers in Google Test Assertions ## - -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in -[Google Test](http://code.google.com/p/googletest/) assertions. It's -called `ASSERT_THAT` and `EXPECT_THAT`: - -``` - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a Google Test test you can write: - -``` -#include <gmock/gmock.h> - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; -... - - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and -`Baz()`, and verifies that: - - * `Foo()` returns a string that starts with `"Hello"`. - * `Bar()` returns a string that matches regular expression `"Line \\d+"`. - * `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that _they read like -English_. They generate informative messages too. For example, if the -first `EXPECT_THAT()` above fails, the message will be something like: - -``` -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the -[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds -`assertThat()` to JUnit. - -## Using Predicates as Matchers ## - -Google Mock provides a built-in set of matchers. In case you find them -lacking, you can use an arbitray unary predicate function or functor -as a matcher - as long as the predicate accepts a value of the type -you want. You do this by wrapping the predicate inside the `Truly()` -function, for example: - -``` -using ::testing::Truly; - -int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } -... - - // Bar() must be called with an even number. - EXPECT_CALL(foo, Bar(Truly(IsEven))); -``` - -Note that the predicate function / functor doesn't have to return -`bool`. It works as long as the return value can be used as the -condition in statement `if (condition) ...`. - -## Matching Arguments that Are Not Copyable ## - -When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves -away a copy of `bar`. When `Foo()` is called later, Google Mock -compares the argument to `Foo()` with the saved copy of `bar`. This -way, you don't need to worry about `bar` being modified or destroyed -after the `EXPECT_CALL()` is executed. The same is true when you use -matchers like `Eq(bar)`, `Le(bar)`, and so on. - -But what if `bar` cannot be copied (i.e. has no copy constructor)? You -could define your own matcher function and use it with `Truly()`, as -the previous couple of recipes have shown. Or, you may be able to get -away from it if you can guarantee that `bar` won't be changed after -the `EXPECT_CALL()` is executed. Just tell Google Mock that it should -save a reference to `bar`, instead of a copy of it. Here's how: - -``` -using ::testing::Eq; -using ::testing::ByRef; -using ::testing::Lt; -... - // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); - - // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); -``` - -Remember: if you do this, don't change `bar` after the -`EXPECT_CALL()`, or the result is undefined. - -## Validating a Member of an Object ## - -Often a mock function takes a reference to object as an argument. When -matching the argument, you may not want to compare the entire object -against a fixed object, as that may be over-specification. Instead, -you may need to validate a certain member variable or the result of a -certain getter method of the object. You can do this with `Field()` -and `Property()`. More specifically, - -``` -Field(&Foo::bar, m) -``` - -is a matcher that matches a `Foo` object whose `bar` member variable -satisfies matcher `m`. - -``` -Property(&Foo::baz, m) -``` - -is a matcher that matches a `Foo` object whose `baz()` method returns -a value that satisfies matcher `m`. - -For example: - -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | -|:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - -Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no -argument and be declared as `const`. - -BTW, `Field()` and `Property()` can also match plain pointers to -objects. For instance, - -``` -Field(&Foo::number, Ge(3)) -``` - -matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, -the match will always fail regardless of the inner matcher. - -What if you want to validate more than one members at the same time? -Remember that there is `AllOf()`. - -## Validating the Value Pointed to by a Pointer Argument ## - -C++ functions often take pointers as arguments. You can use matchers -like `NULL`, `NotNull()`, and other comparison matchers to match a -pointer, but what if you want to make sure the value _pointed to_ by -the pointer, instead of the pointer itself, has a certain property? -Well, you can use the `Pointee(m)` matcher. - -`Pointee(m)` matches a pointer iff `m` matches the value the pointer -points to. For example: - -``` -using ::testing::Ge; -using ::testing::Pointee; -... - EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); -``` - -expects `foo.Bar()` to be called with a pointer that points to a value -greater than or equal to 3. - -One nice thing about `Pointee()` is that it treats a `NULL` pointer as -a match failure, so you can write `Pointee(m)` instead of - -``` - AllOf(NotNull(), Pointee(m)) -``` - -without worrying that a `NULL` pointer will crash your test. - -Also, did we tell you that `Pointee()` works with both raw pointers -**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and -etc)? - -What if you have a pointer to pointer? You guessed it - you can use -nested `Pointee()` to probe deeper inside the value. For example, -`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer -that points to a number less than 3 (what a mouthful...). - -## Testing a Certain Property of an Object ## - -Sometimes you want to specify that an object argument has a certain -property, but there is no existing matcher that does this. If you want -good error messages, you should define a matcher. If you want to do it -quick and dirty, you could get away with writing an ordinary function. - -Let's say you have a mock function that takes an object of type `Foo`, -which has an `int bar()` method and an `int baz()` method, and you -want to constrain that the argument's `bar()` value plus its `baz()` -value is a given number. Here's how you can define a matcher to do it: - -``` -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> { - public: - explicit BarPlusBazEqMatcher(int expected_sum) - : expected_sum_(expected_sum) {} - - virtual bool MatchAndExplain(const Foo& foo, - MatchResultListener* listener) const { - return (foo.bar() + foo.baz()) == expected_sum_; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "bar() + baz() equals " << expected_sum_; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "bar() + baz() does not equal " << expected_sum_; - } - private: - const int expected_sum_; -}; - -inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); -} - -... - - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; -``` - -## Matching Containers ## - -Sometimes an STL container (e.g. list, vector, map, ...) is passed to -a mock function and you may want to validate it. Since most STL -containers support the `==` operator, you can write -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. - -Sometimes, though, you may want to be more flexible (for example, the -first element must be an exact match, but the second element can be -any positive number, and so on). Also, containers used in tests often -have a small number of elements, and having to define the expected -container out-of-line is a bit of a hassle. - -You can use the `ElementsAre()` matcher in such cases: - -``` -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::Gt; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); -``` - -The above matcher says that the container must have 4 elements, which -must be 1, greater than 0, anything, and 5 respectively. - -`ElementsAre()` is overloaded to take 0 to 10 arguments. If more are -needed, you can place them in a C-style array and use -`ElementsAreArray()` instead: - -``` -using ::testing::ElementsAreArray; -... - - // ElementsAreArray accepts an array of element values. - const int expected_vector1[] = { 1, 5, 2, 4, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); - - // Or, an array of element matchers. - Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); -``` - -In case the array needs to be dynamically created (and therefore the -array size cannot be inferred by the compiler), you can give -`ElementsAreArray()` an additional argument to specify the array size: - -``` -using ::testing::ElementsAreArray; -... - int* const expected_vector3 = new int[count]; - ... fill expected_vector3 with values ... - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); -``` - -**Tips:** - - * `ElementAre*()` works with _any_ container that implements the STL iterator concept (i.e. it has a `const_iterator` type and supports `begin()/end()`) and supports `size()`, not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. - * You can use nested `ElementAre*()` to match nested (multi-dimensional) containers. - * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. - * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). - -## Sharing Matchers ## - -Under the hood, a Google Mock matcher object consists of a pointer to -a ref-counted implementation object. Copying matchers is allowed and -very efficient, as only the pointer is copied. When the last matcher -that references the implementation object dies, the implementation -object will be deleted. - -Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a -matcher variable and use that variable repeatedly! For example, - -``` - Matcher<int> in_range = AllOf(Gt(5), Le(10)); - ... use in_range as a matcher in multiple EXPECT_CALLs ... -``` - -# Setting Expectations # - -## Ignoring Uninteresting Calls ## - -If you are not interested in how a mock method is called, just don't -say anything about it. In this case, if the method is ever called, -Google Mock will perform its default action to allow the test program -to continue. If you are not happy with the default action taken by -Google Mock, you can override it using `DefaultValue<T>::Set()` -(described later in this document) or `ON_CALL()`. - -Please note that once you expressed interest in a particular mock -method (via `EXPECT_CALL()`), all invocations to it must match some -expectation. If this function is called but the arguments don't match -any `EXPECT_CALL()` statement, it will be an error. - -## Disallowing Unexpected Calls ## - -If a mock method shouldn't be called at all, explicitly say so: - -``` -using ::testing::_; -... - EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -If some calls to the method are allowed, but the rest are not, just -list all the expected calls: - -``` -using ::testing::AnyNumber; -using ::testing::Gt; -... - EXPECT_CALL(foo, Bar(5)); - EXPECT_CALL(foo, Bar(Gt(10))) - .Times(AnyNumber()); -``` - -A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` -statements will be an error. - -## Expecting Ordered Calls ## - -Although an `EXPECT_CALL()` statement defined earlier takes precedence -when Google Mock tries to match a function call with an expectation, -by default calls don't have to happen in the order `EXPECT_CALL()` -statements are written. For example, if the arguments match the -matchers in the third `EXPECT_CALL()`, but not those in the first two, -then the third expectation will be used. - -If you would rather have all calls occur in the order of the -expectations, put the `EXPECT_CALL()` statements in a block where you -define a variable of type `InSequence`: - -``` - using ::testing::_; - using ::testing::InSequence; - - { - InSequence s; - - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(bar, DoThat(_)) - .Times(2); - EXPECT_CALL(foo, DoThis(6)); - } -``` - -In this example, we expect a call to `foo.DoThis(5)`, followed by two -calls to `bar.DoThat()` where the argument can be anything, which are -in turn followed by a call to `foo.DoThis(6)`. If a call occurred -out-of-order, Google Mock will report an error. - -## Expecting Partially Ordered Calls ## - -Sometimes requiring everything to occur in a predetermined order can -lead to brittle tests. For example, we may care about `A` occurring -before both `B` and `C`, but aren't interested in the relative order -of `B` and `C`. In this case, the test should reflect our real intent, -instead of being overly constraining. - -Google Mock allows you to impose an arbitrary DAG (directed acyclic -graph) on the calls. One way to express the DAG is to use the -[After](V1_5_CheatSheet#The_After_Clause.md) clause of `EXPECT_CALL`. - -Another way is via the `InSequence()` clause (not the same as the -`InSequence` class), which we borrowed from jMock 2. It's less -flexible than `After()`, but more convenient when you have long chains -of sequential calls, as it doesn't require you to come up with -different names for the expectations in the chains. Here's how it -works: - -If we view `EXPECT_CALL()` statements as nodes in a graph, and add an -edge from node A to node B wherever A must occur before B, we can get -a DAG. We use the term "sequence" to mean a directed path in this -DAG. Now, if we decompose the DAG into sequences, we just need to know -which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. - -So, to specify the partial order on the expectations we need to do two -things: first to define some `Sequence` objects, and then for each -`EXPECT_CALL()` say which `Sequence` objects it is part -of. Expectations in the same sequence must occur in the order they are -written. For example, - -``` - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(foo, A()) - .InSequence(s1, s2); - EXPECT_CALL(bar, B()) - .InSequence(s1); - EXPECT_CALL(bar, C()) - .InSequence(s2); - EXPECT_CALL(foo, D()) - .InSequence(s2); -``` - -specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> -C -> D`): - -``` - +---> B - | - A ---| - | - +---> C ---> D -``` - -This means that A must occur before B and C, and C must occur before -D. There's no restriction about the order other than these. - -## Controlling When an Expectation Retires ## - -When a mock method is called, Google Mock only consider expectations -that are still active. An expectation is active when created, and -becomes inactive (aka _retires_) when a call that has to occur later -has occurred. For example, in - -``` - using ::testing::_; - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 - .Times(AnyNumber()) - .InSequence(s1, s2); - EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 - .InSequence(s1); - EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 - .InSequence(s2); -``` - -as soon as either #2 or #3 is matched, #1 will retire. If a warning -`"File too large."` is logged after this, it will be an error. - -Note that an expectation doesn't retire automatically when it's -saturated. For example, - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 -``` - -says that there will be exactly one warning with the message `"File -too large."`. If the second warning contains this message too, #2 will -match again and result in an upper-bound-violated error. - -If this is not what you want, you can ask an expectation to retire as -soon as it becomes saturated: - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 - .RetiresOnSaturation(); -``` - -Here #2 can be used only once, so if you have two warnings with the -message `"File too large."`, the first will match #2 and the second -will match #1 - there will be no error. - -# Using Actions # - -## Returning References from Mock Methods ## - -If a mock function's return type is a reference, you need to use -`ReturnRef()` instead of `Return()` to return a result: - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetBar, Bar&()); -}; -... - - MockFoo foo; - Bar bar; - EXPECT_CALL(foo, GetBar()) - .WillOnce(ReturnRef(bar)); -``` - -## Combining Actions ## - -Want to do more than one thing when a function is called? That's -fine. `DoAll()` allow you to do sequence of actions every time. Only -the return value of the last action in the sequence will be used. - -``` -using ::testing::DoAll; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Bar, bool(int n)); -}; -... - - EXPECT_CALL(foo, Bar(_)) - .WillOnce(DoAll(action_1, - action_2, - ... - action_n)); -``` - -## Mocking Side Effects ## - -Sometimes a method exhibits its effect not via returning a value but -via side effects. For example, it may change some global state or -modify an output argument. To mock side effects, in general you can -define your own action by implementing `::testing::ActionInterface`. - -If all you need to do is to change an output argument, the built-in -`SetArgumentPointee()` action is convenient: - -``` -using ::testing::SetArgumentPointee; - -class MockMutator : public Mutator { - public: - MOCK_METHOD2(Mutate, void(bool mutate, int* value)); - ... -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, Mutate(true, _)) - .WillOnce(SetArgumentPointee<1>(5)); -``` - -In this example, when `mutator.Mutate()` is called, we will assign 5 -to the `int` variable pointed to by argument #1 -(0-based). - -`SetArgumentPointee()` conveniently makes an internal copy of the -value you pass to it, removing the need to keep the value in scope and -alive. The implication however is that the value must have a copy -constructor and assignment operator. - -If the mock method also needs to return a value as well, you can chain -`SetArgumentPointee()` with `Return()` using `DoAll()`: - -``` -using ::testing::_; -using ::testing::Return; -using ::testing::SetArgumentPointee; - -class MockMutator : public Mutator { - public: - ... - MOCK_METHOD1(MutateInt, bool(int* value)); -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, MutateInt(_)) - .WillOnce(DoAll(SetArgumentPointee<0>(5), - Return(true))); -``` - -If the output argument is an array, use the -`SetArrayArgument<N>(first, last)` action instead. It copies the -elements in source range `[first, last)` to the array pointed to by -the `N`-th (0-based) argument: - -``` -using ::testing::NotNull; -using ::testing::SetArrayArgument; - -class MockArrayMutator : public ArrayMutator { - public: - MOCK_METHOD2(Mutate, void(int* values, int num_values)); - ... -}; -... - - MockArrayMutator mutator; - int values[5] = { 1, 2, 3, 4, 5 }; - EXPECT_CALL(mutator, Mutate(NotNull(), 5)) - .WillOnce(SetArrayArgument<0>(values, values + 5)); -``` - -This also works when the argument is an output iterator: - -``` -using ::testing::_; -using ::testing::SeArrayArgument; - -class MockRolodex : public Rolodex { - public: - MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >)); - ... -}; -... - - MockRolodex rolodex; - vector<string> names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); - EXPECT_CALL(rolodex, GetNames(_)) - .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); -``` - -## Changing a Mock Object's Behavior Based on the State ## - -If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: - -``` -using ::testing::InSequence; -using ::testing::Return; - -... - { - InSequence seq; - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(true)); - EXPECT_CALL(my_mock, Flush()); - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(false)); - } - my_mock.FlushIfDirty(); -``` - -This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. - -If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: - -``` -using ::testing::_; -using ::testing::SaveArg; -using ::testing::Return; - -ACTION_P(ReturnPointee, p) { return *p; } -... - int previous_value = 0; - EXPECT_CALL(my_mock, GetPrevValue()) - .WillRepeatedly(ReturnPointee(&previous_value)); - EXPECT_CALL(my_mock, UpdateValue(_)) - .WillRepeatedly(SaveArg<0>(&previous_value)); - my_mock.DoSomethingToUpdateValue(); -``` - -Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. - -## Setting the Default Value for a Return Type ## - -If a mock method's return type is a built-in C++ type or pointer, by -default it will return 0 when invoked. You only need to specify an -action if this default value doesn't work for you. - -Sometimes, you may want to change this default value, or you may want -to specify a default value for types Google Mock doesn't know -about. You can do this using the `::testing::DefaultValue` class -template: - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD0(CalculateBar, Bar()); -}; -... - - Bar default_bar; - // Sets the default return value for type Bar. - DefaultValue<Bar>::Set(default_bar); - - MockFoo foo; - - // We don't need to specify an action here, as the default - // return value works for us. - EXPECT_CALL(foo, CalculateBar()); - - foo.CalculateBar(); // This should return default_bar. - - // Unsets the default return value. - DefaultValue<Bar>::Clear(); -``` - -Please note that changing the default value for a type can make you -tests hard to understand. We recommend you to use this feature -judiciously. For example, you may want to make sure the `Set()` and -`Clear()` calls are right next to the code that uses your mock. - -## Setting the Default Actions for a Mock Method ## - -You've learned how to change the default value of a given -type. However, this may be too coarse for your purpose: perhaps you -have two mock methods with the same return type and you want them to -have different behaviors. The `ON_CALL()` macro allows you to -customize your mock's behavior at the method level: - -``` -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Gt; -using ::testing::Return; -... - ON_CALL(foo, Sign(_)) - .WillByDefault(Return(-1)); - ON_CALL(foo, Sign(0)) - .WillByDefault(Return(0)); - ON_CALL(foo, Sign(Gt(0))) - .WillByDefault(Return(1)); - - EXPECT_CALL(foo, Sign(_)) - .Times(AnyNumber()); - - foo.Sign(5); // This should return 1. - foo.Sign(-9); // This should return -1. - foo.Sign(0); // This should return 0. -``` - -As you may have guessed, when there are more than one `ON_CALL()` -statements, the news order take precedence over the older ones. In -other words, the **last** one that matches the function arguments will -be used. This matching order allows you to set up the common behavior -in a mock object's constructor or the test fixture's set-up phase and -specialize the mock's behavior later. - -## Using Functions/Methods/Functors as Actions ## - -If the built-in actions don't suit you, you can easily use an existing -function, method, or functor as an action: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(Sum, int(int x, int y)); - MOCK_METHOD1(ComplexJob, bool(int x)); -}; - -int CalculateSum(int x, int y) { return x + y; } - -class Helper { - public: - bool ComplexJob(int x); -}; -... - - MockFoo foo; - Helper helper; - EXPECT_CALL(foo, Sum(_, _)) - .WillOnce(Invoke(CalculateSum)); - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); - - foo.Sum(5, 6); // Invokes CalculateSum(5, 6). - foo.ComplexJob(10); // Invokes helper.ComplexJob(10); -``` - -The only requirement is that the type of the function, etc must be -_compatible_ with the signature of the mock function, meaning that the -latter's arguments can be implicitly converted to the corresponding -arguments of the former, and the former's return type can be -implicitly converted to that of the latter. So, you can invoke -something whose type is _not_ exactly the same as the mock function, -as long as it's safe to do so - nice, huh? - -## Invoking a Function/Method/Functor Without Arguments ## - -`Invoke()` is very useful for doing actions that are more complex. It -passes the mock function's arguments to the function or functor being -invoked such that the callee has the full context of the call to work -with. If the invoked function is not interested in some or all of the -arguments, it can simply ignore them. - -Yet, a common pattern is that a test author wants to invoke a function -without the arguments of the mock function. `Invoke()` allows her to -do that using a wrapper function that throws away the arguments before -invoking an underlining nullary function. Needless to say, this can be -tedious and obscures the intent of the test. - -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except -that it doesn't pass the mock function's arguments to the -callee. Here's an example: - -``` -using ::testing::_; -using ::testing::InvokeWithoutArgs; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(ComplexJob, bool(int n)); -}; - -bool Job1() { ... } -... - - MockFoo foo; - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)); - - foo.ComplexJob(10); // Invokes Job1(). -``` - -## Invoking an Argument of the Mock Function ## - -Sometimes a mock function will receive a function pointer or a functor -(in other words, a "callable") as an argument, e.g. - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); -}; -``` - -and you may want to invoke this callable argument: - -``` -using ::testing::_; -... - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(...); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? - -Well, Google Mock has an action to solve _exactly_ this problem: - -``` - InvokeArgument<N>(arg_1, arg_2, ..., arg_m) -``` - -will invoke the `N`-th (0-based) argument the mock function receives, -with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is -a function pointer or a functor, Google Mock handles them both. - -With that, you could write: - -``` -using ::testing::_; -using ::testing::InvokeArgument; -... - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(InvokeArgument<1>(5)); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -What if the callable takes an argument by reference? No problem - just -wrap it inside `ByRef()`: - -``` -... - MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); -... -using ::testing::_; -using ::testing::ByRef; -using ::testing::InvokeArgument; -... - - MockFoo foo; - Helper helper; - ... - EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callable. -``` - -What if the callable takes an argument by reference and we do **not** -wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a -copy_ of the argument, and pass a _reference to the copy_, instead of -a reference to the original value, to the callable. This is especially -handy when the argument is a temporary value: - -``` -... - MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); -... -using ::testing::_; -using ::testing::InvokeArgument; -... - - MockFoo foo; - ... - EXPECT_CALL(foo, DoThat(_)) - .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); - // Will execute (*f)(5.0, string("Hi")), where f is the function pointer - // DoThat() receives. Note that the values 5.0 and string("Hi") are - // temporary and dead once the EXPECT_CALL() statement finishes. Yet - // it's fine to perform this action later, since a copy of the values - // are kept inside the InvokeArgument action. -``` - -## Ignoring an Action's Result ## - -Sometimes you have an action that returns _something_, but you need an -action that returns `void` (perhaps you want to use it in a mock -function that returns `void`, or perhaps it needs to be used in -`DoAll()` and it's not the last in the list). `IgnoreResult()` lets -you do that. For example: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -int Process(const MyData& data); -string DoSomething(); - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Abc, void(const MyData& data)); - MOCK_METHOD0(Xyz, bool()); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, Abc(_)) - // .WillOnce(Invoke(Process)); - // The above line won't compile as Process() returns int but Abc() needs - // to return void. - .WillOnce(IgnoreResult(Invoke(Process))); - - EXPECT_CALL(foo, Xyz()) - .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), - // Ignores the string DoSomething() returns. - Return(true))); -``` - -Note that you **cannot** use `IgnoreResult()` on an action that already -returns `void`. Doing so will lead to ugly compiler errors. - -## Selecting an Action's Arguments ## - -Say you have a mock function `Foo()` that takes seven arguments, and -you have a custom action that you want to invoke when `Foo()` is -called. Trouble is, the custom action only wants three arguments: - -``` -using ::testing::_; -using ::testing::Invoke; -... - MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight)); -... - -bool IsVisibleInQuadrant1(bool visible, int x, int y) { - return visible && x >= 0 && y >= 0; -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( -``` - -To please the compiler God, you can to define an "adaptor" that has -the same signature as `Foo()` and calls the custom action with the -right arguments: - -``` -using ::testing::_; -using ::testing::Invoke; - -bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight) { - return IsVisibleInQuadrant1(visible, x, y); -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. -``` - -But isn't this awkward? - -Google Mock provides a generic _action adaptor_, so you can spend your -time minding more important business than writing your own -adaptors. Here's the syntax: - -``` - WithArgs<N1, N2, ..., Nk>(action) -``` - -creates an action that passes the arguments of the mock function at -the given indices (0-based) to the inner `action` and performs -it. Using `WithArgs`, our original example can be written as: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::WithArgs; -... - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); - // No need to define your own adaptor. -``` - -For better readability, Google Mock also gives you: - - * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and - * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. - -As you may have realized, `InvokeWithoutArgs(...)` is just syntactic -sugar for `WithoutArgs(Inovke(...))`. - -Here are more tips: - - * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. - * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. - * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. - * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. - -## Ignoring Arguments in Action Functions ## - -The selecting-an-action's-arguments recipe showed us one way to make a -mock function and an action with incompatible argument lists fit -together. The downside is that wrapping the action in -`WithArgs<...>()` can get tedious for people writing the tests. - -If you are defining a function, method, or functor to be used with -`Invoke*()`, and you are not interested in some of its arguments, an -alternative to `WithArgs` is to declare the uninteresting arguments as -`Unused`. This makes the definition less cluttered and less fragile in -case the types of the uninteresting arguments change. It could also -increase the chance the action function can be reused. For example, -given - -``` - MOCK_METHOD3(Foo, double(const string& label, double x, double y)); - MOCK_METHOD3(Bar, double(int index, double x, double y)); -``` - -instead of - -``` -using ::testing::_; -using ::testing::Invoke; - -double DistanceToOriginWithLabel(const string& label, double x, double y) { - return sqrt(x*x + y*y); -} - -double DistanceToOriginWithIndex(int index, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOriginWithLabel)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOriginWithIndex)); -``` - -you could write - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Unused; - -double DistanceToOrigin(Unused, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOrigin)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOrigin)); -``` - -## Sharing Actions ## - -Just like matchers, a Google Mock action object consists of a pointer -to a ref-counted implementation object. Therefore copying actions is -also allowed and very efficient. When the last action that references -the implementation object dies, the implementation object will be -deleted. - -If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action -doesn't have an internal state (i.e. if it always does the same thing -no matter how many times it has been called), you can assign it to an -action variable and use that variable repeatedly. For example: - -``` - Action<bool(int*)> set_flag = DoAll(SetArgumentPointee<0>(5), - Return(true)); - ... use set_flag in .WillOnce() and .WillRepeatedly() ... -``` - -However, if the action has its own state, you may be surprised if you -share the action object. Suppose you have an action factory -`IncrementCounter(init)` which creates an action that increments and -returns a counter whose initial value is `init`, using two actions -created from the same expression and using a shared action will -exihibit different behaviors. Example: - -``` - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(IncrementCounter(0)); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(IncrementCounter(0)); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. -``` - -versus - -``` - Action<int()> increment = IncrementCounter(0); - - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(increment); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(increment); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 3 - the counter is shared. -``` - -# Misc Recipes on Using Google Mock # - -## Forcing a Verification ## - -When it's being destoyed, your friendly mock object will automatically -verify that all expectations on it have been satisfied, and will -generate [Google Test](http://code.google.com/p/googletest/) failures -if not. This is convenient as it leaves you with one less thing to -worry about. That is, unless you are not sure if your mock object will -be destoyed. - -How could it be that your mock object won't eventually be destroyed? -Well, it might be created on the heap and owned by the code you are -testing. Suppose there's a bug in that code and it doesn't delete the -mock object properly - you could end up with a passing test when -there's actually a bug. - -Using a heap checker is a good idea and can alleviate the concern, but -its implementation may not be 100% reliable. So, sometimes you do want -to _force_ Google Mock to verify a mock object before it is -(hopefully) destructed. You can do this with -`Mock::VerifyAndClearExpectations(&mock_object)`: - -``` -TEST(MyServerTest, ProcessesRequest) { - using ::testing::Mock; - - MockFoo* const foo = new MockFoo; - EXPECT_CALL(*foo, ...)...; - // ... other expectations ... - - // server now owns foo. - MyServer server(foo); - server.ProcessRequest(...); - - // In case that server's destructor will forget to delete foo, - // this will verify the expectations anyway. - Mock::VerifyAndClearExpectations(foo); -} // server is destroyed when it goes out of scope here. -``` - -**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a -`bool` to indicate whether the verification was successful (`true` for -yes), so you can wrap that function call inside a `ASSERT_TRUE()` if -there is no point going further when the verification has failed. - -## Using Check Points ## - -Sometimes you may want to "reset" a mock object at various check -points in your test: at each check point, you verify that all existing -expectations on the mock object have been satisfied, and then you set -some new expectations on it as if it's newly created. This allows you -to work with a mock object in "phases" whose sizes are each -manageable. - -One such scenario is that in your test's `SetUp()` function, you may -want to put the object you are testing into a certain state, with the -help from a mock object. Once in the desired state, you want to clear -all expectations on the mock, such that in the `TEST_F` body you can -set fresh expectations on it. - -As you may have figured out, the `Mock::VerifyAndClearExpectations()` -function we saw in the previous recipe can help you here. Or, if you -are using `ON_CALL()` to set default actions on the mock object and -want to clear the default actions as well, use -`Mock::VerifyAndClear(&mock_object)` instead. This function does what -`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the -same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. - -Another trick you can use to achieve the same effect is to put the -expectations in sequences and insert calls to a dummy "check-point" -function at specific places. Then you can verify that the mock -function calls do happen at the right time. For example, if you are -exercising code: - -``` -Foo(1); -Foo(2); -Foo(3); -``` - -and want to verify that `Foo(1)` and `Foo(3)` both invoke -`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: - -``` -using ::testing::MockFunction; - -TEST(FooTest, InvokesBarCorrectly) { - MyMock mock; - // Class MockFunction<F> has exactly one mock method. It is named - // Call() and has type F. - MockFunction<void(string check_point_name)> check; - { - InSequence s; - - EXPECT_CALL(mock, Bar("a")); - EXPECT_CALL(check, Call("1")); - EXPECT_CALL(check, Call("2")); - EXPECT_CALL(mock, Bar("a")); - } - Foo(1); - check.Call("1"); - Foo(2); - check.Call("2"); - Foo(3); -} -``` - -The expectation spec says that the first `Bar("a")` must happen before -check point "1", the second `Bar("a")` must happen after check point "2", -and nothing should happen between the two check points. The explicit -check points make it easy to tell which `Bar("a")` is called by which -call to `Foo()`. - -## Mocking Destructors ## - -Sometimes you want to make sure a mock object is destructed at the -right time, e.g. after `bar->A()` is called but before `bar->B()` is -called. We already know that you can specify constraints on the order -of mock function calls, so all we need to do is to mock the destructor -of the mock function. - -This sounds simple, except for one problem: a destructor is a special -function with special syntax and special semantics, and the -`MOCK_METHOD0` macro doesn't work for it: - -``` - MOCK_METHOD0(~MockFoo, void()); // Won't compile! -``` - -The good news is that you can use a simple pattern to achieve the same -effect. First, add a mock function `Die()` to your mock class and call -it in the destructor, like this: - -``` -class MockFoo : public Foo { - ... - // Add the following two lines to the mock class. - MOCK_METHOD0(Die, void()); - virtual ~MockFoo() { Die(); } -}; -``` - -(If the name `Die()` clashes with an existing symbol, choose another -name.) Now, we have translated the problem of testing when a `MockFoo` -object dies to testing when its `Die()` method is called: - -``` - MockFoo* foo = new MockFoo; - MockBar* bar = new MockBar; - ... - { - InSequence s; - - // Expects *foo to die after bar->A() and before bar->B(). - EXPECT_CALL(*bar, A()); - EXPECT_CALL(*foo, Die()); - EXPECT_CALL(*bar, B()); - } -``` - -And that's that. - -## Using Google Mock and Threads ## - -**IMPORTANT NOTE:** What we describe in this recipe is **NOT** true yet, -as Google Mock is not currently thread-safe. However, all we need to -make it thread-safe is to implement some synchronization operations in -`<gtest/internal/gtest-port.h>` - and then the information below will -become true. - -In a **unit** test, it's best if you could isolate and test a piece of -code in a single-threaded context. That avoids race conditions and -dead locks, and makes debugging your test much easier. - -Yet many programs are multi-threaded, and sometimes to test something -we need to pound on it from more than one thread. Google Mock works -for this purpose too. - -Remember the steps for using a mock: - - 1. Create a mock object `foo`. - 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. - 1. The code under test calls methods of `foo`. - 1. Optionally, verify and reset the mock. - 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. - -If you follow the following simple rules, your mocks and threads can -live happily togeter: - - * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. - * Obviously, you can do step #1 without locking. - * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? - * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. - -If you violate the rules (for example, if you set expectations on a -mock while another thread is calling its methods), you get undefined -behavior. That's not fun, so don't do it. - -Google Mock guarantees that the action for a mock function is done in -the same thread that called the mock function. For example, in - -``` - EXPECT_CALL(mock, Foo(1)) - .WillOnce(action1); - EXPECT_CALL(mock, Foo(2)) - .WillOnce(action2); -``` - -if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, -Google Mock will execute `action1` in thread 1 and `action2` in thread -2. - -Google Mock does _not_ impose a sequence on actions performed in -different threads (doing so may create deadlocks as the actions may -need to cooperate). This means that the execution of `action1` and -`action2` in the above example _may_ interleave. If this is a problem, -you should add proper synchronization logic to `action1` and `action2` -to make the test thread-safe. - - -Also, remember that `DefaultValue<T>` is a global resource that -potentially affects _all_ living mock objects in your -program. Naturally, you won't want to mess with it from multiple -threads or when there still are mocks in action. - -## Controlling How Much Information Google Mock Prints ## - -When Google Mock sees something that has the potential of being an -error (e.g. a mock function with no expectation is called, a.k.a. an -uninteresting call, which is allowed but perhaps you forgot to -explicitly ban the call), it prints some warning messages, including -the arguments of the function and the return value. Hopefully this -will remind you to take a look and see if there is indeed a problem. - -Sometimes you are confident that your tests are correct and may not -appreciate such friendly messages. Some other times, you are debugging -your tests or learning about the behavior of the code you are testing, -and wish you could observe every mock call that happens (including -argument values and the return value). Clearly, one size doesn't fit -all. - -You can control how much Google Mock tells you using the -`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string -with three possible values: - - * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. - * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. - * `error`: Google Mock will print errors only (least verbose). - -Alternatively, you can adjust the value of that flag from within your -tests like so: - -``` - ::testing::FLAGS_gmock_verbose = "error"; -``` - -Now, judiciously use the right flag to enable Google Mock serve you better! - -## Running Tests in Emacs ## - -If you build and run your tests in Emacs, the source file locations of -Google Mock and [Google Test](http://code.google.com/p/googletest/) -errors will be highlighted. Just press `<Enter>` on one of them and -you'll be taken to the offending line. Or, you can just type `C-x `` -to jump to the next error. - -To make it even easier, you can add the following lines to your -`~/.emacs` file: - -``` -(global-set-key "\M-m" 'compile) ; m is for make -(global-set-key [M-down] 'next-error) -(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) -``` - -Then you can type `M-m` to start a build, or `M-up`/`M-down` to move -back and forth between errors. - -## Fusing Google Mock Source Files ## - -Google Mock's implementation consists of dozens of files (excluding -its own tests). Sometimes you may want them to be packaged up in -fewer files 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_gmock_files.py` in the `scripts/` directory -(starting with release 1.2.0). Assuming you have Python 2.4 or above -installed on your machine, just go to that directory and run -``` -python fuse_gmock_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. -These three files contain everything you need to use Google Mock (and -Google Test). Just copy them to anywhere you want and you are ready -to write tests and use mocks. You can use the -[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests -against them. - -# Extending Google Mock # - -## Writing New Matchers Quickly ## - -The `MATCHER*` family of macros can be used to define custom matchers -easily. The syntax: - -``` -MATCHER(name, "description string") { statements; } -``` - -will define a matcher with the given name that executes the -statements, which must return a `bool` to indicate if the match -succeeds. Inside the statements, you can refer to the value being -matched by `arg`, and refer to its type by `arg_type`. - -The description string documents what the matcher does, and is used to -generate the failure message when the match fails. Since a -`MATCHER()` is usually defined in a header file shared by multiple C++ -source files, we require the description to be a C-string _literal_ to -avoid possible side effects. It can be empty (`""`), in which case -Google Mock will use the sequence of words in the matcher name as the -description. - -For example: -``` -MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } -``` -allows you to write -``` - // Expects mock_foo.Bar(n) to be called where n is divisible by 7. - EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); -``` -or, -``` - // Verifies that the value of some_expression is divisible by 7. - EXPECT_THAT(some_expression, IsDivisibleBy7()); -``` -If the above assertion fails, it will print something like: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 -``` -where the description `"is divisible by 7"` is automatically calculated from the -matcher name `IsDivisibleBy7`. - -Optionally, you can stream additional information to a hidden argument -named `result_listener` to explain the match result. For example, a -better definition of `IsDivisibleBy7` is: -``` -MATCHER(IsDivisibleBy7, "") { - if ((arg % 7) == 0) - return true; - - *result_listener << "the remainder is " << (arg % 7); - return false; -} -``` - -With this definition, the above assertion will give a better message: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 (the remainder is 6) -``` - -You should let `MatchAndExplain()` print _any additional information_ -that can help a user understand the match result. Note that it should -explain why the match succeeds in case of a success (unless it's -obvious) - this is useful when the matcher is used inside -`Not()`. There is no need to print the argument value itself, as -Google Mock already prints it for you. - -**Notes:** - - 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. - 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. - -## Writing New Parameterized Matchers Quickly ## - -Sometimes you'll want to define a matcher that has parameters. For that you -can use the macro: -``` -MATCHER_P(name, param_name, "description string") { statements; } -``` - -For example: -``` -MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -``` -will allow you to write: -``` - EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -``` -which may lead to this message (assuming `n` is 10): -``` - Value of: Blah("a") - Expected: has absolute value 10 - Actual: -9 -``` - -Note that both the matcher description and its parameter are -printed, making the message human-friendly. - -In the matcher definition body, you can write `foo_type` to -reference the type of a parameter named `foo`. For example, in the -body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write -`value_type` to refer to the type of `value`. - -Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to -`MATCHER_P10` to support multi-parameter matchers: -``` -MATCHER_Pk(name, param_1, ..., param_k, "description string") { statements; } -``` - -Please note that the custom description string is for a particular -**instance** of the matcher, where the parameters have been bound to -actual values. Therefore usually you'll want the parameter values to -be part of the description. Google Mock lets you do that using -Python-style interpolations. The following syntaxes are supported -currently: - -| `%%` | a single `%` character | -|:-----|:-----------------------| -| `%(*)s` | all parameters of the matcher printed as a tuple | -| `%(foo)s` | value of the matcher parameter named `foo` | - -For example, -``` - MATCHER_P2(InClosedRange, low, hi, "is in range [%(low)s, %(hi)s]") { - return low <= arg && arg <= hi; - } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the message: -``` - Expected: is in range [4, 6] -``` - -If you specify `""` as the description, the failure message will -contain the sequence of words in the matcher name followed by the -parameter values printed as a tuple. For example, -``` - MATCHER_P2(InClosedRange, low, hi, "") { ... } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the text: -``` - Expected: in closed range (4, 6) -``` - -For the purpose of typing, you can view -``` -MATCHER_Pk(Foo, p1, ..., pk, "description string") { ... } -``` -as shorthand for -``` -template <typename p1_type, ..., typename pk_type> -FooMatcherPk<p1_type, ..., pk_type> -Foo(p1_type p1, ..., pk_type pk) { ... } -``` - -When you write `Foo(v1, ..., vk)`, the compiler infers the types of -the parameters `v1`, ..., and `vk` for you. If you are not happy with -the result of the type inference, you can specify the types by -explicitly instantiating the template, as in `Foo<long, bool>(5, false)`. -As said earlier, you don't get to (or need to) specify -`arg_type` as that's determined by the context in which the matcher -is used. - -You can assign the result of expression `Foo(p1, ..., pk)` to a -variable of type `FooMatcherPk<p1_type, ..., pk_type>`. This can be -useful when composing matchers. Matchers that don't have a parameter -or have only one parameter have special types: you can assign `Foo()` -to a `FooMatcher`-typed variable, and assign `Foo(p)` to a -`FooMatcherP<p_type>`-typed variable. - -While you can instantiate a matcher template with reference types, -passing the parameters by pointer usually makes your code more -readable. If, however, you still want to pass a parameter by -reference, be aware that in the failure message generated by the -matcher you will see the value of the referenced object but not its -address. - -You can overload matchers with different numbers of parameters: -``` -MATCHER_P(Blah, a, "description string 1") { ... } -MATCHER_P2(Blah, a, b, "description string 2") { ... } -``` - -While it's tempting to always use the `MATCHER*` macros when defining -a new matcher, you should also consider implementing -`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see -the recipes that follow), especially if you need to use the matcher a -lot. While these approaches require more work, they give you more -control on the types of the value being matched and the matcher -parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers -based on parameter types (as opposed to just based on the number of -parameters). - -## Writing New Monomorphic Matchers ## - -A matcher of argument type `T` implements -`::testing::MatcherInterface<T>` and does two things: it tests whether a -value of type `T` matches the matcher, and can describe what kind of -values it matches. The latter ability is used for generating readable -error messages when expectations are violated. - -The interface looks like this: - -``` -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template <typename T> - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - ::std::ostream* stream(); -}; - -template <typename T> -class MatcherInterface { - public: - virtual ~MatcherInterface(); - - // Returns true iff the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; -}; -``` - -If you need a custom matcher but `Truly()` is not a good option (for -example, you may not be happy with the way `Truly(predicate)` -describes itself, or you may want your matcher to be polymorphic as -`Eq(value)` is), you can define a matcher to do whatever you want in -two steps: first implement the matcher interface, and then define a -factory function to create a matcher instance. The second step is not -strictly needed but it makes the syntax of using the matcher nicer. - -For example, you can define a matcher to test whether an `int` is -divisible by 7 and then use it like this: -``` -using ::testing::MakeMatcher; -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { - return (n % 7) == 0; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "is divisible by 7"; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "is not divisible by 7"; - } -}; - -inline Matcher<int> DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); -} -... - - EXPECT_CALL(foo, Bar(DivisibleBy7())); -``` - -You may improve the matcher message by streaming additional -information to the `listener` argument in `MatchAndExplain()`: - -``` -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, - MatchResultListener* listener) const { - const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; - } - return remainder == 0; - } - ... -}; -``` - -Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: -``` -Value of: x -Expected: is divisible by 7 - Actual: 23 (the remainder is 2) -``` - -## Writing New Polymorphic Matchers ## - -You've learned how to write your own matchers in the previous -recipe. Just one problem: a matcher created using `MakeMatcher()` only -works for one particular type of arguments. If you want a -_polymorphic_ matcher that works with arguments of several types (for -instance, `Eq(x)` can be used to match a `value` as long as `value` == -`x` compiles -- `value` and `x` don't have to share the same type), -you can learn the trick from `<gmock/gmock-matchers.h>` but it's a bit -involved. - -Fortunately, most of the time you can define a polymorphic matcher -easily with the help of `MakePolymorphicMatcher()`. Here's how you can -define `NotNull()` as an example: - -``` -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -using ::testing::NotNull; -using ::testing::PolymorphicMatcher; - -class NotNullMatcher { - public: - // To implement a polymorphic matcher, first define a COPYABLE class - // that has three members MatchAndExplain(), DescribeTo(), and - // DescribeNegationTo(), like the following. - - // In this example, we want to use NotNull() with any pointer, so - // MatchAndExplain() accepts a pointer of any type as its first argument. - // In general, you can define MatchAndExplain() as an ordinary method or - // a method template, or even overload it. - template <typename T> - bool MatchAndExplain(T* p, - MatchResultListener* /* listener */) const { - return p != NULL; - } - - // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } - - // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } -}; - -// To construct a polymorphic matcher, pass an instance of the class -// to MakePolymorphicMatcher(). Note the return type. -inline PolymorphicMatcher<NotNullMatcher> NotNull() { - return MakePolymorphicMatcher(NotNullMatcher()); -} -... - - EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. -``` - -**Note:** Your polymorphic matcher class does **not** need to inherit from -`MatcherInterface` or any other class, and its methods do **not** need -to be virtual. - -Like in a monomorphic matcher, you may explain the match result by -streaming additional information to the `listener` argument in -`MatchAndExplain()`. - -## Writing New Cardinalities ## - -A cardinality is used in `Times()` to tell Google Mock how many times -you expect a call to occur. It doesn't have to be exact. For example, -you can say `AtLeast(5)` or `Between(2, 4)`. - -If the built-in set of cardinalities doesn't suit you, you are free to -define your own by implementing the following interface (in namespace -`testing`): - -``` -class CardinalityInterface { - public: - virtual ~CardinalityInterface(); - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; -``` - -For example, to specify that a call must occur even number of times, -you can write - -``` -using ::testing::Cardinality; -using ::testing::CardinalityInterface; -using ::testing::MakeCardinality; - -class EvenNumberCardinality : public CardinalityInterface { - public: - virtual bool IsSatisfiedByCallCount(int call_count) const { - return (call_count % 2) == 0; - } - - virtual bool IsSaturatedByCallCount(int call_count) const { - return false; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "called even number of times"; - } -}; - -Cardinality EvenNumber() { - return MakeCardinality(new EvenNumberCardinality); -} -... - - EXPECT_CALL(foo, Bar(3)) - .Times(EvenNumber()); -``` - -## Writing New Actions Quickly ## - -If the built-in actions don't work for you, and you find it -inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` -family to quickly define a new action that can be used in your code as -if it's a built-in action. - -By writing -``` -ACTION(name) { statements; } -``` -in a namespace scope (i.e. not inside a class or function), you will -define an action with the given name that executes the statements. -The value returned by `statements` will be used as the return value of -the action. Inside the statements, you can refer to the K-th -(0-based) argument of the mock function as `argK`. For example: -``` -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -``` -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments. Rest assured that your code is type-safe though: -you'll get a compiler error if `*arg1` doesn't support the `++` -operator, or if the type of `++(*arg1)` isn't compatible with the mock -function's return type. - -Another example: -``` -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -``` -int DoSomething(bool flag, int* ptr); -``` -we have: -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `std::tr1::tuple<bool, int*>` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Writing New Parameterized Actions Quickly ## - -Sometimes you'll want to parameterize an action you define. For that -we have another macro -``` -ACTION_P(name, param) { statements; } -``` - -For example, -``` -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -``` -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. For example, in the body of -`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. - -Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -``` -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -``` -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -You can also easily define actions overloaded on the number of parameters: -``` -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -## Restricting the Type of an Argument or Parameter in an ACTION ## - -For maximum brevity and reusability, the `ACTION*` macros don't ask -you to provide the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -``` -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq<const char*, arg1_type>(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion in Google Test -that verifies two types are the same. - -## Writing New Action Templates Quickly ## - -Sometimes you want to give an action explicit template parameters that -cannot be inferred from its value parameters. `ACTION_TEMPLATE()` -supports that and can be viewed as an extension to `ACTION()` and -`ACTION_P*()`. - -The syntax: -``` -ACTION_TEMPLATE(ActionName, - HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), - AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -``` - -defines an action template that takes _m_ explicit template parameters -and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is -between 0 and 10. `name_i` is the name of the i-th template -parameter, and `kind_i` specifies whether it's a `typename`, an -integral constant, or a template. `p_i` is the name of the i-th value -parameter. - -Example: -``` -// DuplicateArg<k, T>(output) converts the k-th argument of the mock -// function to type T and copies it to *output. -ACTION_TEMPLATE(DuplicateArg, - // Note the comma between int and k: - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(output)) { - *output = T(std::tr1::get<k>(args)); -} -``` - -To create an instance of an action template, write: -``` - ActionName<t1, ..., t_m>(v1, ..., v_n) -``` -where the `t`s are the template arguments and the -`v`s are the value arguments. The value argument -types are inferred by the compiler. For example: -``` -using ::testing::_; -... - int n; - EXPECT_CALL(mock, Foo(_, _)) - .WillOnce(DuplicateArg<1, unsigned char>(&n)); -``` - -If you want to explicitly specify the value argument types, you can -provide additional template arguments: -``` - ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) -``` -where `u_i` is the desired type of `v_i`. - -`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the -number of value parameters, but not on the number of template -parameters. Without the restriction, the meaning of the following is -unclear: - -``` - OverloadedAction<int, bool>(x); -``` - -Are we using a single-template-parameter action where `bool` refers to -the type of `x`, or a two-template-parameter action where the compiler -is asked to infer the type of `x`? - -## Using the ACTION Object's Type ## - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | -| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of value -parameters, or the action definitions cannot be overloaded on the -number of them. - -## Writing New Monomorphic Actions ## - -While the `ACTION*` macros are very convenient, sometimes they are -inappropriate. For example, despite the tricks shown in the previous -recipes, they don't let you directly specify the types of the mock -function arguments and the action parameters, which in general leads -to unoptimized compiler error messages that can baffle unfamiliar -users. They also don't allow overloading actions based on parameter -types without jumping through some hoops. - -An alternative to the `ACTION*` macros is to implement -`::testing::ActionInterface<F>`, where `F` is the type of the mock -function in which the action will be used. For example: - -``` -template <typename F>class ActionInterface { - public: - virtual ~ActionInterface(); - - // Performs the action. Result is the return type of function type - // F, and ArgumentTuple is the tuple of arguments of F. - // - // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>. - virtual Result Perform(const ArgumentTuple& args) = 0; -}; - -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::MakeAction; - -typedef int IncrementMethod(int*); - -class IncrementArgumentAction : public ActionInterface<IncrementMethod> { - public: - virtual int Perform(const tr1::tuple<int*>& args) { - int* p = tr1::get<0>(args); // Grabs the first argument. - return *p++; - } -}; - -Action<IncrementMethod> IncrementArgument() { - return MakeAction(new IncrementArgumentAction); -} -... - - EXPECT_CALL(foo, Baz(_)) - .WillOnce(IncrementArgument()); - - int n = 5; - foo.Baz(&n); // Should return 5 and change n to 6. -``` - -## Writing New Polymorphic Actions ## - -The previous recipe showed you how to define your own action. This is -all good, except that you need to know the type of the function in -which the action will be used. Sometimes that can be a problem. For -example, if you want to use the action in functions with _different_ -types (e.g. like `Return()` and `SetArgumentPointee()`). - -If an action can be used in several types of mock functions, we say -it's _polymorphic_. The `MakePolymorphicAction()` function template -makes it easy to define such an action: - -``` -namespace testing { - -template <typename Impl> -PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); - -} // namespace testing -``` - -As an example, let's define an action that returns the second argument -in the mock function's argument list. The first step is to define an -implementation class: - -``` -class ReturnSecondArgumentAction { - public: - template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use tr1::get<i>(args). - return tr1::get<1>(args); - } -}; -``` - -This implementation class does _not_ need to inherit from any -particular class. What matters is that it must have a `Perform()` -method template. This method template takes the mock function's -arguments as a tuple in a **single** argument, and returns the result of -the action. It can be either `const` or not, but must be invokable -with exactly one template argument, which is the result type. In other -words, you must be able to call `Perform<R>(args)` where `R` is the -mock function's return type and `args` is its arguments in a tuple. - -Next, we use `MakePolymorphicAction()` to turn an instance of the -implementation class into the polymorphic action we need. It will be -convenient to have a wrapper for this: - -``` -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; - -PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { - return MakePolymorphicAction(ReturnSecondArgumentAction()); -} -``` - -Now, you can use this polymorphic action the same way you use the -built-in ones: - -``` -using ::testing::_; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, int(bool flag, int n)); - MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(ReturnSecondArgument()); - EXPECT_CALL(foo, DoThat(_, _, _)) - .WillOnce(ReturnSecondArgument()); - ... - foo.DoThis(true, 5); // Will return 5. - foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". -``` - -## Teaching Google Mock How to Print Your Values ## - -When an uninteresting or unexpected call occurs, Google Mock prints -the argument values to help you debug. The `EXPECT_THAT` and -`ASSERT_THAT` assertions also print the value being validated when the -test fails. Google Mock does this using the user-extensible value -printer defined in `<gmock/gmock-printers.h>`. - -This printer knows how to print the 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 hope you the -user can figure it out. - -Did I say that 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, you just need to define `<<` for your type: - -``` -#include <iostream> - -namespace foo { - -class Foo { ... }; - -// It's important that the << operator is defined in the SAME -// namespace that defines Foo. C++'s look-up rules rely on that. -::std::ostream& operator<<(::std::ostream& os, const Foo& foo) { - return os << foo.DebugString(); // Whatever needed to print foo to os. -} - -} // namespace foo -``` - -Sometimes, this might not be an option. For example, your team may -consider it dangerous or bad style to have a `<<` operator for `Foo`, -or `Foo` may already have a `<<` operator that doesn't do what you -want (and you cannot change it). Don't despair though - Google Mock -gives you a second chance to get it right. Namely, you can define a -`PrintTo()` function like this: - -``` -#include <iostream> - -namespace foo { - -class Foo { ... }; - -// It's important that PrintTo() is defined in the SAME -// namespace that defines Foo. C++'s look-up rules rely on that. -void PrintTo(const Foo& foo, ::std::ostream* os) { - *os << foo.DebugString(); // Whatever needed to print foo to os. -} - -} // namespace foo -``` - -What if you have both `<<` and `PrintTo()`? In this case, the latter -will override the former when Google Mock is concerned. This allows -you to customize how the value should appear in Google Mock's output -without affecting code that relies on the behavior of its `<<` -operator. - -**Note:** When printing a pointer of type `T*`, Google Mock calls -`PrintTo(T*, std::ostream* os)` instead of `operator<<(std::ostream&, T*)`. -Therefore the only way to affect how a pointer is printed by Google -Mock is to define `PrintTo()` for it. Also note that `T*` and `const T*` -are different types, so you may need to define `PrintTo()` for both. - -Why does Google Mock treat pointers specially? There are several reasons: - - * We cannot use `operator<<` to print a `signed char*` or `unsigned char*`, since it will print the pointer as a NUL-terminated C string, which likely will cause an access violation. - * We want `NULL` pointers to be printed as `"NULL"`, but `operator<<` prints it as `"0"`, `"nullptr"`, or something else, depending on the compiler. - * With some compilers, printing a `NULL` `char*` using `operator<<` will segfault. - * `operator<<` prints a function pointer as a `bool` (hence it always prints `"1"`), which is not very useful. \ No newline at end of file diff --git a/googlemock/docs/v1_5/Documentation.md b/googlemock/docs/v1_5/Documentation.md deleted file mode 100644 index 315b0a29..00000000 --- a/googlemock/docs/v1_5/Documentation.md +++ /dev/null @@ -1,11 +0,0 @@ -This page lists all documentation wiki pages for Google Mock **version 1.5.0** -- **if you use a different version of Google Mock, please read the documentation for that specific version instead.** - - * [ForDummies](V1_5_ForDummies.md) -- start here if you are new to Google Mock. - * [CheatSheet](V1_5_CheatSheet.md) -- a quick reference. - * [CookBook](V1_5_CookBook.md) -- recipes for doing various tasks using Google Mock. - * [FrequentlyAskedQuestions](V1_5_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Mock, read: - - * DevGuide -- read this _before_ writing your first patch. - * [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files. \ No newline at end of file diff --git a/googlemock/docs/v1_5/ForDummies.md b/googlemock/docs/v1_5/ForDummies.md deleted file mode 100644 index fcc3b561..00000000 --- a/googlemock/docs/v1_5/ForDummies.md +++ /dev/null @@ -1,439 +0,0 @@ - - -(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](V1_5_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md).) - -# What Is Google C++ Mocking Framework? # -When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). - -**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: - - * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. - * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. - -If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. - -**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. - -Using Google Mock involves three basic steps: - - 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; - 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; - 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. - -# Why Google Mock? # -While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. - * The knowledge you gained from using one mock doesn't transfer to the next. - -In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. - -Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: - - * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". - * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). - * Your tests are brittle as some resources they use are unreliable (e.g. the network). - * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. - * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. - * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. - -We encourage you to use Google Mock as: - - * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! - * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. - -# Getting Started # -Using Google Mock is easy! Inside your C++ source file, just `#include` `<gtest/gtest.h>` and `<gmock/gmock.h>`, and you are ready to go. - -# A Case for Mock Turtles # -Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: - -``` -class Turtle { - ... - virtual ~Turtle() {} - virtual void PenUp() = 0; - virtual void PenDown() = 0; - virtual void Forward(int distance) = 0; - virtual void Turn(int degrees) = 0; - virtual void GoTo(int x, int y) = 0; - virtual int GetX() const = 0; - virtual int GetY() const = 0; -}; -``` - -(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) - -You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. - -Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. - -# Writing the Mock Class # -If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) - -## How to Define It ## -Using the `Turtle` interface as example, here are the simple steps you need to follow: - - 1. Derive a class `MockTurtle` from `Turtle`. - 1. Take a virtual function of `Turtle`. Count how many arguments it has. - 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. - 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). - 1. Repeat until all virtual functions you want to mock are done. - -After the process, you should have something like: - -``` -#include <gmock/gmock.h> // Brings in Google Mock. -class MockTurtle : public Turtle { - public: - ... - MOCK_METHOD0(PenUp, void()); - MOCK_METHOD0(PenDown, void()); - MOCK_METHOD1(Forward, void(int distance)); - MOCK_METHOD1(Turn, void(int degrees)); - MOCK_METHOD2(GoTo, void(int x, int y)); - MOCK_CONST_METHOD0(GetX, int()); - MOCK_CONST_METHOD0(GetY, int()); -}; -``` - -You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. - -**Tip:** If even this is too much work for you, you'll find the -`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line -tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, -and it will print the definition of the mock class for you. Due to the -complexity of the C++ language, this script may not always work, but -it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). - -## Where to Put It ## -When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) - -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. - -Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - -# Using Mocks in Tests # -Once you have a mock class, using it is easy. The typical work flow is: - - 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). - 1. Create some mock objects. - 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). - 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. - 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. - -Here's an example: - -``` -#include "path/to/mock-turtle.h" -#include <gmock/gmock.h> -#include <gtest/gtest.h> -using ::testing::AtLeast; // #1 - -TEST(PainterTest, CanDrawSomething) { - MockTurtle turtle; // #2 - EXPECT_CALL(turtle, PenDown()) // #3 - .Times(AtLeast(1)); - - Painter painter(&turtle); // #4 - - EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); -} // #5 - -int main(int argc, char** argv) { - // The following line must be executed to initialize Google Mock - // (and Google Test) before running the tests. - ::testing::InitGoogleMock(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: - -``` -path/to/my_test.cc:119: Failure -Actual function call count doesn't match this expectation: -Actually: never called; -Expected: called at least once. -``` - -**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. - -**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. - -**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. - -This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. - -Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. - -## Using Google Mock with Any Testing Framework ## -If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: -``` -int main(int argc, char** argv) { - // The following line causes Google Mock to throw an exception on failure, - // which will be interpreted by your testing framework as a test failure. - ::testing::GTEST_FLAG(throw_on_failure) = true; - ::testing::InitGoogleMock(&argc, argv); - ... whatever your testing framework requires ... -} -``` - -This approach has a catch: it makes Google Mock throw an exception -from a mock object's destructor sometimes. With some compilers, this -sometimes causes the test program to crash. You'll still be able to -notice that the test has failed, but it's not a graceful failure. - -A better solution is to use Google Test's -[event listener API](http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) -to report a test failure to your testing framework properly. You'll need to -implement the `OnTestPartResult()` method of the event listener interface, but it -should be straightforward. - -If this turns out to be too much work, we suggest that you stick with -Google Test, which works with Google Mock seamlessly (in fact, it is -technically part of Google Mock.). If there is a reason that you -cannot use Google Test, please let us know. - -# Setting Expectations # -The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." - -## General Syntax ## -In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: - -``` -EXPECT_CALL(mock_object, method(matchers)) - .Times(cardinality) - .WillOnce(action) - .WillRepeatedly(action); -``` - -The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) - -The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. - -This syntax is designed to make an expectation read like English. For example, you can probably guess that - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .Times(5) - .WillOnce(Return(100)) - .WillOnce(Return(150)) - .WillRepeatedly(Return(200)); -``` - -says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). - -**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. - -## Matchers: What Arguments Do We Expect? ## -When a mock function takes arguments, we must specify what arguments we are expecting; for example: - -``` -// Expects the turtle to move forward by 100 units. -EXPECT_CALL(turtle, Forward(100)); -``` - -Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": - -``` -using ::testing::_; -... -// Expects the turtle to move forward. -EXPECT_CALL(turtle, Forward(_)); -``` - -`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. - -A list of built-in matchers can be found in the [CheatSheet](V1_5_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: - -``` -using ::testing::Ge;... -EXPECT_CALL(turtle, Forward(Ge(100))); -``` - -This checks that the turtle will be told to go forward by at least 100 units. - -## Cardinalities: How Many Times Will It Be Called? ## -The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. - -An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. - -We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_5_CheatSheet.md). - -The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: - - * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. - * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. - * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. - -**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? - -## Actions: What Should It Do? ## -Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. - -First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. - -Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillOnce(Return(300)); -``` - -This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillRepeatedly(Return(300)); -``` - -says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. - -Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). - -What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](V1_5_CheatSheet#Actions.md). - -**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: - -``` -int n = 100; -EXPECT_CALL(turtle, GetX()) -.Times(4) -.WillOnce(Return(n++)); -``` - -Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_5_CookBook.md). - -Time for another quiz! What do you think the following means? - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) -.Times(4) -.WillOnce(Return(100)); -``` - -Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. - -## Using Multiple Expectations ## -So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. - -By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: - -``` -using ::testing::_;... -EXPECT_CALL(turtle, Forward(_)); // #1 -EXPECT_CALL(turtle, Forward(10)) // #2 - .Times(2); -``` - -If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. - -**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. - -## Ordered vs Unordered Calls ## -By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. - -Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: - -``` -using ::testing::InSequence;... -TEST(FooTest, DrawsLineSegment) { - ... - { - InSequence dummy; - - EXPECT_CALL(turtle, PenDown()); - EXPECT_CALL(turtle, Forward(100)); - EXPECT_CALL(turtle, PenUp()); - } - Foo(); -} -``` - -By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. - -In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. - -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_5_CookBook.md).) - -## All Expectations Are Sticky (Unless Said Otherwise) ## -Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? - -After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): - -``` -using ::testing::_;... -EXPECT_CALL(turtle, GoTo(_, _)) // #1 - .Times(AnyNumber()); -EXPECT_CALL(turtle, GoTo(0, 0)) // #2 - .Times(2); -``` - -Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. - -This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). - -Simple? Let's see if you've really understood it: what does the following code say? - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)); -} -``` - -If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! - -One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); -} -``` - -And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: - -``` -using ::testing::InSequence; -using ::testing::Return; -... -{ - InSequence s; - - for (int i = 1; i <= n; i++) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); - } -} -``` - -By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). - -## Uninteresting Calls ## -A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. - -In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. - -# What Now? # -Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. - -Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_5_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. \ No newline at end of file diff --git a/googlemock/docs/v1_5/FrequentlyAskedQuestions.md b/googlemock/docs/v1_5/FrequentlyAskedQuestions.md deleted file mode 100644 index 7593243c..00000000 --- a/googlemock/docs/v1_5/FrequentlyAskedQuestions.md +++ /dev/null @@ -1,624 +0,0 @@ - - -Please send your questions to the -[googlemock](http://groups.google.com/group/googlemock) discussion -group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. - -## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## - -After version 1.4.0 of Google Mock was released, we had an idea on how -to make it easier to write matchers that can generate informative -messages efficiently. We experimented with this idea and liked what -we saw. Therefore we decided to implement it. - -Unfortunately, this means that if you have defined your own matchers -by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, -your definitions will no longer compile. Matchers defined using the -`MATCHER*` family of macros are not affected. - -Sorry for the hassle if your matchers are affected. We believe it's -in everyone's long-term interest to make this change sooner than -later. Fortunately, it's usually not hard to migrate an existing -matcher to the new API. Here's what you need to do: - -If you wrote your matcher like this: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` - -you'll need to change it to: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` -(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second -argument of type `MatchResultListener*`.) - -If you were also using `ExplainMatchResultTo()` to improve the matcher -message: -``` -// Old matcher definition that doesn't work with the lastest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - - virtual void ExplainMatchResultTo(MyType value, - ::std::ostream* os) const { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Foo property is " << value.GetFoo(); - } - ... -}; -``` - -you should move the logic of `ExplainMatchResultTo()` into -`MatchAndExplain()`, using the `MatchResultListener` argument where -the `::std::ostream` was used: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Foo property is " << value.GetFoo(); - return value.GetFoo() > 5; - } - ... -}; -``` - -If your matcher is defined using `MakePolymorphicMatcher()`: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you should rename the `Matches()` method to `MatchAndExplain()` and -add a `MatchResultListener*` argument (the same as what you need to do -for matchers defined by implementing `MatcherInterface`): -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -If your polymorphic matcher uses `ExplainMatchResultTo()` for better -failure messages: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -void ExplainMatchResultTo(const MyGreatMatcher& matcher, - MyType value, - ::std::ostream* os) { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Bar property is " << value.GetBar(); -} -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you'll need to move the logic inside `ExplainMatchResultTo()` to -`MatchAndExplain()`: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Bar property is " << value.GetBar(); - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -For more information, you can read these -[two](V1_5_CookBook#Writing_New_Monomorphic_Matchers.md) -[recipes](V1_5_CookBook#Writing_New_Polymorphic_Matchers.md) -from the cookbook. As always, you -are welcome to post questions on `googlemock@googlegroups.com` if you -need any help. - -## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## - -Google Mock works out of the box with Google Test. However, it's easy -to configure it to work with any testing framework of your choice. -[Here](V1_5_ForDummies#Using_Google_Mock_with_Any_Testing_Framework.md) is how. - -## How am I supposed to make sense of these horrible template errors? ## - -If you are confused by the compiler errors gcc threw at you, -try consulting the _Google Mock Doctor_ tool first. What it does is to -scan stdin for gcc error messages, and spit out diagnoses on the -problems (we call them diseases) your code has. - -To "install", run command: -``` -alias gmd='<path to googlemock>/scripts/gmock_doctor.py' -``` - -To use it, do: -``` -<your-favorite-build-command> <your-test> 2>&1 | gmd -``` - -For example: -``` -make my_test 2>&1 | gmd -``` - -Or you can run `gmd` and copy-n-paste gcc's error messages to it. - -## Can I mock a variadic function? ## - -You cannot mock a variadic function (i.e. a function taking ellipsis -(`...`) arguments) directly in Google Mock. - -The problem is that in general, there is _no way_ for a mock object to -know how many arguments are passed to the variadic method, and what -the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into his head. - -Therefore, to mock such a function, the _user_ must teach the mock -object how to figure out the number of arguments and their types. One -way to do it is to provide overloaded versions of the function. - -Ellipsis arguments are inherited from C and not really a C++ feature. -They are unsafe to use and don't work with arguments that have -constructors or destructors. Therefore we recommend to avoid them in -C++ as much as possible. - -## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## - -If you compile this using Microsoft Visual C++ 2005 SP1: -``` -class Foo { - ... - virtual void Bar(const int i) = 0; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Bar, void(const int i)); -}; -``` -You may get the following warning: -``` -warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier -``` - -This is a MSVC bug. The same code compiles fine with gcc ,for -example. If you use Visual C++ 2008 SP1, you would get the warning: -``` -warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers -``` - -In C++, if you _declare_ a function with a `const` parameter, the -`const` modifier is _ignored_. Therefore, the `Foo` base class above -is equivalent to: -``` -class Foo { - ... - virtual void Bar(int i) = 0; // int or const int? Makes no difference. -}; -``` - -In fact, you can _declare_ Bar() with an `int` parameter, and _define_ -it with a `const int` parameter. The compiler will still match them -up. - -Since making a parameter `const` is meaningless in the method -_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. -That should workaround the VC bug. - -Note that we are talking about the _top-level_ `const` modifier here. -If the function parameter is passed by pointer or reference, declaring -the _pointee_ or _referee_ as `const` is still meaningful. For -example, the following two declarations are _not_ equivalent: -``` -void Bar(int* p); // Neither p nor *p is const. -void Bar(const int* p); // p is not const, but *p is. -``` - -## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## - -We've noticed that when the `/clr` compiler flag is used, Visual C++ -uses 5~6 times as much memory when compiling a mock class. We suggest -to avoid `/clr` when compiling native C++ mocks. - -## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## - -You might want to run your test with -`--gmock_verbose=info`. This flag lets Google Mock print a trace -of every mock function call it receives. By studying the trace, -you'll gain insights on why the expectations you set are not met. - -## How can I assert that a function is NEVER called? ## - -``` -EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## - -When Google Mock detects a failure, it prints relevant information -(the mock function arguments, the state of relevant expectations, and -etc) to help the user debug. If another failure is detected, Google -Mock will do the same, including printing the state of relevant -expectations. - -Sometimes an expectation's state didn't change between two failures, -and you'll see the same description of the state twice. They are -however _not_ redundant, as they refer to _different points in time_. -The fact they are the same _is_ interesting information. - -## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## - -Does the class (hopefully a pure interface) you are mocking have a -virtual destructor? - -Whenever you derive from a base class, make sure its destructor is -virtual. Otherwise Bad Things will happen. Consider the following -code: - -``` -class Base { - public: - // Not virtual, but should be. - ~Base() { ... } - ... -}; - -class Derived : public Base { - public: - ... - private: - std::string value_; -}; - -... - Base* p = new Derived; - ... - delete p; // Surprise! ~Base() will be called, but ~Derived() will not - // - value_ is leaked. -``` - -By changing `~Base()` to virtual, `~Derived()` will be correctly -called when `delete p` is executed, and the heap checker -will be happy. - -## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## - -When people complain about this, often they are referring to code like: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. However, I have to write the expectations in the -// reverse order. This sucks big time!!! -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); -``` - -The problem is that they didn't pick the **best** way to express the test's -intent. - -By default, expectations don't have to be matched in _any_ particular -order. If you want them to match in a certain order, you need to be -explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's -easy to accidentally over-specify your tests, and we want to make it -harder to do so. - -There are two better ways to write the test spec. You could either -put the expectations in sequence: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. Using a sequence, we can write the expectations -// in their natural order. -{ - InSequence s; - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -} -``` - -or you can put the sequence of actions in the same expectation: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -``` - -Back to the original questions: why does Google Mock search the -expectations (and `ON_CALL`s) from back to front? Because this -allows a user to set up a mock's behavior for the common case early -(e.g. in the mock's constructor or the test fixture's set-up phase) -and customize it with more specific rules later. If Google Mock -searches from front to back, this very useful pattern won't be -possible. - -## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## - -When choosing between being neat and being safe, we lean toward the -latter. So the answer is that we think it's better to show the -warning. - -Often people write `ON_CALL`s in the mock object's -constructor or `SetUp()`, as the default behavior rarely changes from -test to test. Then in the test body they set the expectations, which -are often different for each test. Having an `ON_CALL` in the set-up -part of a test doesn't mean that the calls are expected. If there's -no `EXPECT_CALL` and the method is called, it's possibly an error. If -we quietly let the call go through without notifying the user, bugs -may creep in unnoticed. - -If, however, you are sure that the calls are OK, you can write - -``` -EXPECT_CALL(foo, Bar(_)) - .WillRepeatedly(...); -``` - -instead of - -``` -ON_CALL(foo, Bar(_)) - .WillByDefault(...); -``` - -This tells Google Mock that you do expect the calls and no warning should be -printed. - -Also, you can control the verbosity using the `--gmock_verbose` flag. -If you find the output too noisy when debugging, just choose a less -verbose level. - -## How can I delete the mock function's argument in an action? ## - -If you find yourself needing to perform some action that's not -supported by Google Mock directly, remember that you can define your own -actions using -[MakeAction()](V1_5_CookBook#Writing_New_Actions.md) or -[MakePolymorphicAction()](V1_5_CookBook#Writing_New_Polymorphic_Actions.md), -or you can write a stub function and invoke it using -[Invoke()](V1_5_CookBook#Using_Functions_Methods_Functors.md). - -## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## - -What?! I think it's beautiful. :-) - -While which syntax looks more natural is a subjective matter to some -extent, Google Mock's syntax was chosen for several practical advantages it -has. - -Try to mock a function that takes a map as an argument: -``` -virtual int GetSize(const map<int, std::string>& m); -``` - -Using the proposed syntax, it would be: -``` -MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); -``` - -Guess what? You'll get a compiler error as the compiler thinks that -`const map<int, std::string>& m` are **two**, not one, arguments. To work -around this you can use `typedef` to give the map type a name, but -that gets in the way of your work. Google Mock's syntax avoids this -problem as the function's argument types are protected inside a pair -of parentheses: -``` -// This compiles fine. -MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); -``` - -You still need a `typedef` if the return type contains an unprotected -comma, but that's much rarer. - -Other advantages include: - 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. - 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. - 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! - -## My code calls a static/global function. Can I mock it? ## - -You can, but you need to make some changes. - -In general, if you find yourself needing to mock a static function, -it's a sign that your modules are too tightly coupled (and less -flexible, less reusable, less testable, etc). You are probably better -off defining a small interface and call the function through that -interface, which then can be easily mocked. It's a bit of work -initially, but usually pays for itself quickly. - -This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) -says it excellently. Check it out. - -## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## - -I know it's not a question, but you get an answer for free any way. :-) - -With Google Mock, you can create mocks in C++ easily. And people might be -tempted to use them everywhere. Sometimes they work great, and -sometimes you may find them, well, a pain to use. So, what's wrong in -the latter case? - -When you write a test without using mocks, you exercise the code and -assert that it returns the correct value or that the system is in an -expected state. This is sometimes called "state-based testing". - -Mocks are great for what some call "interaction-based" testing: -instead of checking the system state at the very end, mock objects -verify that they are invoked the right way and report an error as soon -as it arises, giving you a handle on the precise context in which the -error was triggered. This is often more effective and economical to -do than state-based testing. - -If you are doing state-based testing and using a test double just to -simulate the real object, you are probably better off using a fake. -Using a mock in this case causes pain, as it's not a strong point for -mocks to perform complex actions. If you experience this and think -that mocks suck, you are just not using the right tool for your -problem. Or, you might be trying to solve the wrong problem. :-) - -## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## - -By all means, NO! It's just an FYI. - -What it means is that you have a mock function, you haven't set any -expectations on it (by Google Mock's rule this means that you are not -interested in calls to this function and therefore it can be called -any number of times), and it is called. That's OK - you didn't say -it's not OK to call the function! - -What if you actually meant to disallow this function to be called, but -forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While -one can argue that it's the user's fault, Google Mock tries to be nice and -prints you a note. - -So, when you see the message and believe that there shouldn't be any -uninteresting calls, you should investigate what's going on. To make -your life easier, Google Mock prints the function name and arguments -when an uninteresting call is encountered. - -## I want to define a custom action. Should I use Invoke() or implement the action interface? ## - -Either way is fine - you want to choose the one that's more convenient -for your circumstance. - -Usually, if your action is for a particular function type, defining it -using `Invoke()` should be easier; if your action can be used in -functions of different types (e.g. if you are defining -`Return(value)`), `MakePolymorphicAction()` is -easiest. Sometimes you want precise control on what types of -functions the action can be used in, and implementing -`ActionInterface` is the way to go here. See the implementation of -`Return()` in `include/gmock/gmock-actions.h` for an example. - -## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## - -You got this error as Google Mock has no idea what value it should return -when the mock method is called. `SetArgumentPointee()` says what the -side effect is, but doesn't say what the return value should be. You -need `DoAll()` to chain a `SetArgumentPointee()` with a `Return()`. - -See this [recipe](V1_5_CookBook#Mocking_Side_Effects.md) for more details and an example. - - -## My question is not in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), - 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). - -Please note that creating an issue in the -[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. \ No newline at end of file diff --git a/googlemock/docs/v1_6/CheatSheet.md b/googlemock/docs/v1_6/CheatSheet.md deleted file mode 100644 index 91de1d21..00000000 --- a/googlemock/docs/v1_6/CheatSheet.md +++ /dev/null @@ -1,534 +0,0 @@ - - -# Defining a Mock Class # - -## Mocking a Normal Class ## - -Given -``` -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` -(note that `~Foo()` **must** be virtual) we can define its mock as -``` -#include "gmock/gmock.h" - -class MockFoo : public Foo { - MOCK_CONST_METHOD0(GetSize, int()); - MOCK_METHOD1(Describe, string(const char* name)); - MOCK_METHOD1(Describe, string(int type)); - MOCK_METHOD2(Process, bool(Bar elem, int count)); -}; -``` - -To create a "nice" mock object which ignores all uninteresting calls, -or a "strict" mock object, which treats them as failures: -``` -NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. -StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. -``` - -## Mocking a Class Template ## - -To mock -``` -template <typename Elem> -class StackInterface { - public: - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` -(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -``` -template <typename Elem> -class MockStack : public StackInterface<Elem> { - public: - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Specifying Calling Conventions for Mock Functions ## - -If your mock function doesn't use the default calling convention, you -can specify it by appending `_WITH_CALLTYPE` to any of the macros -described in the previous two sections and supplying the calling -convention as the first argument to the macro. For example, -``` - MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); - MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); -``` -where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. - -# Using Mocks in Tests # - -The typical flow is: - 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. - 1. Create the mock objects. - 1. Optionally, set the default actions of the mock objects. - 1. Set your expectations on the mock objects (How will they be called? What wil they do?). - 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. - 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. - -Here is an example: -``` -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -# Setting Default Actions # - -Google Mock has a **built-in default action** for any function that -returns `void`, `bool`, a numeric value, or a pointer. - -To customize the default action for functions with return type `T` globally: -``` -using ::testing::DefaultValue; - -DefaultValue<T>::Set(value); // Sets the default value to be returned. -// ... use the mocks ... -DefaultValue<T>::Clear(); // Resets the default value. -``` - -To customize the default action for a particular method, use `ON_CALL()`: -``` -ON_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .WillByDefault(action); -``` - -# Setting Expectations # - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be -called? What will it do?): -``` -EXPECT_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -If `Times()` is omitted, the cardinality is assumed to be: - - * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; - * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or - * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. - -# Matchers # - -A **matcher** matches a _single_ argument. You can use it inside -`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value -directly: - -| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -|:------------------------------|:----------------------------------------| -| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | - -Built-in matchers (where `argument` is the function argument) are -divided into several categories: - -## Wildcard ## -|`_`|`argument` can be any value of the correct type.| -|:--|:-----------------------------------------------| -|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | - -## Generic Comparison ## - -|`Eq(value)` or `value`|`argument == value`| -|:---------------------|:------------------| -|`Ge(value)` |`argument >= value`| -|`Gt(value)` |`argument > value` | -|`Le(value)` |`argument <= value`| -|`Lt(value)` |`argument < value` | -|`Ne(value)` |`argument != value`| -|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| -|`NotNull()` |`argument` is a non-null pointer (raw or smart).| -|`Ref(variable)` |`argument` is a reference to `variable`.| -|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| - -Except `Ref()`, these matchers make a _copy_ of `value` in case it's -modified or destructed later. If the compiler complains that `value` -doesn't have a public copy constructor, try wrap it in `ByRef()`, -e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure -`non_copyable_value` is not changed afterwards, or the meaning of your -matcher will be changed. - -## Floating-Point Matchers ## - -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| -|:-------------------|:----------------------------------------------------------------------------------------------| -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | - -These matchers use ULP-based comparison (the same as used in -[Google Test](http://code.google.com/p/googletest/)). They -automatically pick a reasonable error bound based on the absolute -value of the expected value. `DoubleEq()` and `FloatEq()` conform to -the IEEE standard, which requires comparing two NaNs for equality to -return false. The `NanSensitive*` version instead treats two NaNs as -equal, which is often what a user wants. - -## String Matchers ## - -The `argument` can be either a C string or a C++ string object: - -|`ContainsRegex(string)`|`argument` matches the given regular expression.| -|:----------------------|:-----------------------------------------------| -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | -|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | -|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | - -`ContainsRegex()` and `MatchesRegex()` use the regular expression -syntax defined -[here](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Regular_Expression_Syntax). -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide -strings as well. - -## Container Matchers ## - -Most STL-style containers support `==`, so you can use -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. If you want to write the elements in-line, -match them more flexibly, or get more informative messages, you can use: - -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -|:--------------|:-------------------------------------------------------------------------------------------| -| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | -| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `ElementsAreArray(array)` or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from a C-style array. | -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | -| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. | - -These matchers can also match: - - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). - -where the array may be multi-dimensional (i.e. its elements can be arrays). - -## Member Matchers ## - -|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| -|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | -|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| - -## Matching the Result of a Function or Functor ## - -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| -|:---------------|:---------------------------------------------------------------------| - -## Pointer Matchers ## - -|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|:-----------|:-----------------------------------------------------------------------------------------------| - -## Multiargument Matchers ## - -Technically, all matchers match a _single_ value. A "multi-argument" -matcher is just one that matches a _tuple_. The following matchers can -be used to match a tuple `(x, y)`: - -|`Eq()`|`x == y`| -|:-----|:-------| -|`Ge()`|`x >= y`| -|`Gt()`|`x > y` | -|`Le()`|`x <= y`| -|`Lt()`|`x < y` | -|`Ne()`|`x != y`| - -You can use the following selectors to pick a subset of the arguments -(or reorder them) to participate in the matching: - -|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|:-----------|:-------------------------------------------------------------------| -|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| - -## Composite Matchers ## - -You can make a matcher from one or more other matchers: - -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| -|:-----------------------|:---------------------------------------------------| -|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | - -## Adapters for Matchers ## - -|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| -|:------------------|:--------------------------------------| -|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. | -|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| - -## Matchers as Predicates ## - -|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| -|:------------------|:---------------------------------------------------------------------------------------------| -|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | -|`Value(value, m)` |evaluates to `true` if `value` matches `m`. | - -## Defining Matchers ## - -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -|:-------------------------------------------------|:------------------------------------------------------| -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - -**Notes:** - - 1. The `MATCHER*` macros cannot be used inside a function or class. - 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). - 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. - -## Matchers as Test Assertions ## - -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/V1_6_Primer#Assertions) if the value of `expression` doesn't match matcher `m`.| -|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | - -# Actions # - -**Actions** specify what a mock function should do when invoked. - -## Returning a Value ## - -|`Return()`|Return from a `void` mock function.| -|:---------|:----------------------------------| -|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| -|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| -|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer. | -|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| -|`ReturnRef(variable)`|Return a reference to `variable`. | -|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| - -## Side Effects ## - -|`Assign(&variable, value)`|Assign `value` to variable.| -|:-------------------------|:--------------------------| -| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| -|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| -|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| -|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| - -## Using a Function or a Functor as an Action ## - -|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|:----------|:-----------------------------------------------------------------------------------------------------------------| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | -|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| - -The return value of the invoked function is used as the return value -of the action. - -When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -``` - double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } - ... - EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -``` - InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. - -## Default Action ## - -|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| -|:------------|:--------------------------------------------------------------------| - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. - -## Composite Actions ## - -|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | - -## Defining Actions ## - -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -|:--------------------------------------|:---------------------------------------------------------------------------------------| -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - -The `ACTION*` macros cannot be used inside a function or class. - -# Cardinalities # - -These are used in `Times()` to specify how many times a mock function will be called: - -|`AnyNumber()`|The function can be called any number of times.| -|:------------|:----------------------------------------------| -|`AtLeast(n)` |The call is expected at least `n` times. | -|`AtMost(n)` |The call is expected at most `n` times. | -|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| -|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| - -# Expectation Order # - -By default, the expectations can be matched in _any_ order. If some -or all expectations must be matched in a given order, there are two -ways to specify it. They can be used either independently or -together. - -## The After Clause ## - -``` -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` -says that `Bar()` can be called only after both `InitX()` and -`InitY()` have been called. - -If you don't know how many pre-requisites an expectation has when you -write it, you can use an `ExpectationSet` to collect them: - -``` -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` -says that `Bar()` can be called only after all elements have been -initialized (but we don't care about which elements get initialized -before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't -affect the meaning of the `.After()`. - -## Sequences ## - -When you have a long chain of sequential expectations, it's easier to -specify the order using **sequences**, which don't require you to given -each expectation in the chain a different name. <i>All expected<br> -calls</i> in the same sequence must occur in the order they are -specified. - -``` -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A<const char*>())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` -says that `Reset()` must be called before _both_ `GetSize()` _and_ -`Describe()`, and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: -``` -using ::testing::InSequence; -{ - InSequence dummy; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` -says that all expected calls in the scope of `dummy` must occur in -strict order. The name `dummy` is irrelevant.) - -# Verifying and Resetting a Mock # - -Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -``` -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true iff successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true iff successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell Google Mock that a mock object can be leaked and doesn't -need to be verified: -``` -Mock::AllowLeak(&mock_obj); -``` - -# Mock Classes # - -Google Mock defines a convenient mock class template -``` -class MockFunction<R(A1, ..., An)> { - public: - MOCK_METHODn(Call, R(A1, ..., An)); -}; -``` -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Check_Points) for one application of it. - -# Flags # - -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -|:-------------------------------|:----------------------------------------------| -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | \ No newline at end of file diff --git a/googlemock/docs/v1_6/CookBook.md b/googlemock/docs/v1_6/CookBook.md deleted file mode 100644 index f5975a00..00000000 --- a/googlemock/docs/v1_6/CookBook.md +++ /dev/null @@ -1,3342 +0,0 @@ - - -You can find recipes for using Google Mock here. If you haven't yet, -please read the [ForDummies](V1_6_ForDummies.md) document first to make sure you understand -the basics. - -**Note:** Google Mock lives in the `testing` name space. For -readability, it is recommended to write `using ::testing::Foo;` once in -your file before using the name `Foo` defined by Google Mock. We omit -such `using` statements in this page for brevity, but you should do it -in your own code. - -# Creating Mock Classes # - -## Mocking Private or Protected Methods ## - -You must always put a mock method definition (`MOCK_METHOD*`) in a -`public:` section of the mock class, regardless of the method being -mocked being `public`, `protected`, or `private` in the base class. -This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: - -``` -class Foo { - public: - ... - virtual bool Transform(Gadget* g) = 0; - - protected: - virtual void Resume(); - - private: - virtual int GetTimeOut(); -}; - -class MockFoo : public Foo { - public: - ... - MOCK_METHOD1(Transform, bool(Gadget* g)); - - // The following must be in the public section, even though the - // methods are protected or private in the base class. - MOCK_METHOD0(Resume, void()); - MOCK_METHOD0(GetTimeOut, int()); -}; -``` - -## Mocking Overloaded Methods ## - -You can mock overloaded functions as usual. No special attention is required: - -``` -class Foo { - ... - - // Must be virtual as we'll inherit from Foo. - virtual ~Foo(); - - // Overloaded on the types and/or numbers of arguments. - virtual int Add(Element x); - virtual int Add(int times, Element x); - - // Overloaded on the const-ness of this object. - virtual Bar& GetBar(); - virtual const Bar& GetBar() const; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Add, int(Element x)); - MOCK_METHOD2(Add, int(int times, Element x); - - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -``` - -**Note:** if you don't mock all versions of the overloaded method, the -compiler will give you a warning about some methods in the base class -being hidden. To fix that, use `using` to bring them in scope: - -``` -class MockFoo : public Foo { - ... - using Foo::Add; - MOCK_METHOD1(Add, int(Element x)); - // We don't want to mock int Add(int times, Element x); - ... -}; -``` - -## Mocking Class Templates ## - -To mock a class template, append `_T` to the `MOCK_*` macros: - -``` -template <typename Elem> -class StackInterface { - ... - // Must be virtual as we'll inherit from StackInterface. - virtual ~StackInterface(); - - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; - -template <typename Elem> -class MockStack : public StackInterface<Elem> { - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Mocking Nonvirtual Methods ## - -Google Mock can mock non-virtual functions to be used in what we call _hi-perf -dependency injection_. - -In this case, instead of sharing a common base class with the real -class, your mock class will be _unrelated_ to the real class, but -contain methods with the same signatures. The syntax for mocking -non-virtual methods is the _same_ as mocking virtual methods: - -``` -// A simple packet stream class. None of its members is virtual. -class ConcretePacketStream { - public: - void AppendPacket(Packet* new_packet); - const Packet* GetPacket(size_t packet_number) const; - size_t NumberOfPackets() const; - ... -}; - -// A mock packet stream class. It inherits from no other, but defines -// GetPacket() and NumberOfPackets(). -class MockPacketStream { - public: - MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); - MOCK_CONST_METHOD0(NumberOfPackets, size_t()); - ... -}; -``` - -Note that the mock class doesn't define `AppendPacket()`, unlike the -real class. That's fine as long as the test doesn't need to call it. - -Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` -in tests. Since the functions are not virtual and the two classes are -unrelated, you must specify your choice at _compile time_ (as opposed -to run time). - -One way to do it is to templatize your code that needs to use a packet -stream. More specifically, you will give your code a template type -argument for the type of the packet stream. In production, you will -instantiate your template with `ConcretePacketStream` as the type -argument. In tests, you will instantiate the same template with -`MockPacketStream`. For example, you may write: - -``` -template <class PacketStream> -void CreateConnection(PacketStream* stream) { ... } - -template <class PacketStream> -class PacketReader { - public: - void ReadPackets(PacketStream* stream, size_t packet_num); -}; -``` - -Then you can use `CreateConnection<ConcretePacketStream>()` and -`PacketReader<ConcretePacketStream>` in production code, and use -`CreateConnection<MockPacketStream>()` and -`PacketReader<MockPacketStream>` in tests. - -``` - MockPacketStream mock_stream; - EXPECT_CALL(mock_stream, ...)...; - .. set more expectations on mock_stream ... - PacketReader<MockPacketStream> reader(&mock_stream); - ... exercise reader ... -``` - -## Mocking Free Functions ## - -It's possible to use Google Mock to mock a free function (i.e. a -C-style function or a static method). You just need to rewrite your -code to use an interface (abstract class). - -Instead of calling a free function (say, `OpenFile`) directly, -introduce an interface for it and have a concrete subclass that calls -the free function: - -``` -class FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) = 0; -}; - -class File : public FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) { - return OpenFile(path, mode); - } -}; -``` - -Your code should talk to `FileInterface` to open a file. Now it's -easy to mock out the function. - -This may seem much hassle, but in practice you often have multiple -related functions that you can put in the same interface, so the -per-function syntactic overhead will be much lower. - -If you are concerned about the performance overhead incurred by -virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md). - -## Nice Mocks and Strict Mocks ## - -If a mock method has no `EXPECT_CALL` spec but is called, Google Mock -will print a warning about the "uninteresting call". The rationale is: - - * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. - -However, sometimes you may want to suppress all "uninteresting call" -warnings, while sometimes you may want the opposite, i.e. to treat all -of them as errors. Google Mock lets you make the decision on a -per-mock-object basis. - -Suppose your test uses a mock class `MockFoo`: - -``` -TEST(...) { - MockFoo mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -If a method of `mock_foo` other than `DoThis()` is called, it will be -reported by Google Mock as a warning. However, if you rewrite your -test to use `NiceMock<MockFoo>` instead, the warning will be gone, -resulting in a cleaner test output: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used -wherever `MockFoo` is accepted. - -It also works if `MockFoo`'s constructor takes some arguments, as -`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -The usage of `StrictMock` is similar, except that it makes all -uninteresting calls failures: - -``` -using ::testing::StrictMock; - -TEST(...) { - StrictMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... - - // The test will fail if a method of mock_foo other than DoThis() - // is called. -} -``` - -There are some caveats though (I don't like them just as much as the -next guy, but sadly they are side effects of C++'s limitations): - - 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). - 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) - -Finally, you should be **very cautious** when using this feature, as the -decision you make applies to **all** future changes to the mock -class. If an important change is made in the interface you are mocking -(and thus in the mock class), it could break your tests (if you use -`StrictMock`) or let bugs pass through without a warning (if you use -`NiceMock`). Therefore, try to specify the mock's behavior using -explicit `EXPECT_CALL` first, and only turn to `NiceMock` or -`StrictMock` as the last resort. - -## Simplifying the Interface without Breaking Existing Code ## - -Sometimes a method has a long list of arguments that is mostly -uninteresting. For example, - -``` -class LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) = 0; -}; -``` - -This method's argument list is lengthy and hard to work with (let's -say that the `message` argument is not even 0-terminated). If we mock -it as is, using the mock will be awkward. If, however, we try to -simplify this interface, we'll need to fix all clients depending on -it, which is often infeasible. - -The trick is to re-dispatch the method in the mock class: - -``` -class ScopedMockLog : public LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - Log(severity, full_filename, std::string(message, message_len)); - } - - // Implements the mock method: - // - // void Log(LogSeverity severity, - // const string& file_path, - // const string& message); - MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, - const string& message)); -}; -``` - -By defining a new mock method with a trimmed argument list, we make -the mock class much more user-friendly. - -## Alternative to Mocking Concrete Classes ## - -Often you may find yourself using classes that don't implement -interfaces. In order to test your code that uses such a class (let's -call it `Concrete`), you may be tempted to make the methods of -`Concrete` virtual and then mock it. - -Try not to do that. - -Making a non-virtual function virtual is a big decision. It creates an -extension point where subclasses can tweak your class' behavior. This -weakens your control on the class because now it's harder to maintain -the class' invariants. You should make a function virtual only when -there is a valid reason for a subclass to override it. - -Mocking concrete classes directly is problematic as it creates a tight -coupling between the class and the tests - any small change in the -class may invalidate your tests and make test maintenance a pain. - -To avoid such problems, many programmers have been practicing "coding -to interfaces": instead of talking to the `Concrete` class, your code -would define an interface and talk to it. Then you implement that -interface as an adaptor on top of `Concrete`. In tests, you can easily -mock that interface to observe how your code is doing. - -This technique incurs some overhead: - - * You pay the cost of virtual function calls (usually not a problem). - * There is more abstraction for the programmers to learn. - -However, it can also bring significant benefits in addition to better -testability: - - * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. - * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. - -Some people worry that if everyone is practicing this technique, they -will end up writing lots of redundant code. This concern is totally -understandable. However, there are two reasons why it may not be the -case: - - * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. - * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. - -You need to weigh the pros and cons carefully for your particular -problem, but I'd like to assure you that the Java community has been -practicing this for a long time and it's a proven effective technique -applicable in a wide variety of situations. :-) - -## Delegating Calls to a Fake ## - -Some times you have a non-trivial fake implementation of an -interface. For example: - -``` -class Foo { - public: - virtual ~Foo() {} - virtual char DoThis(int n) = 0; - virtual void DoThat(const char* s, int* p) = 0; -}; - -class FakeFoo : public Foo { - public: - virtual char DoThis(int n) { - return (n > 0) ? '+' : - (n < 0) ? '-' : '0'; - } - - virtual void DoThat(const char* s, int* p) { - *p = strlen(s); - } -}; -``` - -Now you want to mock this interface such that you can set expectations -on it. However, you also want to use `FakeFoo` for the default -behavior, as duplicating it in the mock object is, well, a lot of -work. - -When you define the mock class using Google Mock, you can have it -delegate its default action to a fake class you already have, using -this pattern: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - // Normal mock method definitions using Google Mock. - MOCK_METHOD1(DoThis, char(int n)); - MOCK_METHOD2(DoThat, void(const char* s, int* p)); - - // Delegates the default actions of the methods to a FakeFoo object. - // This must be called *before* the custom ON_CALL() statements. - void DelegateToFake() { - ON_CALL(*this, DoThis(_)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); - ON_CALL(*this, DoThat(_, _)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); - } - private: - FakeFoo fake_; // Keeps an instance of the fake in the mock. -}; -``` - -With that, you can use `MockFoo` in your tests as usual. Just remember -that if you don't explicitly set an action in an `ON_CALL()` or -`EXPECT_CALL()`, the fake will be called upon to do it: - -``` -using ::testing::_; - -TEST(AbcTest, Xyz) { - MockFoo foo; - foo.DelegateToFake(); // Enables the fake for delegation. - - // Put your ON_CALL(foo, ...)s here, if any. - - // No action specified, meaning to use the default action. - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(foo, DoThat(_, _)); - - int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. - foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); -} -``` - -**Some tips:** - - * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. - * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. - * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. - * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. - -Regarding the tip on mixing a mock and a fake, here's an example on -why it may be a bad sign: Suppose you have a class `System` for -low-level system operations. In particular, it does file and I/O -operations. And suppose you want to test how your code uses `System` -to do I/O, and you just want the file operations to work normally. If -you mock out the entire `System` class, you'll have to provide a fake -implementation for the file operation part, which suggests that -`System` is taking on too many roles. - -Instead, you can define a `FileOps` interface and an `IOOps` interface -and split `System`'s functionalities into the two. Then you can mock -`IOOps` without mocking `FileOps`. - -## Delegating Calls to a Real Object ## - -When using testing doubles (mocks, fakes, stubs, and etc), sometimes -their behaviors will differ from those of the real objects. This -difference could be either intentional (as in simulating an error such -that you can test the error handling code) or unintentional. If your -mocks have different behaviors than the real objects by mistake, you -could end up with code that passes the tests but fails in production. - -You can use the _delegating-to-real_ technique to ensure that your -mock has the same behavior as the real object while retaining the -ability to validate calls. This technique is very similar to the -delegating-to-fake technique, the difference being that we use a real -object instead of a fake. Here's an example: - -``` -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MockFoo() { - // By default, all calls are delegated to the real object. - ON_CALL(*this, DoThis()) - .WillByDefault(Invoke(&real_, &Foo::DoThis)); - ON_CALL(*this, DoThat(_)) - .WillByDefault(Invoke(&real_, &Foo::DoThat)); - ... - } - MOCK_METHOD0(DoThis, ...); - MOCK_METHOD1(DoThat, ...); - ... - private: - Foo real_; -}; -... - - MockFoo mock; - - EXPECT_CALL(mock, DoThis()) - .Times(3); - EXPECT_CALL(mock, DoThat("Hi")) - .Times(AtLeast(1)); - ... use mock in test ... -``` - -With this, Google Mock will verify that your code made the right calls -(with the right arguments, in the right order, called the right number -of times, etc), and a real object will answer the calls (so the -behavior will be the same as in production). This gives you the best -of both worlds. - -## Delegating Calls to a Parent Class ## - -Ideally, you should code to interfaces, whose methods are all pure -virtual. In reality, sometimes you do need to mock a virtual method -that is not pure (i.e, it already has an implementation). For example: - -``` -class Foo { - public: - virtual ~Foo(); - - virtual void Pure(int n) = 0; - virtual int Concrete(const char* str) { ... } -}; - -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); -}; -``` - -Sometimes you may want to call `Foo::Concrete()` instead of -`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub -action, or perhaps your test doesn't need to mock `Concrete()` at all -(but it would be oh-so painful to have to define a new mock class -whenever you don't need to mock one of its methods). - -The trick is to leave a back door in your mock class for accessing the -real methods in the base class: - -``` -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: - -``` -using ::testing::_; -using ::testing::Invoke; -... - EXPECT_CALL(foo, Concrete(_)) - .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -or tell the mock object that you don't want to mock `Concrete()`: - -``` -using ::testing::Invoke; -... - ON_CALL(foo, Concrete(_)) - .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do -that, `MockFoo::Concrete()` will be called (and cause an infinite -recursion) since `Foo::Concrete()` is virtual. That's just how C++ -works.) - -# Using Matchers # - -## Matching Argument Values Exactly ## - -You can specify exactly which arguments a mock method is expecting: - -``` -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(5)) - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", bar)); -``` - -## Using Simple Matchers ## - -You can use matchers to match arguments that have a certain property: - -``` -using ::testing::Ge; -using ::testing::NotNull; -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", NotNull())); - // The second argument must not be NULL. -``` - -A frequently used matcher is `_`, which matches anything: - -``` -using ::testing::_; -using ::testing::NotNull; -... - EXPECT_CALL(foo, DoThat(_, NotNull())); -``` - -## Combining Matchers ## - -You can build complex matchers from existing ones using `AllOf()`, -`AnyOf()`, and `Not()`: - -``` -using ::testing::AllOf; -using ::testing::Gt; -using ::testing::HasSubstr; -using ::testing::Ne; -using ::testing::Not; -... - // The argument must be > 5 and != 10. - EXPECT_CALL(foo, DoThis(AllOf(Gt(5), - Ne(10)))); - - // The first argument must not contain sub-string "blah". - EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), - NULL)); -``` - -## Casting Matchers ## - -Google Mock matchers are statically typed, meaning that the compiler -can catch your mistake if you use a matcher of the wrong type (for -example, if you use `Eq(5)` to match a `string` argument). Good for -you! - -Sometimes, however, you know what you're doing and want the compiler -to give you some slack. One example is that you have a matcher for -`long` and the argument you want to match is `int`. While the two -types aren't exactly the same, there is nothing really wrong with -using a `Matcher<long>` to match an `int` - after all, we can first -convert the `int` argument to a `long` before giving it to the -matcher. - -To support this need, Google Mock gives you the -`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type -`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the -type `m` accepts): - - 1. Type `T` can be implicitly cast to type `U`; - 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and - 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). - -The code won't compile if any of these conditions isn't met. - -Here's one example: - -``` -using ::testing::SafeMatcherCast; - -// A base class and a child class. -class Base { ... }; -class Derived : public Base { ... }; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(DoThis, void(Derived* derived)); -}; -... - - MockFoo foo; - // m is a Matcher<Base*> we got from somewhere. - EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); -``` - -If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar -function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works -as long as you can `static_cast` type `T` to type `U`. - -`MatcherCast` essentially lets you bypass C++'s type system -(`static_cast` isn't always safe as it could throw away information, -for example), so be careful not to misuse/abuse it. - -## Selecting Between Overloaded Functions ## - -If you expect an overloaded function to be called, the compiler may -need some help on which overloaded version it is. - -To disambiguate functions overloaded on the const-ness of this object, -use the `Const()` argument wrapper. - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - ... - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -... - - MockFoo foo; - Bar bar1, bar2; - EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). - .WillOnce(ReturnRef(bar1)); - EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). - .WillOnce(ReturnRef(bar2)); -``` - -(`Const()` is defined by Google Mock and returns a `const` reference -to its argument.) - -To disambiguate overloaded functions with the same number of arguments -but different argument types, you may need to specify the exact type -of a matcher, either by wrapping your matcher in `Matcher<type>()`, or -using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, -etc): - -``` -using ::testing::An; -using ::testing::Lt; -using ::testing::Matcher; -using ::testing::TypedEq; - -class MockPrinter : public Printer { - public: - MOCK_METHOD1(Print, void(int n)); - MOCK_METHOD1(Print, void(char c)); -}; - -TEST(PrinterTest, Print) { - MockPrinter printer; - - EXPECT_CALL(printer, Print(An<int>())); // void Print(int); - EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); - EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); - - printer.Print(3); - printer.Print(6); - printer.Print('a'); -} -``` - -## Performing Different Actions Based on the Arguments ## - -When a mock method is called, the _last_ matching expectation that's -still active will be selected (think "newer overrides older"). So, you -can make a method do different things depending on its argument values -like this: - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Return; -... - // The default case. - EXPECT_CALL(foo, DoThis(_)) - .WillRepeatedly(Return('b')); - - // The more specific case. - EXPECT_CALL(foo, DoThis(Lt(5))) - .WillRepeatedly(Return('a')); -``` - -Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will -be returned; otherwise `'b'` will be returned. - -## Matching Multiple Arguments as a Whole ## - -Sometimes it's not enough to match the arguments individually. For -example, we may want to say that the first argument must be less than -the second argument. The `With()` clause allows us to match -all arguments of a mock function as a whole. For example, - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Ne; -... - EXPECT_CALL(foo, InRange(Ne(0), _)) - .With(Lt()); -``` - -says that the first argument of `InRange()` must not be 0, and must be -less than the second argument. - -The expression inside `With()` must be a matcher of type -`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the -types of the function arguments. - -You can also write `AllArgs(m)` instead of `m` inside `.With()`. The -two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable -than `.With(Lt())`. - -You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments -(as a tuple) against `m`. For example, - -``` -using ::testing::_; -using ::testing::AllOf; -using ::testing::Args; -using ::testing::Lt; -... - EXPECT_CALL(foo, Blah(_, _, _)) - .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); -``` - -says that `Blah()` will be called with arguments `x`, `y`, and `z` where -`x < y < z`. - -As a convenience and example, Google Mock provides some matchers for -2-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_6_CheatSheet.md) for -the complete list. - -Note that if you want to pass the arguments to a predicate of your own -(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be -written to take a `tr1::tuple` as its argument; Google Mock will pass the `n` -selected arguments as _one_ single tuple to the predicate. - -## Using Matchers as Predicates ## - -Have you noticed that a matcher is just a fancy predicate that also -knows how to describe itself? Many existing algorithms take predicates -as arguments (e.g. those defined in STL's `<algorithm>` header), and -it would be a shame if Google Mock matchers are not allowed to -participate. - -Luckily, you can use a matcher where a unary predicate functor is -expected by wrapping it inside the `Matches()` function. For example, - -``` -#include <algorithm> -#include <vector> - -std::vector<int> v; -... -// How many elements in v are >= 10? -const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); -``` - -Since you can build complex matchers from simpler ones easily using -Google Mock, this gives you a way to conveniently construct composite -predicates (doing the same using STL's `<functional>` header is just -painful). For example, here's a predicate that's satisfied by any -number that is >= 0, <= 100, and != 50: - -``` -Matches(AllOf(Ge(0), Le(100), Ne(50))) -``` - -## Using Matchers in Google Test Assertions ## - -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in -[Google Test](http://code.google.com/p/googletest/) assertions. It's -called `ASSERT_THAT` and `EXPECT_THAT`: - -``` - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a Google Test test you can write: - -``` -#include "gmock/gmock.h" - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; -... - - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and -`Baz()`, and verifies that: - - * `Foo()` returns a string that starts with `"Hello"`. - * `Bar()` returns a string that matches regular expression `"Line \\d+"`. - * `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that _they read like -English_. They generate informative messages too. For example, if the -first `EXPECT_THAT()` above fails, the message will be something like: - -``` -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the -[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds -`assertThat()` to JUnit. - -## Using Predicates as Matchers ## - -Google Mock provides a built-in set of matchers. In case you find them -lacking, you can use an arbitray unary predicate function or functor -as a matcher - as long as the predicate accepts a value of the type -you want. You do this by wrapping the predicate inside the `Truly()` -function, for example: - -``` -using ::testing::Truly; - -int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } -... - - // Bar() must be called with an even number. - EXPECT_CALL(foo, Bar(Truly(IsEven))); -``` - -Note that the predicate function / functor doesn't have to return -`bool`. It works as long as the return value can be used as the -condition in statement `if (condition) ...`. - -## Matching Arguments that Are Not Copyable ## - -When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves -away a copy of `bar`. When `Foo()` is called later, Google Mock -compares the argument to `Foo()` with the saved copy of `bar`. This -way, you don't need to worry about `bar` being modified or destroyed -after the `EXPECT_CALL()` is executed. The same is true when you use -matchers like `Eq(bar)`, `Le(bar)`, and so on. - -But what if `bar` cannot be copied (i.e. has no copy constructor)? You -could define your own matcher function and use it with `Truly()`, as -the previous couple of recipes have shown. Or, you may be able to get -away from it if you can guarantee that `bar` won't be changed after -the `EXPECT_CALL()` is executed. Just tell Google Mock that it should -save a reference to `bar`, instead of a copy of it. Here's how: - -``` -using ::testing::Eq; -using ::testing::ByRef; -using ::testing::Lt; -... - // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); - - // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); -``` - -Remember: if you do this, don't change `bar` after the -`EXPECT_CALL()`, or the result is undefined. - -## Validating a Member of an Object ## - -Often a mock function takes a reference to object as an argument. When -matching the argument, you may not want to compare the entire object -against a fixed object, as that may be over-specification. Instead, -you may need to validate a certain member variable or the result of a -certain getter method of the object. You can do this with `Field()` -and `Property()`. More specifically, - -``` -Field(&Foo::bar, m) -``` - -is a matcher that matches a `Foo` object whose `bar` member variable -satisfies matcher `m`. - -``` -Property(&Foo::baz, m) -``` - -is a matcher that matches a `Foo` object whose `baz()` method returns -a value that satisfies matcher `m`. - -For example: - -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | -|:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - -Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no -argument and be declared as `const`. - -BTW, `Field()` and `Property()` can also match plain pointers to -objects. For instance, - -``` -Field(&Foo::number, Ge(3)) -``` - -matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, -the match will always fail regardless of the inner matcher. - -What if you want to validate more than one members at the same time? -Remember that there is `AllOf()`. - -## Validating the Value Pointed to by a Pointer Argument ## - -C++ functions often take pointers as arguments. You can use matchers -like `NULL`, `NotNull()`, and other comparison matchers to match a -pointer, but what if you want to make sure the value _pointed to_ by -the pointer, instead of the pointer itself, has a certain property? -Well, you can use the `Pointee(m)` matcher. - -`Pointee(m)` matches a pointer iff `m` matches the value the pointer -points to. For example: - -``` -using ::testing::Ge; -using ::testing::Pointee; -... - EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); -``` - -expects `foo.Bar()` to be called with a pointer that points to a value -greater than or equal to 3. - -One nice thing about `Pointee()` is that it treats a `NULL` pointer as -a match failure, so you can write `Pointee(m)` instead of - -``` - AllOf(NotNull(), Pointee(m)) -``` - -without worrying that a `NULL` pointer will crash your test. - -Also, did we tell you that `Pointee()` works with both raw pointers -**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and -etc)? - -What if you have a pointer to pointer? You guessed it - you can use -nested `Pointee()` to probe deeper inside the value. For example, -`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer -that points to a number less than 3 (what a mouthful...). - -## Testing a Certain Property of an Object ## - -Sometimes you want to specify that an object argument has a certain -property, but there is no existing matcher that does this. If you want -good error messages, you should define a matcher. If you want to do it -quick and dirty, you could get away with writing an ordinary function. - -Let's say you have a mock function that takes an object of type `Foo`, -which has an `int bar()` method and an `int baz()` method, and you -want to constrain that the argument's `bar()` value plus its `baz()` -value is a given number. Here's how you can define a matcher to do it: - -``` -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> { - public: - explicit BarPlusBazEqMatcher(int expected_sum) - : expected_sum_(expected_sum) {} - - virtual bool MatchAndExplain(const Foo& foo, - MatchResultListener* listener) const { - return (foo.bar() + foo.baz()) == expected_sum_; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "bar() + baz() equals " << expected_sum_; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "bar() + baz() does not equal " << expected_sum_; - } - private: - const int expected_sum_; -}; - -inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); -} - -... - - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; -``` - -## Matching Containers ## - -Sometimes an STL container (e.g. list, vector, map, ...) is passed to -a mock function and you may want to validate it. Since most STL -containers support the `==` operator, you can write -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. - -Sometimes, though, you may want to be more flexible (for example, the -first element must be an exact match, but the second element can be -any positive number, and so on). Also, containers used in tests often -have a small number of elements, and having to define the expected -container out-of-line is a bit of a hassle. - -You can use the `ElementsAre()` matcher in such cases: - -``` -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::Gt; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); -``` - -The above matcher says that the container must have 4 elements, which -must be 1, greater than 0, anything, and 5 respectively. - -`ElementsAre()` is overloaded to take 0 to 10 arguments. If more are -needed, you can place them in a C-style array and use -`ElementsAreArray()` instead: - -``` -using ::testing::ElementsAreArray; -... - - // ElementsAreArray accepts an array of element values. - const int expected_vector1[] = { 1, 5, 2, 4, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); - - // Or, an array of element matchers. - Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); -``` - -In case the array needs to be dynamically created (and therefore the -array size cannot be inferred by the compiler), you can give -`ElementsAreArray()` an additional argument to specify the array size: - -``` -using ::testing::ElementsAreArray; -... - int* const expected_vector3 = new int[count]; - ... fill expected_vector3 with values ... - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); -``` - -**Tips:** - - * `ElementAre*()` works with _any_ container that implements the STL iterator concept (i.e. it has a `const_iterator` type and supports `begin()/end()`) and supports `size()`, not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. - * You can use nested `ElementAre*()` to match nested (multi-dimensional) containers. - * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. - * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). - -## Sharing Matchers ## - -Under the hood, a Google Mock matcher object consists of a pointer to -a ref-counted implementation object. Copying matchers is allowed and -very efficient, as only the pointer is copied. When the last matcher -that references the implementation object dies, the implementation -object will be deleted. - -Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a -matcher variable and use that variable repeatedly! For example, - -``` - Matcher<int> in_range = AllOf(Gt(5), Le(10)); - ... use in_range as a matcher in multiple EXPECT_CALLs ... -``` - -# Setting Expectations # - -## Ignoring Uninteresting Calls ## - -If you are not interested in how a mock method is called, just don't -say anything about it. In this case, if the method is ever called, -Google Mock will perform its default action to allow the test program -to continue. If you are not happy with the default action taken by -Google Mock, you can override it using `DefaultValue<T>::Set()` -(described later in this document) or `ON_CALL()`. - -Please note that once you expressed interest in a particular mock -method (via `EXPECT_CALL()`), all invocations to it must match some -expectation. If this function is called but the arguments don't match -any `EXPECT_CALL()` statement, it will be an error. - -## Disallowing Unexpected Calls ## - -If a mock method shouldn't be called at all, explicitly say so: - -``` -using ::testing::_; -... - EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -If some calls to the method are allowed, but the rest are not, just -list all the expected calls: - -``` -using ::testing::AnyNumber; -using ::testing::Gt; -... - EXPECT_CALL(foo, Bar(5)); - EXPECT_CALL(foo, Bar(Gt(10))) - .Times(AnyNumber()); -``` - -A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` -statements will be an error. - -## Expecting Ordered Calls ## - -Although an `EXPECT_CALL()` statement defined earlier takes precedence -when Google Mock tries to match a function call with an expectation, -by default calls don't have to happen in the order `EXPECT_CALL()` -statements are written. For example, if the arguments match the -matchers in the third `EXPECT_CALL()`, but not those in the first two, -then the third expectation will be used. - -If you would rather have all calls occur in the order of the -expectations, put the `EXPECT_CALL()` statements in a block where you -define a variable of type `InSequence`: - -``` - using ::testing::_; - using ::testing::InSequence; - - { - InSequence s; - - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(bar, DoThat(_)) - .Times(2); - EXPECT_CALL(foo, DoThis(6)); - } -``` - -In this example, we expect a call to `foo.DoThis(5)`, followed by two -calls to `bar.DoThat()` where the argument can be anything, which are -in turn followed by a call to `foo.DoThis(6)`. If a call occurred -out-of-order, Google Mock will report an error. - -## Expecting Partially Ordered Calls ## - -Sometimes requiring everything to occur in a predetermined order can -lead to brittle tests. For example, we may care about `A` occurring -before both `B` and `C`, but aren't interested in the relative order -of `B` and `C`. In this case, the test should reflect our real intent, -instead of being overly constraining. - -Google Mock allows you to impose an arbitrary DAG (directed acyclic -graph) on the calls. One way to express the DAG is to use the -[After](http://code.google.com/p/googlemock/wiki/V1_6_CheatSheet#The_After_Clause) clause of `EXPECT_CALL`. - -Another way is via the `InSequence()` clause (not the same as the -`InSequence` class), which we borrowed from jMock 2. It's less -flexible than `After()`, but more convenient when you have long chains -of sequential calls, as it doesn't require you to come up with -different names for the expectations in the chains. Here's how it -works: - -If we view `EXPECT_CALL()` statements as nodes in a graph, and add an -edge from node A to node B wherever A must occur before B, we can get -a DAG. We use the term "sequence" to mean a directed path in this -DAG. Now, if we decompose the DAG into sequences, we just need to know -which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. - -So, to specify the partial order on the expectations we need to do two -things: first to define some `Sequence` objects, and then for each -`EXPECT_CALL()` say which `Sequence` objects it is part -of. Expectations in the same sequence must occur in the order they are -written. For example, - -``` - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(foo, A()) - .InSequence(s1, s2); - EXPECT_CALL(bar, B()) - .InSequence(s1); - EXPECT_CALL(bar, C()) - .InSequence(s2); - EXPECT_CALL(foo, D()) - .InSequence(s2); -``` - -specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> -C -> D`): - -``` - +---> B - | - A ---| - | - +---> C ---> D -``` - -This means that A must occur before B and C, and C must occur before -D. There's no restriction about the order other than these. - -## Controlling When an Expectation Retires ## - -When a mock method is called, Google Mock only consider expectations -that are still active. An expectation is active when created, and -becomes inactive (aka _retires_) when a call that has to occur later -has occurred. For example, in - -``` - using ::testing::_; - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 - .Times(AnyNumber()) - .InSequence(s1, s2); - EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 - .InSequence(s1); - EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 - .InSequence(s2); -``` - -as soon as either #2 or #3 is matched, #1 will retire. If a warning -`"File too large."` is logged after this, it will be an error. - -Note that an expectation doesn't retire automatically when it's -saturated. For example, - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 -``` - -says that there will be exactly one warning with the message `"File -too large."`. If the second warning contains this message too, #2 will -match again and result in an upper-bound-violated error. - -If this is not what you want, you can ask an expectation to retire as -soon as it becomes saturated: - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 - .RetiresOnSaturation(); -``` - -Here #2 can be used only once, so if you have two warnings with the -message `"File too large."`, the first will match #2 and the second -will match #1 - there will be no error. - -# Using Actions # - -## Returning References from Mock Methods ## - -If a mock function's return type is a reference, you need to use -`ReturnRef()` instead of `Return()` to return a result: - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetBar, Bar&()); -}; -... - - MockFoo foo; - Bar bar; - EXPECT_CALL(foo, GetBar()) - .WillOnce(ReturnRef(bar)); -``` - -## Returning Live Values from Mock Methods ## - -The `Return(x)` action saves a copy of `x` when the action is -_created_, and always returns the same value whenever it's -executed. Sometimes you may want to instead return the _live_ value of -`x` (i.e. its value at the time when the action is _executed_.). - -If the mock function's return type is a reference, you can do it using -`ReturnRef(x)`, as shown in the previous recipe ("Returning References -from Mock Methods"). However, Google Mock doesn't let you use -`ReturnRef()` in a mock function whose return type is not a reference, -as doing that usually indicates a user error. So, what shall you do? - -You may be tempted to try `ByRef()`: - -``` -using testing::ByRef; -using testing::Return; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetValue, int()); -}; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(Return(ByRef(x))); - x = 42; - EXPECT_EQ(42, foo.GetValue()); -``` - -Unfortunately, it doesn't work here. The above code will fail with error: - -``` -Value of: foo.GetValue() - Actual: 0 -Expected: 42 -``` - -The reason is that `Return(value)` converts `value` to the actual -return type of the mock function at the time when the action is -_created_, not when it is _executed_. (This behavior was chosen for -the action to be safe when `value` is a proxy object that references -some temporary objects.) As a result, `ByRef(x)` is converted to an -`int` value (instead of a `const int&`) when the expectation is set, -and `Return(ByRef(x))` will always return 0. - -`ReturnPointee(pointer)` was provided to solve this problem -specifically. It returns the value pointed to by `pointer` at the time -the action is _executed_: - -``` -using testing::ReturnPointee; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(ReturnPointee(&x)); // Note the & here. - x = 42; - EXPECT_EQ(42, foo.GetValue()); // This will succeed now. -``` - -## Combining Actions ## - -Want to do more than one thing when a function is called? That's -fine. `DoAll()` allow you to do sequence of actions every time. Only -the return value of the last action in the sequence will be used. - -``` -using ::testing::DoAll; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Bar, bool(int n)); -}; -... - - EXPECT_CALL(foo, Bar(_)) - .WillOnce(DoAll(action_1, - action_2, - ... - action_n)); -``` - -## Mocking Side Effects ## - -Sometimes a method exhibits its effect not via returning a value but -via side effects. For example, it may change some global state or -modify an output argument. To mock side effects, in general you can -define your own action by implementing `::testing::ActionInterface`. - -If all you need to do is to change an output argument, the built-in -`SetArgPointee()` action is convenient: - -``` -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - MOCK_METHOD2(Mutate, void(bool mutate, int* value)); - ... -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, Mutate(true, _)) - .WillOnce(SetArgPointee<1>(5)); -``` - -In this example, when `mutator.Mutate()` is called, we will assign 5 -to the `int` variable pointed to by argument #1 -(0-based). - -`SetArgPointee()` conveniently makes an internal copy of the -value you pass to it, removing the need to keep the value in scope and -alive. The implication however is that the value must have a copy -constructor and assignment operator. - -If the mock method also needs to return a value as well, you can chain -`SetArgPointee()` with `Return()` using `DoAll()`: - -``` -using ::testing::_; -using ::testing::Return; -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - ... - MOCK_METHOD1(MutateInt, bool(int* value)); -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, MutateInt(_)) - .WillOnce(DoAll(SetArgPointee<0>(5), - Return(true))); -``` - -If the output argument is an array, use the -`SetArrayArgument<N>(first, last)` action instead. It copies the -elements in source range `[first, last)` to the array pointed to by -the `N`-th (0-based) argument: - -``` -using ::testing::NotNull; -using ::testing::SetArrayArgument; - -class MockArrayMutator : public ArrayMutator { - public: - MOCK_METHOD2(Mutate, void(int* values, int num_values)); - ... -}; -... - - MockArrayMutator mutator; - int values[5] = { 1, 2, 3, 4, 5 }; - EXPECT_CALL(mutator, Mutate(NotNull(), 5)) - .WillOnce(SetArrayArgument<0>(values, values + 5)); -``` - -This also works when the argument is an output iterator: - -``` -using ::testing::_; -using ::testing::SeArrayArgument; - -class MockRolodex : public Rolodex { - public: - MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >)); - ... -}; -... - - MockRolodex rolodex; - vector<string> names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); - EXPECT_CALL(rolodex, GetNames(_)) - .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); -``` - -## Changing a Mock Object's Behavior Based on the State ## - -If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: - -``` -using ::testing::InSequence; -using ::testing::Return; - -... - { - InSequence seq; - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(true)); - EXPECT_CALL(my_mock, Flush()); - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(false)); - } - my_mock.FlushIfDirty(); -``` - -This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. - -If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: - -``` -using ::testing::_; -using ::testing::SaveArg; -using ::testing::Return; - -ACTION_P(ReturnPointee, p) { return *p; } -... - int previous_value = 0; - EXPECT_CALL(my_mock, GetPrevValue()) - .WillRepeatedly(ReturnPointee(&previous_value)); - EXPECT_CALL(my_mock, UpdateValue(_)) - .WillRepeatedly(SaveArg<0>(&previous_value)); - my_mock.DoSomethingToUpdateValue(); -``` - -Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. - -## Setting the Default Value for a Return Type ## - -If a mock method's return type is a built-in C++ type or pointer, by -default it will return 0 when invoked. You only need to specify an -action if this default value doesn't work for you. - -Sometimes, you may want to change this default value, or you may want -to specify a default value for types Google Mock doesn't know -about. You can do this using the `::testing::DefaultValue` class -template: - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD0(CalculateBar, Bar()); -}; -... - - Bar default_bar; - // Sets the default return value for type Bar. - DefaultValue<Bar>::Set(default_bar); - - MockFoo foo; - - // We don't need to specify an action here, as the default - // return value works for us. - EXPECT_CALL(foo, CalculateBar()); - - foo.CalculateBar(); // This should return default_bar. - - // Unsets the default return value. - DefaultValue<Bar>::Clear(); -``` - -Please note that changing the default value for a type can make you -tests hard to understand. We recommend you to use this feature -judiciously. For example, you may want to make sure the `Set()` and -`Clear()` calls are right next to the code that uses your mock. - -## Setting the Default Actions for a Mock Method ## - -You've learned how to change the default value of a given -type. However, this may be too coarse for your purpose: perhaps you -have two mock methods with the same return type and you want them to -have different behaviors. The `ON_CALL()` macro allows you to -customize your mock's behavior at the method level: - -``` -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Gt; -using ::testing::Return; -... - ON_CALL(foo, Sign(_)) - .WillByDefault(Return(-1)); - ON_CALL(foo, Sign(0)) - .WillByDefault(Return(0)); - ON_CALL(foo, Sign(Gt(0))) - .WillByDefault(Return(1)); - - EXPECT_CALL(foo, Sign(_)) - .Times(AnyNumber()); - - foo.Sign(5); // This should return 1. - foo.Sign(-9); // This should return -1. - foo.Sign(0); // This should return 0. -``` - -As you may have guessed, when there are more than one `ON_CALL()` -statements, the news order take precedence over the older ones. In -other words, the **last** one that matches the function arguments will -be used. This matching order allows you to set up the common behavior -in a mock object's constructor or the test fixture's set-up phase and -specialize the mock's behavior later. - -## Using Functions/Methods/Functors as Actions ## - -If the built-in actions don't suit you, you can easily use an existing -function, method, or functor as an action: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(Sum, int(int x, int y)); - MOCK_METHOD1(ComplexJob, bool(int x)); -}; - -int CalculateSum(int x, int y) { return x + y; } - -class Helper { - public: - bool ComplexJob(int x); -}; -... - - MockFoo foo; - Helper helper; - EXPECT_CALL(foo, Sum(_, _)) - .WillOnce(Invoke(CalculateSum)); - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); - - foo.Sum(5, 6); // Invokes CalculateSum(5, 6). - foo.ComplexJob(10); // Invokes helper.ComplexJob(10); -``` - -The only requirement is that the type of the function, etc must be -_compatible_ with the signature of the mock function, meaning that the -latter's arguments can be implicitly converted to the corresponding -arguments of the former, and the former's return type can be -implicitly converted to that of the latter. So, you can invoke -something whose type is _not_ exactly the same as the mock function, -as long as it's safe to do so - nice, huh? - -## Invoking a Function/Method/Functor Without Arguments ## - -`Invoke()` is very useful for doing actions that are more complex. It -passes the mock function's arguments to the function or functor being -invoked such that the callee has the full context of the call to work -with. If the invoked function is not interested in some or all of the -arguments, it can simply ignore them. - -Yet, a common pattern is that a test author wants to invoke a function -without the arguments of the mock function. `Invoke()` allows her to -do that using a wrapper function that throws away the arguments before -invoking an underlining nullary function. Needless to say, this can be -tedious and obscures the intent of the test. - -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except -that it doesn't pass the mock function's arguments to the -callee. Here's an example: - -``` -using ::testing::_; -using ::testing::InvokeWithoutArgs; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(ComplexJob, bool(int n)); -}; - -bool Job1() { ... } -... - - MockFoo foo; - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)); - - foo.ComplexJob(10); // Invokes Job1(). -``` - -## Invoking an Argument of the Mock Function ## - -Sometimes a mock function will receive a function pointer or a functor -(in other words, a "callable") as an argument, e.g. - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); -}; -``` - -and you may want to invoke this callable argument: - -``` -using ::testing::_; -... - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(...); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? - -Well, Google Mock has an action to solve _exactly_ this problem: - -``` - InvokeArgument<N>(arg_1, arg_2, ..., arg_m) -``` - -will invoke the `N`-th (0-based) argument the mock function receives, -with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is -a function pointer or a functor, Google Mock handles them both. - -With that, you could write: - -``` -using ::testing::_; -using ::testing::InvokeArgument; -... - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(InvokeArgument<1>(5)); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -What if the callable takes an argument by reference? No problem - just -wrap it inside `ByRef()`: - -``` -... - MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); -... -using ::testing::_; -using ::testing::ByRef; -using ::testing::InvokeArgument; -... - - MockFoo foo; - Helper helper; - ... - EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callable. -``` - -What if the callable takes an argument by reference and we do **not** -wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a -copy_ of the argument, and pass a _reference to the copy_, instead of -a reference to the original value, to the callable. This is especially -handy when the argument is a temporary value: - -``` -... - MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); -... -using ::testing::_; -using ::testing::InvokeArgument; -... - - MockFoo foo; - ... - EXPECT_CALL(foo, DoThat(_)) - .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); - // Will execute (*f)(5.0, string("Hi")), where f is the function pointer - // DoThat() receives. Note that the values 5.0 and string("Hi") are - // temporary and dead once the EXPECT_CALL() statement finishes. Yet - // it's fine to perform this action later, since a copy of the values - // are kept inside the InvokeArgument action. -``` - -## Ignoring an Action's Result ## - -Sometimes you have an action that returns _something_, but you need an -action that returns `void` (perhaps you want to use it in a mock -function that returns `void`, or perhaps it needs to be used in -`DoAll()` and it's not the last in the list). `IgnoreResult()` lets -you do that. For example: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -int Process(const MyData& data); -string DoSomething(); - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Abc, void(const MyData& data)); - MOCK_METHOD0(Xyz, bool()); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, Abc(_)) - // .WillOnce(Invoke(Process)); - // The above line won't compile as Process() returns int but Abc() needs - // to return void. - .WillOnce(IgnoreResult(Invoke(Process))); - - EXPECT_CALL(foo, Xyz()) - .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), - // Ignores the string DoSomething() returns. - Return(true))); -``` - -Note that you **cannot** use `IgnoreResult()` on an action that already -returns `void`. Doing so will lead to ugly compiler errors. - -## Selecting an Action's Arguments ## - -Say you have a mock function `Foo()` that takes seven arguments, and -you have a custom action that you want to invoke when `Foo()` is -called. Trouble is, the custom action only wants three arguments: - -``` -using ::testing::_; -using ::testing::Invoke; -... - MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight)); -... - -bool IsVisibleInQuadrant1(bool visible, int x, int y) { - return visible && x >= 0 && y >= 0; -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( -``` - -To please the compiler God, you can to define an "adaptor" that has -the same signature as `Foo()` and calls the custom action with the -right arguments: - -``` -using ::testing::_; -using ::testing::Invoke; - -bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight) { - return IsVisibleInQuadrant1(visible, x, y); -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. -``` - -But isn't this awkward? - -Google Mock provides a generic _action adaptor_, so you can spend your -time minding more important business than writing your own -adaptors. Here's the syntax: - -``` - WithArgs<N1, N2, ..., Nk>(action) -``` - -creates an action that passes the arguments of the mock function at -the given indices (0-based) to the inner `action` and performs -it. Using `WithArgs`, our original example can be written as: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::WithArgs; -... - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); - // No need to define your own adaptor. -``` - -For better readability, Google Mock also gives you: - - * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and - * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. - -As you may have realized, `InvokeWithoutArgs(...)` is just syntactic -sugar for `WithoutArgs(Inovke(...))`. - -Here are more tips: - - * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. - * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. - * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. - * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. - -## Ignoring Arguments in Action Functions ## - -The selecting-an-action's-arguments recipe showed us one way to make a -mock function and an action with incompatible argument lists fit -together. The downside is that wrapping the action in -`WithArgs<...>()` can get tedious for people writing the tests. - -If you are defining a function, method, or functor to be used with -`Invoke*()`, and you are not interested in some of its arguments, an -alternative to `WithArgs` is to declare the uninteresting arguments as -`Unused`. This makes the definition less cluttered and less fragile in -case the types of the uninteresting arguments change. It could also -increase the chance the action function can be reused. For example, -given - -``` - MOCK_METHOD3(Foo, double(const string& label, double x, double y)); - MOCK_METHOD3(Bar, double(int index, double x, double y)); -``` - -instead of - -``` -using ::testing::_; -using ::testing::Invoke; - -double DistanceToOriginWithLabel(const string& label, double x, double y) { - return sqrt(x*x + y*y); -} - -double DistanceToOriginWithIndex(int index, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOriginWithLabel)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOriginWithIndex)); -``` - -you could write - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Unused; - -double DistanceToOrigin(Unused, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOrigin)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOrigin)); -``` - -## Sharing Actions ## - -Just like matchers, a Google Mock action object consists of a pointer -to a ref-counted implementation object. Therefore copying actions is -also allowed and very efficient. When the last action that references -the implementation object dies, the implementation object will be -deleted. - -If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action -doesn't have an internal state (i.e. if it always does the same thing -no matter how many times it has been called), you can assign it to an -action variable and use that variable repeatedly. For example: - -``` - Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5), - Return(true)); - ... use set_flag in .WillOnce() and .WillRepeatedly() ... -``` - -However, if the action has its own state, you may be surprised if you -share the action object. Suppose you have an action factory -`IncrementCounter(init)` which creates an action that increments and -returns a counter whose initial value is `init`, using two actions -created from the same expression and using a shared action will -exihibit different behaviors. Example: - -``` - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(IncrementCounter(0)); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(IncrementCounter(0)); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. -``` - -versus - -``` - Action<int()> increment = IncrementCounter(0); - - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(increment); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(increment); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 3 - the counter is shared. -``` - -# Misc Recipes on Using Google Mock # - -## Making the Compilation Faster ## - -Believe it or not, the _vast majority_ of the time spent on compiling -a mock class is in generating its constructor and destructor, as they -perform non-trivial tasks (e.g. verification of the -expectations). What's more, mock methods with different signatures -have different types and thus their constructors/destructors need to -be generated by the compiler separately. As a result, if you mock many -different types of methods, compiling your mock class can get really -slow. - -If you are experiencing slow compilation, you can move the definition -of your mock class' constructor and destructor out of the class body -and into a `.cpp` file. This way, even if you `#include` your mock -class in N files, the compiler only needs to generate its constructor -and destructor once, resulting in a much faster compilation. - -Let's illustrate the idea using an example. Here's the definition of a -mock class before applying this recipe: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // Since we don't declare the constructor or the destructor, - // the compiler will generate them in every translation unit - // where this mock class is used. - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` - -After the change, it would look like: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // The constructor and destructor are declared, but not defined, here. - MockFoo(); - virtual ~MockFoo(); - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` -and -``` -// File mock_foo.cpp. -#include "path/to/mock_foo.h" - -// The definitions may appear trivial, but the functions actually do a -// lot of things through the constructors/destructors of the member -// variables used to implement the mock methods. -MockFoo::MockFoo() {} -MockFoo::~MockFoo() {} -``` - -## Forcing a Verification ## - -When it's being destoyed, your friendly mock object will automatically -verify that all expectations on it have been satisfied, and will -generate [Google Test](http://code.google.com/p/googletest/) failures -if not. This is convenient as it leaves you with one less thing to -worry about. That is, unless you are not sure if your mock object will -be destoyed. - -How could it be that your mock object won't eventually be destroyed? -Well, it might be created on the heap and owned by the code you are -testing. Suppose there's a bug in that code and it doesn't delete the -mock object properly - you could end up with a passing test when -there's actually a bug. - -Using a heap checker is a good idea and can alleviate the concern, but -its implementation may not be 100% reliable. So, sometimes you do want -to _force_ Google Mock to verify a mock object before it is -(hopefully) destructed. You can do this with -`Mock::VerifyAndClearExpectations(&mock_object)`: - -``` -TEST(MyServerTest, ProcessesRequest) { - using ::testing::Mock; - - MockFoo* const foo = new MockFoo; - EXPECT_CALL(*foo, ...)...; - // ... other expectations ... - - // server now owns foo. - MyServer server(foo); - server.ProcessRequest(...); - - // In case that server's destructor will forget to delete foo, - // this will verify the expectations anyway. - Mock::VerifyAndClearExpectations(foo); -} // server is destroyed when it goes out of scope here. -``` - -**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a -`bool` to indicate whether the verification was successful (`true` for -yes), so you can wrap that function call inside a `ASSERT_TRUE()` if -there is no point going further when the verification has failed. - -## Using Check Points ## - -Sometimes you may want to "reset" a mock object at various check -points in your test: at each check point, you verify that all existing -expectations on the mock object have been satisfied, and then you set -some new expectations on it as if it's newly created. This allows you -to work with a mock object in "phases" whose sizes are each -manageable. - -One such scenario is that in your test's `SetUp()` function, you may -want to put the object you are testing into a certain state, with the -help from a mock object. Once in the desired state, you want to clear -all expectations on the mock, such that in the `TEST_F` body you can -set fresh expectations on it. - -As you may have figured out, the `Mock::VerifyAndClearExpectations()` -function we saw in the previous recipe can help you here. Or, if you -are using `ON_CALL()` to set default actions on the mock object and -want to clear the default actions as well, use -`Mock::VerifyAndClear(&mock_object)` instead. This function does what -`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the -same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. - -Another trick you can use to achieve the same effect is to put the -expectations in sequences and insert calls to a dummy "check-point" -function at specific places. Then you can verify that the mock -function calls do happen at the right time. For example, if you are -exercising code: - -``` -Foo(1); -Foo(2); -Foo(3); -``` - -and want to verify that `Foo(1)` and `Foo(3)` both invoke -`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: - -``` -using ::testing::MockFunction; - -TEST(FooTest, InvokesBarCorrectly) { - MyMock mock; - // Class MockFunction<F> has exactly one mock method. It is named - // Call() and has type F. - MockFunction<void(string check_point_name)> check; - { - InSequence s; - - EXPECT_CALL(mock, Bar("a")); - EXPECT_CALL(check, Call("1")); - EXPECT_CALL(check, Call("2")); - EXPECT_CALL(mock, Bar("a")); - } - Foo(1); - check.Call("1"); - Foo(2); - check.Call("2"); - Foo(3); -} -``` - -The expectation spec says that the first `Bar("a")` must happen before -check point "1", the second `Bar("a")` must happen after check point "2", -and nothing should happen between the two check points. The explicit -check points make it easy to tell which `Bar("a")` is called by which -call to `Foo()`. - -## Mocking Destructors ## - -Sometimes you want to make sure a mock object is destructed at the -right time, e.g. after `bar->A()` is called but before `bar->B()` is -called. We already know that you can specify constraints on the order -of mock function calls, so all we need to do is to mock the destructor -of the mock function. - -This sounds simple, except for one problem: a destructor is a special -function with special syntax and special semantics, and the -`MOCK_METHOD0` macro doesn't work for it: - -``` - MOCK_METHOD0(~MockFoo, void()); // Won't compile! -``` - -The good news is that you can use a simple pattern to achieve the same -effect. First, add a mock function `Die()` to your mock class and call -it in the destructor, like this: - -``` -class MockFoo : public Foo { - ... - // Add the following two lines to the mock class. - MOCK_METHOD0(Die, void()); - virtual ~MockFoo() { Die(); } -}; -``` - -(If the name `Die()` clashes with an existing symbol, choose another -name.) Now, we have translated the problem of testing when a `MockFoo` -object dies to testing when its `Die()` method is called: - -``` - MockFoo* foo = new MockFoo; - MockBar* bar = new MockBar; - ... - { - InSequence s; - - // Expects *foo to die after bar->A() and before bar->B(). - EXPECT_CALL(*bar, A()); - EXPECT_CALL(*foo, Die()); - EXPECT_CALL(*bar, B()); - } -``` - -And that's that. - -## Using Google Mock and Threads ## - -**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on -platforms where Google Mock is thread-safe. Currently these are only -platforms that support the pthreads library (this includes Linux and Mac). -To make it thread-safe on other platforms we only need to implement -some synchronization operations in `"gtest/internal/gtest-port.h"`. - -In a **unit** test, it's best if you could isolate and test a piece of -code in a single-threaded context. That avoids race conditions and -dead locks, and makes debugging your test much easier. - -Yet many programs are multi-threaded, and sometimes to test something -we need to pound on it from more than one thread. Google Mock works -for this purpose too. - -Remember the steps for using a mock: - - 1. Create a mock object `foo`. - 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. - 1. The code under test calls methods of `foo`. - 1. Optionally, verify and reset the mock. - 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. - -If you follow the following simple rules, your mocks and threads can -live happily togeter: - - * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. - * Obviously, you can do step #1 without locking. - * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? - * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. - -If you violate the rules (for example, if you set expectations on a -mock while another thread is calling its methods), you get undefined -behavior. That's not fun, so don't do it. - -Google Mock guarantees that the action for a mock function is done in -the same thread that called the mock function. For example, in - -``` - EXPECT_CALL(mock, Foo(1)) - .WillOnce(action1); - EXPECT_CALL(mock, Foo(2)) - .WillOnce(action2); -``` - -if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, -Google Mock will execute `action1` in thread 1 and `action2` in thread -2. - -Google Mock does _not_ impose a sequence on actions performed in -different threads (doing so may create deadlocks as the actions may -need to cooperate). This means that the execution of `action1` and -`action2` in the above example _may_ interleave. If this is a problem, -you should add proper synchronization logic to `action1` and `action2` -to make the test thread-safe. - - -Also, remember that `DefaultValue<T>` is a global resource that -potentially affects _all_ living mock objects in your -program. Naturally, you won't want to mess with it from multiple -threads or when there still are mocks in action. - -## Controlling How Much Information Google Mock Prints ## - -When Google Mock sees something that has the potential of being an -error (e.g. a mock function with no expectation is called, a.k.a. an -uninteresting call, which is allowed but perhaps you forgot to -explicitly ban the call), it prints some warning messages, including -the arguments of the function and the return value. Hopefully this -will remind you to take a look and see if there is indeed a problem. - -Sometimes you are confident that your tests are correct and may not -appreciate such friendly messages. Some other times, you are debugging -your tests or learning about the behavior of the code you are testing, -and wish you could observe every mock call that happens (including -argument values and the return value). Clearly, one size doesn't fit -all. - -You can control how much Google Mock tells you using the -`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string -with three possible values: - - * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. - * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. - * `error`: Google Mock will print errors only (least verbose). - -Alternatively, you can adjust the value of that flag from within your -tests like so: - -``` - ::testing::FLAGS_gmock_verbose = "error"; -``` - -Now, judiciously use the right flag to enable Google Mock serve you better! - -## Running Tests in Emacs ## - -If you build and run your tests in Emacs, the source file locations of -Google Mock and [Google Test](http://code.google.com/p/googletest/) -errors will be highlighted. Just press `<Enter>` on one of them and -you'll be taken to the offending line. Or, you can just type `C-x `` -to jump to the next error. - -To make it even easier, you can add the following lines to your -`~/.emacs` file: - -``` -(global-set-key "\M-m" 'compile) ; m is for make -(global-set-key [M-down] 'next-error) -(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) -``` - -Then you can type `M-m` to start a build, or `M-up`/`M-down` to move -back and forth between errors. - -## Fusing Google Mock Source Files ## - -Google Mock's implementation consists of dozens of files (excluding -its own tests). Sometimes you may want them to be packaged up in -fewer files 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_gmock_files.py` in the `scripts/` directory -(starting with release 1.2.0). Assuming you have Python 2.4 or above -installed on your machine, just go to that directory and run -``` -python fuse_gmock_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. -These three files contain everything you need to use Google Mock (and -Google Test). Just copy them to anywhere you want and you are ready -to write tests and use mocks. You can use the -[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests -against them. - -# Extending Google Mock # - -## Writing New Matchers Quickly ## - -The `MATCHER*` family of macros can be used to define custom matchers -easily. The syntax: - -``` -MATCHER(name, description_string_expression) { statements; } -``` - -will define a matcher with the given name that executes the -statements, which must return a `bool` to indicate if the match -succeeds. Inside the statements, you can refer to the value being -matched by `arg`, and refer to its type by `arg_type`. - -The description string is a `string`-typed expression that documents -what the matcher does, and is used to generate the failure message -when the match fails. It can (and should) reference the special -`bool` variable `negation`, and should evaluate to the description of -the matcher when `negation` is `false`, or that of the matcher's -negation when `negation` is `true`. - -For convenience, we allow the description string to be empty (`""`), -in which case Google Mock will use the sequence of words in the -matcher name as the description. - -For example: -``` -MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } -``` -allows you to write -``` - // Expects mock_foo.Bar(n) to be called where n is divisible by 7. - EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); -``` -or, -``` -using ::testing::Not; -... - EXPECT_THAT(some_expression, IsDivisibleBy7()); - EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); -``` -If the above assertions fail, they will print something like: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 -... - Value of: some_other_expression - Expected: not (is divisible by 7) - Actual: 21 -``` -where the descriptions `"is divisible by 7"` and `"not (is divisible -by 7)"` are automatically calculated from the matcher name -`IsDivisibleBy7`. - -As you may have noticed, the auto-generated descriptions (especially -those for the negation) may not be so great. You can always override -them with a string expression of your own: -``` -MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + - " divisible by 7") { - return (arg % 7) == 0; -} -``` - -Optionally, you can stream additional information to a hidden argument -named `result_listener` to explain the match result. For example, a -better definition of `IsDivisibleBy7` is: -``` -MATCHER(IsDivisibleBy7, "") { - if ((arg % 7) == 0) - return true; - - *result_listener << "the remainder is " << (arg % 7); - return false; -} -``` - -With this definition, the above assertion will give a better message: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 (the remainder is 6) -``` - -You should let `MatchAndExplain()` print _any additional information_ -that can help a user understand the match result. Note that it should -explain why the match succeeds in case of a success (unless it's -obvious) - this is useful when the matcher is used inside -`Not()`. There is no need to print the argument value itself, as -Google Mock already prints it for you. - -**Notes:** - - 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. - 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. - -## Writing New Parameterized Matchers Quickly ## - -Sometimes you'll want to define a matcher that has parameters. For that you -can use the macro: -``` -MATCHER_P(name, param_name, description_string) { statements; } -``` -where the description string can be either `""` or a string expression -that references `negation` and `param_name`. - -For example: -``` -MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -``` -will allow you to write: -``` - EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -``` -which may lead to this message (assuming `n` is 10): -``` - Value of: Blah("a") - Expected: has absolute value 10 - Actual: -9 -``` - -Note that both the matcher description and its parameter are -printed, making the message human-friendly. - -In the matcher definition body, you can write `foo_type` to -reference the type of a parameter named `foo`. For example, in the -body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write -`value_type` to refer to the type of `value`. - -Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to -`MATCHER_P10` to support multi-parameter matchers: -``` -MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } -``` - -Please note that the custom description string is for a particular -**instance** of the matcher, where the parameters have been bound to -actual values. Therefore usually you'll want the parameter values to -be part of the description. Google Mock lets you do that by -referencing the matcher parameters in the description string -expression. - -For example, -``` - using ::testing::PrintToString; - MATCHER_P2(InClosedRange, low, hi, - std::string(negation ? "isn't" : "is") + " in range [" + - PrintToString(low) + ", " + PrintToString(hi) + "]") { - return low <= arg && arg <= hi; - } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the message: -``` - Expected: is in range [4, 6] -``` - -If you specify `""` as the description, the failure message will -contain the sequence of words in the matcher name followed by the -parameter values printed as a tuple. For example, -``` - MATCHER_P2(InClosedRange, low, hi, "") { ... } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the text: -``` - Expected: in closed range (4, 6) -``` - -For the purpose of typing, you can view -``` -MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -``` -as shorthand for -``` -template <typename p1_type, ..., typename pk_type> -FooMatcherPk<p1_type, ..., pk_type> -Foo(p1_type p1, ..., pk_type pk) { ... } -``` - -When you write `Foo(v1, ..., vk)`, the compiler infers the types of -the parameters `v1`, ..., and `vk` for you. If you are not happy with -the result of the type inference, you can specify the types by -explicitly instantiating the template, as in `Foo<long, bool>(5, false)`. -As said earlier, you don't get to (or need to) specify -`arg_type` as that's determined by the context in which the matcher -is used. - -You can assign the result of expression `Foo(p1, ..., pk)` to a -variable of type `FooMatcherPk<p1_type, ..., pk_type>`. This can be -useful when composing matchers. Matchers that don't have a parameter -or have only one parameter have special types: you can assign `Foo()` -to a `FooMatcher`-typed variable, and assign `Foo(p)` to a -`FooMatcherP<p_type>`-typed variable. - -While you can instantiate a matcher template with reference types, -passing the parameters by pointer usually makes your code more -readable. If, however, you still want to pass a parameter by -reference, be aware that in the failure message generated by the -matcher you will see the value of the referenced object but not its -address. - -You can overload matchers with different numbers of parameters: -``` -MATCHER_P(Blah, a, description_string_1) { ... } -MATCHER_P2(Blah, a, b, description_string_2) { ... } -``` - -While it's tempting to always use the `MATCHER*` macros when defining -a new matcher, you should also consider implementing -`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see -the recipes that follow), especially if you need to use the matcher a -lot. While these approaches require more work, they give you more -control on the types of the value being matched and the matcher -parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers -based on parameter types (as opposed to just based on the number of -parameters). - -## Writing New Monomorphic Matchers ## - -A matcher of argument type `T` implements -`::testing::MatcherInterface<T>` and does two things: it tests whether a -value of type `T` matches the matcher, and can describe what kind of -values it matches. The latter ability is used for generating readable -error messages when expectations are violated. - -The interface looks like this: - -``` -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template <typename T> - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - ::std::ostream* stream(); -}; - -template <typename T> -class MatcherInterface { - public: - virtual ~MatcherInterface(); - - // Returns true iff the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; -}; -``` - -If you need a custom matcher but `Truly()` is not a good option (for -example, you may not be happy with the way `Truly(predicate)` -describes itself, or you may want your matcher to be polymorphic as -`Eq(value)` is), you can define a matcher to do whatever you want in -two steps: first implement the matcher interface, and then define a -factory function to create a matcher instance. The second step is not -strictly needed but it makes the syntax of using the matcher nicer. - -For example, you can define a matcher to test whether an `int` is -divisible by 7 and then use it like this: -``` -using ::testing::MakeMatcher; -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { - return (n % 7) == 0; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "is divisible by 7"; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "is not divisible by 7"; - } -}; - -inline Matcher<int> DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); -} -... - - EXPECT_CALL(foo, Bar(DivisibleBy7())); -``` - -You may improve the matcher message by streaming additional -information to the `listener` argument in `MatchAndExplain()`: - -``` -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, - MatchResultListener* listener) const { - const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; - } - return remainder == 0; - } - ... -}; -``` - -Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: -``` -Value of: x -Expected: is divisible by 7 - Actual: 23 (the remainder is 2) -``` - -## Writing New Polymorphic Matchers ## - -You've learned how to write your own matchers in the previous -recipe. Just one problem: a matcher created using `MakeMatcher()` only -works for one particular type of arguments. If you want a -_polymorphic_ matcher that works with arguments of several types (for -instance, `Eq(x)` can be used to match a `value` as long as `value` == -`x` compiles -- `value` and `x` don't have to share the same type), -you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit -involved. - -Fortunately, most of the time you can define a polymorphic matcher -easily with the help of `MakePolymorphicMatcher()`. Here's how you can -define `NotNull()` as an example: - -``` -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -using ::testing::NotNull; -using ::testing::PolymorphicMatcher; - -class NotNullMatcher { - public: - // To implement a polymorphic matcher, first define a COPYABLE class - // that has three members MatchAndExplain(), DescribeTo(), and - // DescribeNegationTo(), like the following. - - // In this example, we want to use NotNull() with any pointer, so - // MatchAndExplain() accepts a pointer of any type as its first argument. - // In general, you can define MatchAndExplain() as an ordinary method or - // a method template, or even overload it. - template <typename T> - bool MatchAndExplain(T* p, - MatchResultListener* /* listener */) const { - return p != NULL; - } - - // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } - - // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } -}; - -// To construct a polymorphic matcher, pass an instance of the class -// to MakePolymorphicMatcher(). Note the return type. -inline PolymorphicMatcher<NotNullMatcher> NotNull() { - return MakePolymorphicMatcher(NotNullMatcher()); -} -... - - EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. -``` - -**Note:** Your polymorphic matcher class does **not** need to inherit from -`MatcherInterface` or any other class, and its methods do **not** need -to be virtual. - -Like in a monomorphic matcher, you may explain the match result by -streaming additional information to the `listener` argument in -`MatchAndExplain()`. - -## Writing New Cardinalities ## - -A cardinality is used in `Times()` to tell Google Mock how many times -you expect a call to occur. It doesn't have to be exact. For example, -you can say `AtLeast(5)` or `Between(2, 4)`. - -If the built-in set of cardinalities doesn't suit you, you are free to -define your own by implementing the following interface (in namespace -`testing`): - -``` -class CardinalityInterface { - public: - virtual ~CardinalityInterface(); - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; -``` - -For example, to specify that a call must occur even number of times, -you can write - -``` -using ::testing::Cardinality; -using ::testing::CardinalityInterface; -using ::testing::MakeCardinality; - -class EvenNumberCardinality : public CardinalityInterface { - public: - virtual bool IsSatisfiedByCallCount(int call_count) const { - return (call_count % 2) == 0; - } - - virtual bool IsSaturatedByCallCount(int call_count) const { - return false; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "called even number of times"; - } -}; - -Cardinality EvenNumber() { - return MakeCardinality(new EvenNumberCardinality); -} -... - - EXPECT_CALL(foo, Bar(3)) - .Times(EvenNumber()); -``` - -## Writing New Actions Quickly ## - -If the built-in actions don't work for you, and you find it -inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` -family to quickly define a new action that can be used in your code as -if it's a built-in action. - -By writing -``` -ACTION(name) { statements; } -``` -in a namespace scope (i.e. not inside a class or function), you will -define an action with the given name that executes the statements. -The value returned by `statements` will be used as the return value of -the action. Inside the statements, you can refer to the K-th -(0-based) argument of the mock function as `argK`. For example: -``` -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -``` -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments. Rest assured that your code is type-safe though: -you'll get a compiler error if `*arg1` doesn't support the `++` -operator, or if the type of `++(*arg1)` isn't compatible with the mock -function's return type. - -Another example: -``` -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -``` -int DoSomething(bool flag, int* ptr); -``` -we have: -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `std::tr1::tuple<bool, int*>` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Writing New Parameterized Actions Quickly ## - -Sometimes you'll want to parameterize an action you define. For that -we have another macro -``` -ACTION_P(name, param) { statements; } -``` - -For example, -``` -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -``` -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. For example, in the body of -`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. - -Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -``` -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -``` -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -You can also easily define actions overloaded on the number of parameters: -``` -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -## Restricting the Type of an Argument or Parameter in an ACTION ## - -For maximum brevity and reusability, the `ACTION*` macros don't ask -you to provide the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -``` -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq<const char*, arg1_type>(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion in Google Test -that verifies two types are the same. - -## Writing New Action Templates Quickly ## - -Sometimes you want to give an action explicit template parameters that -cannot be inferred from its value parameters. `ACTION_TEMPLATE()` -supports that and can be viewed as an extension to `ACTION()` and -`ACTION_P*()`. - -The syntax: -``` -ACTION_TEMPLATE(ActionName, - HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), - AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -``` - -defines an action template that takes _m_ explicit template parameters -and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is -between 0 and 10. `name_i` is the name of the i-th template -parameter, and `kind_i` specifies whether it's a `typename`, an -integral constant, or a template. `p_i` is the name of the i-th value -parameter. - -Example: -``` -// DuplicateArg<k, T>(output) converts the k-th argument of the mock -// function to type T and copies it to *output. -ACTION_TEMPLATE(DuplicateArg, - // Note the comma between int and k: - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(output)) { - *output = T(std::tr1::get<k>(args)); -} -``` - -To create an instance of an action template, write: -``` - ActionName<t1, ..., t_m>(v1, ..., v_n) -``` -where the `t`s are the template arguments and the -`v`s are the value arguments. The value argument -types are inferred by the compiler. For example: -``` -using ::testing::_; -... - int n; - EXPECT_CALL(mock, Foo(_, _)) - .WillOnce(DuplicateArg<1, unsigned char>(&n)); -``` - -If you want to explicitly specify the value argument types, you can -provide additional template arguments: -``` - ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) -``` -where `u_i` is the desired type of `v_i`. - -`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the -number of value parameters, but not on the number of template -parameters. Without the restriction, the meaning of the following is -unclear: - -``` - OverloadedAction<int, bool>(x); -``` - -Are we using a single-template-parameter action where `bool` refers to -the type of `x`, or a two-template-parameter action where the compiler -is asked to infer the type of `x`? - -## Using the ACTION Object's Type ## - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | -| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of value -parameters, or the action definitions cannot be overloaded on the -number of them. - -## Writing New Monomorphic Actions ## - -While the `ACTION*` macros are very convenient, sometimes they are -inappropriate. For example, despite the tricks shown in the previous -recipes, they don't let you directly specify the types of the mock -function arguments and the action parameters, which in general leads -to unoptimized compiler error messages that can baffle unfamiliar -users. They also don't allow overloading actions based on parameter -types without jumping through some hoops. - -An alternative to the `ACTION*` macros is to implement -`::testing::ActionInterface<F>`, where `F` is the type of the mock -function in which the action will be used. For example: - -``` -template <typename F>class ActionInterface { - public: - virtual ~ActionInterface(); - - // Performs the action. Result is the return type of function type - // F, and ArgumentTuple is the tuple of arguments of F. - // - // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>. - virtual Result Perform(const ArgumentTuple& args) = 0; -}; - -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::MakeAction; - -typedef int IncrementMethod(int*); - -class IncrementArgumentAction : public ActionInterface<IncrementMethod> { - public: - virtual int Perform(const tr1::tuple<int*>& args) { - int* p = tr1::get<0>(args); // Grabs the first argument. - return *p++; - } -}; - -Action<IncrementMethod> IncrementArgument() { - return MakeAction(new IncrementArgumentAction); -} -... - - EXPECT_CALL(foo, Baz(_)) - .WillOnce(IncrementArgument()); - - int n = 5; - foo.Baz(&n); // Should return 5 and change n to 6. -``` - -## Writing New Polymorphic Actions ## - -The previous recipe showed you how to define your own action. This is -all good, except that you need to know the type of the function in -which the action will be used. Sometimes that can be a problem. For -example, if you want to use the action in functions with _different_ -types (e.g. like `Return()` and `SetArgPointee()`). - -If an action can be used in several types of mock functions, we say -it's _polymorphic_. The `MakePolymorphicAction()` function template -makes it easy to define such an action: - -``` -namespace testing { - -template <typename Impl> -PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); - -} // namespace testing -``` - -As an example, let's define an action that returns the second argument -in the mock function's argument list. The first step is to define an -implementation class: - -``` -class ReturnSecondArgumentAction { - public: - template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use tr1::get<i>(args). - return tr1::get<1>(args); - } -}; -``` - -This implementation class does _not_ need to inherit from any -particular class. What matters is that it must have a `Perform()` -method template. This method template takes the mock function's -arguments as a tuple in a **single** argument, and returns the result of -the action. It can be either `const` or not, but must be invokable -with exactly one template argument, which is the result type. In other -words, you must be able to call `Perform<R>(args)` where `R` is the -mock function's return type and `args` is its arguments in a tuple. - -Next, we use `MakePolymorphicAction()` to turn an instance of the -implementation class into the polymorphic action we need. It will be -convenient to have a wrapper for this: - -``` -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; - -PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { - return MakePolymorphicAction(ReturnSecondArgumentAction()); -} -``` - -Now, you can use this polymorphic action the same way you use the -built-in ones: - -``` -using ::testing::_; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, int(bool flag, int n)); - MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(ReturnSecondArgument()); - EXPECT_CALL(foo, DoThat(_, _, _)) - .WillOnce(ReturnSecondArgument()); - ... - foo.DoThis(true, 5); // Will return 5. - foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". -``` - -## Teaching Google Mock How to Print Your Values ## - -When an uninteresting or unexpected call occurs, Google Mock prints the -argument values and the stack trace to help you debug. Assertion -macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in -question when the assertion fails. Google Mock and Google Test do this using -Google Test's 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. -[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#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. \ No newline at end of file diff --git a/googlemock/docs/v1_6/Documentation.md b/googlemock/docs/v1_6/Documentation.md deleted file mode 100644 index dcc9156c..00000000 --- a/googlemock/docs/v1_6/Documentation.md +++ /dev/null @@ -1,12 +0,0 @@ -This page lists all documentation wiki pages for Google Mock **1.6** -- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** - - * [ForDummies](V1_6_ForDummies.md) -- start here if you are new to Google Mock. - * [CheatSheet](V1_6_CheatSheet.md) -- a quick reference. - * [CookBook](V1_6_CookBook.md) -- recipes for doing various tasks using Google Mock. - * [FrequentlyAskedQuestions](V1_6_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Mock, read: - - * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [Pump Manual](http://code.google.com/p/googletest/wiki/V1_6_PumpManual) -- how we generate some of Google Mock's source files. \ No newline at end of file diff --git a/googlemock/docs/v1_6/ForDummies.md b/googlemock/docs/v1_6/ForDummies.md deleted file mode 100644 index 19ee63ab..00000000 --- a/googlemock/docs/v1_6/ForDummies.md +++ /dev/null @@ -1,439 +0,0 @@ - - -(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_6_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).) - -# What Is Google C++ Mocking Framework? # -When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). - -**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: - - * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. - * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. - -If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. - -**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. - -Using Google Mock involves three basic steps: - - 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; - 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; - 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. - -# Why Google Mock? # -While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. - * The knowledge you gained from using one mock doesn't transfer to the next. - -In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. - -Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: - - * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". - * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). - * Your tests are brittle as some resources they use are unreliable (e.g. the network). - * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. - * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. - * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. - -We encourage you to use Google Mock as: - - * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! - * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. - -# Getting Started # -Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. - -# A Case for Mock Turtles # -Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: - -``` -class Turtle { - ... - virtual ~Turtle() {} - virtual void PenUp() = 0; - virtual void PenDown() = 0; - virtual void Forward(int distance) = 0; - virtual void Turn(int degrees) = 0; - virtual void GoTo(int x, int y) = 0; - virtual int GetX() const = 0; - virtual int GetY() const = 0; -}; -``` - -(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) - -You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. - -Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. - -# Writing the Mock Class # -If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) - -## How to Define It ## -Using the `Turtle` interface as example, here are the simple steps you need to follow: - - 1. Derive a class `MockTurtle` from `Turtle`. - 1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has. - 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. - 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). - 1. Repeat until all virtual functions you want to mock are done. - -After the process, you should have something like: - -``` -#include "gmock/gmock.h" // Brings in Google Mock. -class MockTurtle : public Turtle { - public: - ... - MOCK_METHOD0(PenUp, void()); - MOCK_METHOD0(PenDown, void()); - MOCK_METHOD1(Forward, void(int distance)); - MOCK_METHOD1(Turn, void(int degrees)); - MOCK_METHOD2(GoTo, void(int x, int y)); - MOCK_CONST_METHOD0(GetX, int()); - MOCK_CONST_METHOD0(GetY, int()); -}; -``` - -You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. - -**Tip:** If even this is too much work for you, you'll find the -`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line -tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, -and it will print the definition of the mock class for you. Due to the -complexity of the C++ language, this script may not always work, but -it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). - -## Where to Put It ## -When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) - -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. - -Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - -# Using Mocks in Tests # -Once you have a mock class, using it is easy. The typical work flow is: - - 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). - 1. Create some mock objects. - 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). - 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. - 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. - -Here's an example: - -``` -#include "path/to/mock-turtle.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" -using ::testing::AtLeast; // #1 - -TEST(PainterTest, CanDrawSomething) { - MockTurtle turtle; // #2 - EXPECT_CALL(turtle, PenDown()) // #3 - .Times(AtLeast(1)); - - Painter painter(&turtle); // #4 - - EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); -} // #5 - -int main(int argc, char** argv) { - // The following line must be executed to initialize Google Mock - // (and Google Test) before running the tests. - ::testing::InitGoogleMock(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: - -``` -path/to/my_test.cc:119: Failure -Actual function call count doesn't match this expectation: -Actually: never called; -Expected: called at least once. -``` - -**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. - -**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. - -**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. - -This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. - -Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. - -## Using Google Mock with Any Testing Framework ## -If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: -``` -int main(int argc, char** argv) { - // The following line causes Google Mock to throw an exception on failure, - // which will be interpreted by your testing framework as a test failure. - ::testing::GTEST_FLAG(throw_on_failure) = true; - ::testing::InitGoogleMock(&argc, argv); - ... whatever your testing framework requires ... -} -``` - -This approach has a catch: it makes Google Mock throw an exception -from a mock object's destructor sometimes. With some compilers, this -sometimes causes the test program to crash. You'll still be able to -notice that the test has failed, but it's not a graceful failure. - -A better solution is to use Google Test's -[event listener API](http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) -to report a test failure to your testing framework properly. You'll need to -implement the `OnTestPartResult()` method of the event listener interface, but it -should be straightforward. - -If this turns out to be too much work, we suggest that you stick with -Google Test, which works with Google Mock seamlessly (in fact, it is -technically part of Google Mock.). If there is a reason that you -cannot use Google Test, please let us know. - -# Setting Expectations # -The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." - -## General Syntax ## -In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: - -``` -EXPECT_CALL(mock_object, method(matchers)) - .Times(cardinality) - .WillOnce(action) - .WillRepeatedly(action); -``` - -The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) - -The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. - -This syntax is designed to make an expectation read like English. For example, you can probably guess that - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .Times(5) - .WillOnce(Return(100)) - .WillOnce(Return(150)) - .WillRepeatedly(Return(200)); -``` - -says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). - -**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. - -## Matchers: What Arguments Do We Expect? ## -When a mock function takes arguments, we must specify what arguments we are expecting; for example: - -``` -// Expects the turtle to move forward by 100 units. -EXPECT_CALL(turtle, Forward(100)); -``` - -Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": - -``` -using ::testing::_; -... -// Expects the turtle to move forward. -EXPECT_CALL(turtle, Forward(_)); -``` - -`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. - -A list of built-in matchers can be found in the [CheatSheet](V1_6_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: - -``` -using ::testing::Ge;... -EXPECT_CALL(turtle, Forward(Ge(100))); -``` - -This checks that the turtle will be told to go forward by at least 100 units. - -## Cardinalities: How Many Times Will It Be Called? ## -The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. - -An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. - -We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_6_CheatSheet.md). - -The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: - - * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. - * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. - * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. - -**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? - -## Actions: What Should It Do? ## -Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. - -First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. - -Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillOnce(Return(300)); -``` - -This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillRepeatedly(Return(300)); -``` - -says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. - -Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). - -What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_6_CheatSheet#Actions). - -**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: - -``` -int n = 100; -EXPECT_CALL(turtle, GetX()) -.Times(4) -.WillRepeatedly(Return(n++)); -``` - -Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_6_CookBook.md). - -Time for another quiz! What do you think the following means? - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) -.Times(4) -.WillOnce(Return(100)); -``` - -Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. - -## Using Multiple Expectations ## -So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. - -By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: - -``` -using ::testing::_;... -EXPECT_CALL(turtle, Forward(_)); // #1 -EXPECT_CALL(turtle, Forward(10)) // #2 - .Times(2); -``` - -If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. - -**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. - -## Ordered vs Unordered Calls ## -By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. - -Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: - -``` -using ::testing::InSequence;... -TEST(FooTest, DrawsLineSegment) { - ... - { - InSequence dummy; - - EXPECT_CALL(turtle, PenDown()); - EXPECT_CALL(turtle, Forward(100)); - EXPECT_CALL(turtle, PenUp()); - } - Foo(); -} -``` - -By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. - -In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. - -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_6_CookBook.md).) - -## All Expectations Are Sticky (Unless Said Otherwise) ## -Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? - -After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): - -``` -using ::testing::_;... -EXPECT_CALL(turtle, GoTo(_, _)) // #1 - .Times(AnyNumber()); -EXPECT_CALL(turtle, GoTo(0, 0)) // #2 - .Times(2); -``` - -Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. - -This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). - -Simple? Let's see if you've really understood it: what does the following code say? - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)); -} -``` - -If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! - -One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); -} -``` - -And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: - -``` -using ::testing::InSequence; -using ::testing::Return; -... -{ - InSequence s; - - for (int i = 1; i <= n; i++) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); - } -} -``` - -By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). - -## Uninteresting Calls ## -A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. - -In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. - -# What Now? # -Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. - -Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_6_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. \ No newline at end of file diff --git a/googlemock/docs/v1_6/FrequentlyAskedQuestions.md b/googlemock/docs/v1_6/FrequentlyAskedQuestions.md deleted file mode 100644 index f74715d2..00000000 --- a/googlemock/docs/v1_6/FrequentlyAskedQuestions.md +++ /dev/null @@ -1,628 +0,0 @@ - - -Please send your questions to the -[googlemock](http://groups.google.com/group/googlemock) discussion -group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. - -## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## - -In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Nonvirtual_Methods). - -## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## - -After version 1.4.0 of Google Mock was released, we had an idea on how -to make it easier to write matchers that can generate informative -messages efficiently. We experimented with this idea and liked what -we saw. Therefore we decided to implement it. - -Unfortunately, this means that if you have defined your own matchers -by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, -your definitions will no longer compile. Matchers defined using the -`MATCHER*` family of macros are not affected. - -Sorry for the hassle if your matchers are affected. We believe it's -in everyone's long-term interest to make this change sooner than -later. Fortunately, it's usually not hard to migrate an existing -matcher to the new API. Here's what you need to do: - -If you wrote your matcher like this: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` - -you'll need to change it to: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` -(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second -argument of type `MatchResultListener*`.) - -If you were also using `ExplainMatchResultTo()` to improve the matcher -message: -``` -// Old matcher definition that doesn't work with the lastest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - - virtual void ExplainMatchResultTo(MyType value, - ::std::ostream* os) const { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Foo property is " << value.GetFoo(); - } - ... -}; -``` - -you should move the logic of `ExplainMatchResultTo()` into -`MatchAndExplain()`, using the `MatchResultListener` argument where -the `::std::ostream` was used: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Foo property is " << value.GetFoo(); - return value.GetFoo() > 5; - } - ... -}; -``` - -If your matcher is defined using `MakePolymorphicMatcher()`: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you should rename the `Matches()` method to `MatchAndExplain()` and -add a `MatchResultListener*` argument (the same as what you need to do -for matchers defined by implementing `MatcherInterface`): -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -If your polymorphic matcher uses `ExplainMatchResultTo()` for better -failure messages: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -void ExplainMatchResultTo(const MyGreatMatcher& matcher, - MyType value, - ::std::ostream* os) { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Bar property is " << value.GetBar(); -} -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you'll need to move the logic inside `ExplainMatchResultTo()` to -`MatchAndExplain()`: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Bar property is " << value.GetBar(); - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -For more information, you can read these -[two](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Monomorphic_Matchers) -[recipes](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Matchers) -from the cookbook. As always, you -are welcome to post questions on `googlemock@googlegroups.com` if you -need any help. - -## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## - -Google Mock works out of the box with Google Test. However, it's easy -to configure it to work with any testing framework of your choice. -[Here](http://code.google.com/p/googlemock/wiki/V1_6_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how. - -## How am I supposed to make sense of these horrible template errors? ## - -If you are confused by the compiler errors gcc threw at you, -try consulting the _Google Mock Doctor_ tool first. What it does is to -scan stdin for gcc error messages, and spit out diagnoses on the -problems (we call them diseases) your code has. - -To "install", run command: -``` -alias gmd='<path to googlemock>/scripts/gmock_doctor.py' -``` - -To use it, do: -``` -<your-favorite-build-command> <your-test> 2>&1 | gmd -``` - -For example: -``` -make my_test 2>&1 | gmd -``` - -Or you can run `gmd` and copy-n-paste gcc's error messages to it. - -## Can I mock a variadic function? ## - -You cannot mock a variadic function (i.e. a function taking ellipsis -(`...`) arguments) directly in Google Mock. - -The problem is that in general, there is _no way_ for a mock object to -know how many arguments are passed to the variadic method, and what -the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into his head. - -Therefore, to mock such a function, the _user_ must teach the mock -object how to figure out the number of arguments and their types. One -way to do it is to provide overloaded versions of the function. - -Ellipsis arguments are inherited from C and not really a C++ feature. -They are unsafe to use and don't work with arguments that have -constructors or destructors. Therefore we recommend to avoid them in -C++ as much as possible. - -## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## - -If you compile this using Microsoft Visual C++ 2005 SP1: -``` -class Foo { - ... - virtual void Bar(const int i) = 0; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Bar, void(const int i)); -}; -``` -You may get the following warning: -``` -warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier -``` - -This is a MSVC bug. The same code compiles fine with gcc ,for -example. If you use Visual C++ 2008 SP1, you would get the warning: -``` -warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers -``` - -In C++, if you _declare_ a function with a `const` parameter, the -`const` modifier is _ignored_. Therefore, the `Foo` base class above -is equivalent to: -``` -class Foo { - ... - virtual void Bar(int i) = 0; // int or const int? Makes no difference. -}; -``` - -In fact, you can _declare_ Bar() with an `int` parameter, and _define_ -it with a `const int` parameter. The compiler will still match them -up. - -Since making a parameter `const` is meaningless in the method -_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. -That should workaround the VC bug. - -Note that we are talking about the _top-level_ `const` modifier here. -If the function parameter is passed by pointer or reference, declaring -the _pointee_ or _referee_ as `const` is still meaningful. For -example, the following two declarations are _not_ equivalent: -``` -void Bar(int* p); // Neither p nor *p is const. -void Bar(const int* p); // p is not const, but *p is. -``` - -## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## - -We've noticed that when the `/clr` compiler flag is used, Visual C++ -uses 5~6 times as much memory when compiling a mock class. We suggest -to avoid `/clr` when compiling native C++ mocks. - -## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## - -You might want to run your test with -`--gmock_verbose=info`. This flag lets Google Mock print a trace -of every mock function call it receives. By studying the trace, -you'll gain insights on why the expectations you set are not met. - -## How can I assert that a function is NEVER called? ## - -``` -EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## - -When Google Mock detects a failure, it prints relevant information -(the mock function arguments, the state of relevant expectations, and -etc) to help the user debug. If another failure is detected, Google -Mock will do the same, including printing the state of relevant -expectations. - -Sometimes an expectation's state didn't change between two failures, -and you'll see the same description of the state twice. They are -however _not_ redundant, as they refer to _different points in time_. -The fact they are the same _is_ interesting information. - -## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## - -Does the class (hopefully a pure interface) you are mocking have a -virtual destructor? - -Whenever you derive from a base class, make sure its destructor is -virtual. Otherwise Bad Things will happen. Consider the following -code: - -``` -class Base { - public: - // Not virtual, but should be. - ~Base() { ... } - ... -}; - -class Derived : public Base { - public: - ... - private: - std::string value_; -}; - -... - Base* p = new Derived; - ... - delete p; // Surprise! ~Base() will be called, but ~Derived() will not - // - value_ is leaked. -``` - -By changing `~Base()` to virtual, `~Derived()` will be correctly -called when `delete p` is executed, and the heap checker -will be happy. - -## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## - -When people complain about this, often they are referring to code like: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. However, I have to write the expectations in the -// reverse order. This sucks big time!!! -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); -``` - -The problem is that they didn't pick the **best** way to express the test's -intent. - -By default, expectations don't have to be matched in _any_ particular -order. If you want them to match in a certain order, you need to be -explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's -easy to accidentally over-specify your tests, and we want to make it -harder to do so. - -There are two better ways to write the test spec. You could either -put the expectations in sequence: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. Using a sequence, we can write the expectations -// in their natural order. -{ - InSequence s; - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -} -``` - -or you can put the sequence of actions in the same expectation: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -``` - -Back to the original questions: why does Google Mock search the -expectations (and `ON_CALL`s) from back to front? Because this -allows a user to set up a mock's behavior for the common case early -(e.g. in the mock's constructor or the test fixture's set-up phase) -and customize it with more specific rules later. If Google Mock -searches from front to back, this very useful pattern won't be -possible. - -## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## - -When choosing between being neat and being safe, we lean toward the -latter. So the answer is that we think it's better to show the -warning. - -Often people write `ON_CALL`s in the mock object's -constructor or `SetUp()`, as the default behavior rarely changes from -test to test. Then in the test body they set the expectations, which -are often different for each test. Having an `ON_CALL` in the set-up -part of a test doesn't mean that the calls are expected. If there's -no `EXPECT_CALL` and the method is called, it's possibly an error. If -we quietly let the call go through without notifying the user, bugs -may creep in unnoticed. - -If, however, you are sure that the calls are OK, you can write - -``` -EXPECT_CALL(foo, Bar(_)) - .WillRepeatedly(...); -``` - -instead of - -``` -ON_CALL(foo, Bar(_)) - .WillByDefault(...); -``` - -This tells Google Mock that you do expect the calls and no warning should be -printed. - -Also, you can control the verbosity using the `--gmock_verbose` flag. -If you find the output too noisy when debugging, just choose a less -verbose level. - -## How can I delete the mock function's argument in an action? ## - -If you find yourself needing to perform some action that's not -supported by Google Mock directly, remember that you can define your own -actions using -[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Actions) or -[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Writing_New_Polymorphic_Actions), -or you can write a stub function and invoke it using -[Invoke()](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Using_Functions_Methods_Functors). - -## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## - -What?! I think it's beautiful. :-) - -While which syntax looks more natural is a subjective matter to some -extent, Google Mock's syntax was chosen for several practical advantages it -has. - -Try to mock a function that takes a map as an argument: -``` -virtual int GetSize(const map<int, std::string>& m); -``` - -Using the proposed syntax, it would be: -``` -MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); -``` - -Guess what? You'll get a compiler error as the compiler thinks that -`const map<int, std::string>& m` are **two**, not one, arguments. To work -around this you can use `typedef` to give the map type a name, but -that gets in the way of your work. Google Mock's syntax avoids this -problem as the function's argument types are protected inside a pair -of parentheses: -``` -// This compiles fine. -MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); -``` - -You still need a `typedef` if the return type contains an unprotected -comma, but that's much rarer. - -Other advantages include: - 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. - 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. - 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! - -## My code calls a static/global function. Can I mock it? ## - -You can, but you need to make some changes. - -In general, if you find yourself needing to mock a static function, -it's a sign that your modules are too tightly coupled (and less -flexible, less reusable, less testable, etc). You are probably better -off defining a small interface and call the function through that -interface, which then can be easily mocked. It's a bit of work -initially, but usually pays for itself quickly. - -This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) -says it excellently. Check it out. - -## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## - -I know it's not a question, but you get an answer for free any way. :-) - -With Google Mock, you can create mocks in C++ easily. And people might be -tempted to use them everywhere. Sometimes they work great, and -sometimes you may find them, well, a pain to use. So, what's wrong in -the latter case? - -When you write a test without using mocks, you exercise the code and -assert that it returns the correct value or that the system is in an -expected state. This is sometimes called "state-based testing". - -Mocks are great for what some call "interaction-based" testing: -instead of checking the system state at the very end, mock objects -verify that they are invoked the right way and report an error as soon -as it arises, giving you a handle on the precise context in which the -error was triggered. This is often more effective and economical to -do than state-based testing. - -If you are doing state-based testing and using a test double just to -simulate the real object, you are probably better off using a fake. -Using a mock in this case causes pain, as it's not a strong point for -mocks to perform complex actions. If you experience this and think -that mocks suck, you are just not using the right tool for your -problem. Or, you might be trying to solve the wrong problem. :-) - -## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## - -By all means, NO! It's just an FYI. - -What it means is that you have a mock function, you haven't set any -expectations on it (by Google Mock's rule this means that you are not -interested in calls to this function and therefore it can be called -any number of times), and it is called. That's OK - you didn't say -it's not OK to call the function! - -What if you actually meant to disallow this function to be called, but -forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While -one can argue that it's the user's fault, Google Mock tries to be nice and -prints you a note. - -So, when you see the message and believe that there shouldn't be any -uninteresting calls, you should investigate what's going on. To make -your life easier, Google Mock prints the function name and arguments -when an uninteresting call is encountered. - -## I want to define a custom action. Should I use Invoke() or implement the action interface? ## - -Either way is fine - you want to choose the one that's more convenient -for your circumstance. - -Usually, if your action is for a particular function type, defining it -using `Invoke()` should be easier; if your action can be used in -functions of different types (e.g. if you are defining -`Return(value)`), `MakePolymorphicAction()` is -easiest. Sometimes you want precise control on what types of -functions the action can be used in, and implementing -`ActionInterface` is the way to go here. See the implementation of -`Return()` in `include/gmock/gmock-actions.h` for an example. - -## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## - -You got this error as Google Mock has no idea what value it should return -when the mock method is called. `SetArgPointee()` says what the -side effect is, but doesn't say what the return value should be. You -need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. - -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_6_CookBook#Mocking_Side_Effects) for more details and an example. - - -## My question is not in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), - 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). - -Please note that creating an issue in the -[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. \ No newline at end of file diff --git a/googlemock/docs/v1_7/CheatSheet.md b/googlemock/docs/v1_7/CheatSheet.md deleted file mode 100644 index db421e51..00000000 --- a/googlemock/docs/v1_7/CheatSheet.md +++ /dev/null @@ -1,556 +0,0 @@ - - -# Defining a Mock Class # - -## Mocking a Normal Class ## - -Given -``` -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` -(note that `~Foo()` **must** be virtual) we can define its mock as -``` -#include "gmock/gmock.h" - -class MockFoo : public Foo { - MOCK_CONST_METHOD0(GetSize, int()); - MOCK_METHOD1(Describe, string(const char* name)); - MOCK_METHOD1(Describe, string(int type)); - MOCK_METHOD2(Process, bool(Bar elem, int count)); -}; -``` - -To create a "nice" mock object which ignores all uninteresting calls, -or a "strict" mock object, which treats them as failures: -``` -NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. -StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. -``` - -## Mocking a Class Template ## - -To mock -``` -template <typename Elem> -class StackInterface { - public: - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` -(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -``` -template <typename Elem> -class MockStack : public StackInterface<Elem> { - public: - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Specifying Calling Conventions for Mock Functions ## - -If your mock function doesn't use the default calling convention, you -can specify it by appending `_WITH_CALLTYPE` to any of the macros -described in the previous two sections and supplying the calling -convention as the first argument to the macro. For example, -``` - MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); - MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); -``` -where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. - -# Using Mocks in Tests # - -The typical flow is: - 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. - 1. Create the mock objects. - 1. Optionally, set the default actions of the mock objects. - 1. Set your expectations on the mock objects (How will they be called? What wil they do?). - 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](http://code.google.com/p/googletest/) assertions. - 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. - -Here is an example: -``` -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -# Setting Default Actions # - -Google Mock has a **built-in default action** for any function that -returns `void`, `bool`, a numeric value, or a pointer. - -To customize the default action for functions with return type `T` globally: -``` -using ::testing::DefaultValue; - -DefaultValue<T>::Set(value); // Sets the default value to be returned. -// ... use the mocks ... -DefaultValue<T>::Clear(); // Resets the default value. -``` - -To customize the default action for a particular method, use `ON_CALL()`: -``` -ON_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .WillByDefault(action); -``` - -# Setting Expectations # - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be -called? What will it do?): -``` -EXPECT_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -If `Times()` is omitted, the cardinality is assumed to be: - - * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; - * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or - * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. - -# Matchers # - -A **matcher** matches a _single_ argument. You can use it inside -`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value -directly: - -| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -|:------------------------------|:----------------------------------------| -| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | - -Built-in matchers (where `argument` is the function argument) are -divided into several categories: - -## Wildcard ## -|`_`|`argument` can be any value of the correct type.| -|:--|:-----------------------------------------------| -|`A<type>()` or `An<type>()`|`argument` can be any value of type `type`. | - -## Generic Comparison ## - -|`Eq(value)` or `value`|`argument == value`| -|:---------------------|:------------------| -|`Ge(value)` |`argument >= value`| -|`Gt(value)` |`argument > value` | -|`Le(value)` |`argument <= value`| -|`Lt(value)` |`argument < value` | -|`Ne(value)` |`argument != value`| -|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| -|`NotNull()` |`argument` is a non-null pointer (raw or smart).| -|`Ref(variable)` |`argument` is a reference to `variable`.| -|`TypedEq<type>(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| - -Except `Ref()`, these matchers make a _copy_ of `value` in case it's -modified or destructed later. If the compiler complains that `value` -doesn't have a public copy constructor, try wrap it in `ByRef()`, -e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure -`non_copyable_value` is not changed afterwards, or the meaning of your -matcher will be changed. - -## Floating-Point Matchers ## - -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal.| -|:-------------------|:----------------------------------------------------------------------------------------------| -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | - -The above matchers use ULP-based comparison (the same as used in -[Google Test](http://code.google.com/p/googletest/)). They -automatically pick a reasonable error bound based on the absolute -value of the expected value. `DoubleEq()` and `FloatEq()` conform to -the IEEE standard, which requires comparing two NaNs for equality to -return false. The `NanSensitive*` version instead treats two NaNs as -equal, which is often what a user wants. - -|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.| -|:------------------------------------|:--------------------------------------------------------------------------------------------------------------------| -|`FloatNear(a_float, max_abs_error)` |`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | -|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | -|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | - -## String Matchers ## - -The `argument` can be either a C string or a C++ string object: - -|`ContainsRegex(string)`|`argument` matches the given regular expression.| -|:----------------------|:-----------------------------------------------| -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | -|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | -|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | - -`ContainsRegex()` and `MatchesRegex()` use the regular expression -syntax defined -[here](http://code.google.com/p/googletest/wiki/AdvancedGuide#Regular_Expression_Syntax). -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide -strings as well. - -## Container Matchers ## - -Most STL-style containers support `==`, so you can use -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. If you want to write the elements in-line, -match them more flexibly, or get more informative messages, you can use: - -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | -|:-------------------------|:---------------------------------------------------------------------------------------------------------------------------------| -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | -| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. | -| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | -| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | -| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | -| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, vector, or C-style array. | -| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(UnorderedElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. | -| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater<int>(), ElementsAre(3, 2, 1))`. | - -Notes: - - * These matchers can also match: - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#Multiargument_Matchers.md)). - * The array being matched may be multi-dimensional (i.e. its elements can be arrays). - * `m` in `Pointwise(m, ...)` should be a matcher for `std::tr1::tuple<T, U>` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write: - -``` -using ::std::tr1::get; -MATCHER(FooEq, "") { - return get<0>(arg).Equals(get<1>(arg)); -} -... -EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); -``` - -## Member Matchers ## - -|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|:------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------| -|`Key(e)` |`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)` |`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | -|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| - -## Matching the Result of a Function or Functor ## - -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| -|:---------------|:---------------------------------------------------------------------| - -## Pointer Matchers ## - -|`Pointee(m)`|`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|:-----------|:-----------------------------------------------------------------------------------------------| - -## Multiargument Matchers ## - -Technically, all matchers match a _single_ value. A "multi-argument" -matcher is just one that matches a _tuple_. The following matchers can -be used to match a tuple `(x, y)`: - -|`Eq()`|`x == y`| -|:-----|:-------| -|`Ge()`|`x >= y`| -|`Gt()`|`x > y` | -|`Le()`|`x <= y`| -|`Lt()`|`x < y` | -|`Ne()`|`x != y`| - -You can use the following selectors to pick a subset of the arguments -(or reorder them) to participate in the matching: - -|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|:-----------|:-------------------------------------------------------------------| -|`Args<N1, N2, ..., Nk>(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| - -## Composite Matchers ## - -You can make a matcher from one or more other matchers: - -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`.| -|:-----------------------|:---------------------------------------------------| -|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | - -## Adapters for Matchers ## - -|`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| -|:------------------|:--------------------------------------| -|`SafeMatcherCast<T>(m)`| [safely casts](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Casting_Matchers) matcher `m` to type `Matcher<T>`. | -|`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| - -## Matchers as Predicates ## - -|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| -|:------------------|:---------------------------------------------------------------------------------------------| -|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | -|`Value(value, m)` |evaluates to `true` if `value` matches `m`. | - -## Defining Matchers ## - -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -|:-------------------------------------------------|:------------------------------------------------------| -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - -**Notes:** - - 1. The `MATCHER*` macros cannot be used inside a function or class. - 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). - 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. - -## Matchers as Test Assertions ## - -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](http://code.google.com/p/googletest/wiki/Primer#Assertions) if the value of `expression` doesn't match matcher `m`.| -|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | - -# Actions # - -**Actions** specify what a mock function should do when invoked. - -## Returning a Value ## - -|`Return()`|Return from a `void` mock function.| -|:---------|:----------------------------------| -|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| -|`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| -|`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer. | -|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| -|`ReturnRef(variable)`|Return a reference to `variable`. | -|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| - -## Side Effects ## - -|`Assign(&variable, value)`|Assign `value` to variable.| -|:-------------------------|:--------------------------| -| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | -| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | -| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | -| `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -|`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| -|`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| -|`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| -|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| - -## Using a Function or a Functor as an Action ## - -|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|:----------|:-----------------------------------------------------------------------------------------------------------------| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | -|`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| - -The return value of the invoked function is used as the return value -of the action. - -When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -``` - double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } - ... - EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -``` - InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. - -## Default Action ## - -|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| -|:------------|:--------------------------------------------------------------------| - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. - -## Composite Actions ## - -|`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -|`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | - -## Defining Actions ## - -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -|:--------------------------------------|:---------------------------------------------------------------------------------------| -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - -The `ACTION*` macros cannot be used inside a function or class. - -# Cardinalities # - -These are used in `Times()` to specify how many times a mock function will be called: - -|`AnyNumber()`|The function can be called any number of times.| -|:------------|:----------------------------------------------| -|`AtLeast(n)` |The call is expected at least `n` times. | -|`AtMost(n)` |The call is expected at most `n` times. | -|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| -|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| - -# Expectation Order # - -By default, the expectations can be matched in _any_ order. If some -or all expectations must be matched in a given order, there are two -ways to specify it. They can be used either independently or -together. - -## The After Clause ## - -``` -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` -says that `Bar()` can be called only after both `InitX()` and -`InitY()` have been called. - -If you don't know how many pre-requisites an expectation has when you -write it, you can use an `ExpectationSet` to collect them: - -``` -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` -says that `Bar()` can be called only after all elements have been -initialized (but we don't care about which elements get initialized -before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't -affect the meaning of the `.After()`. - -## Sequences ## - -When you have a long chain of sequential expectations, it's easier to -specify the order using **sequences**, which don't require you to given -each expectation in the chain a different name. <i>All expected<br> -calls</i> in the same sequence must occur in the order they are -specified. - -``` -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A<const char*>())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` -says that `Reset()` must be called before _both_ `GetSize()` _and_ -`Describe()`, and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: -``` -using ::testing::InSequence; -{ - InSequence dummy; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` -says that all expected calls in the scope of `dummy` must occur in -strict order. The name `dummy` is irrelevant.) - -# Verifying and Resetting a Mock # - -Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -``` -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true iff successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true iff successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell Google Mock that a mock object can be leaked and doesn't -need to be verified: -``` -Mock::AllowLeak(&mock_obj); -``` - -# Mock Classes # - -Google Mock defines a convenient mock class template -``` -class MockFunction<R(A1, ..., An)> { - public: - MOCK_METHODn(Call, R(A1, ..., An)); -}; -``` -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Check_Points) for one application of it. - -# Flags # - -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -|:-------------------------------|:----------------------------------------------| -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | \ No newline at end of file diff --git a/googlemock/docs/v1_7/CookBook.md b/googlemock/docs/v1_7/CookBook.md deleted file mode 100644 index 419a0010..00000000 --- a/googlemock/docs/v1_7/CookBook.md +++ /dev/null @@ -1,3432 +0,0 @@ - - -You can find recipes for using Google Mock here. If you haven't yet, -please read the [ForDummies](V1_7_ForDummies.md) document first to make sure you understand -the basics. - -**Note:** Google Mock lives in the `testing` name space. For -readability, it is recommended to write `using ::testing::Foo;` once in -your file before using the name `Foo` defined by Google Mock. We omit -such `using` statements in this page for brevity, but you should do it -in your own code. - -# Creating Mock Classes # - -## Mocking Private or Protected Methods ## - -You must always put a mock method definition (`MOCK_METHOD*`) in a -`public:` section of the mock class, regardless of the method being -mocked being `public`, `protected`, or `private` in the base class. -This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to change -the access level of a virtual function in the base class.) Example: - -``` -class Foo { - public: - ... - virtual bool Transform(Gadget* g) = 0; - - protected: - virtual void Resume(); - - private: - virtual int GetTimeOut(); -}; - -class MockFoo : public Foo { - public: - ... - MOCK_METHOD1(Transform, bool(Gadget* g)); - - // The following must be in the public section, even though the - // methods are protected or private in the base class. - MOCK_METHOD0(Resume, void()); - MOCK_METHOD0(GetTimeOut, int()); -}; -``` - -## Mocking Overloaded Methods ## - -You can mock overloaded functions as usual. No special attention is required: - -``` -class Foo { - ... - - // Must be virtual as we'll inherit from Foo. - virtual ~Foo(); - - // Overloaded on the types and/or numbers of arguments. - virtual int Add(Element x); - virtual int Add(int times, Element x); - - // Overloaded on the const-ness of this object. - virtual Bar& GetBar(); - virtual const Bar& GetBar() const; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Add, int(Element x)); - MOCK_METHOD2(Add, int(int times, Element x); - - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -``` - -**Note:** if you don't mock all versions of the overloaded method, the -compiler will give you a warning about some methods in the base class -being hidden. To fix that, use `using` to bring them in scope: - -``` -class MockFoo : public Foo { - ... - using Foo::Add; - MOCK_METHOD1(Add, int(Element x)); - // We don't want to mock int Add(int times, Element x); - ... -}; -``` - -## Mocking Class Templates ## - -To mock a class template, append `_T` to the `MOCK_*` macros: - -``` -template <typename Elem> -class StackInterface { - ... - // Must be virtual as we'll inherit from StackInterface. - virtual ~StackInterface(); - - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; - -template <typename Elem> -class MockStack : public StackInterface<Elem> { - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Mocking Nonvirtual Methods ## - -Google Mock can mock non-virtual functions to be used in what we call _hi-perf -dependency injection_. - -In this case, instead of sharing a common base class with the real -class, your mock class will be _unrelated_ to the real class, but -contain methods with the same signatures. The syntax for mocking -non-virtual methods is the _same_ as mocking virtual methods: - -``` -// A simple packet stream class. None of its members is virtual. -class ConcretePacketStream { - public: - void AppendPacket(Packet* new_packet); - const Packet* GetPacket(size_t packet_number) const; - size_t NumberOfPackets() const; - ... -}; - -// A mock packet stream class. It inherits from no other, but defines -// GetPacket() and NumberOfPackets(). -class MockPacketStream { - public: - MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); - MOCK_CONST_METHOD0(NumberOfPackets, size_t()); - ... -}; -``` - -Note that the mock class doesn't define `AppendPacket()`, unlike the -real class. That's fine as long as the test doesn't need to call it. - -Next, you need a way to say that you want to use -`ConcretePacketStream` in production code, and use `MockPacketStream` -in tests. Since the functions are not virtual and the two classes are -unrelated, you must specify your choice at _compile time_ (as opposed -to run time). - -One way to do it is to templatize your code that needs to use a packet -stream. More specifically, you will give your code a template type -argument for the type of the packet stream. In production, you will -instantiate your template with `ConcretePacketStream` as the type -argument. In tests, you will instantiate the same template with -`MockPacketStream`. For example, you may write: - -``` -template <class PacketStream> -void CreateConnection(PacketStream* stream) { ... } - -template <class PacketStream> -class PacketReader { - public: - void ReadPackets(PacketStream* stream, size_t packet_num); -}; -``` - -Then you can use `CreateConnection<ConcretePacketStream>()` and -`PacketReader<ConcretePacketStream>` in production code, and use -`CreateConnection<MockPacketStream>()` and -`PacketReader<MockPacketStream>` in tests. - -``` - MockPacketStream mock_stream; - EXPECT_CALL(mock_stream, ...)...; - .. set more expectations on mock_stream ... - PacketReader<MockPacketStream> reader(&mock_stream); - ... exercise reader ... -``` - -## Mocking Free Functions ## - -It's possible to use Google Mock to mock a free function (i.e. a -C-style function or a static method). You just need to rewrite your -code to use an interface (abstract class). - -Instead of calling a free function (say, `OpenFile`) directly, -introduce an interface for it and have a concrete subclass that calls -the free function: - -``` -class FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) = 0; -}; - -class File : public FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) { - return OpenFile(path, mode); - } -}; -``` - -Your code should talk to `FileInterface` to open a file. Now it's -easy to mock out the function. - -This may seem much hassle, but in practice you often have multiple -related functions that you can put in the same interface, so the -per-function syntactic overhead will be much lower. - -If you are concerned about the performance overhead incurred by -virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md). - -## The Nice, the Strict, and the Naggy ## - -If a mock method has no `EXPECT_CALL` spec but is called, Google Mock -will print a warning about the "uninteresting call". The rationale is: - - * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning. - -However, sometimes you may want to suppress all "uninteresting call" -warnings, while sometimes you may want the opposite, i.e. to treat all -of them as errors. Google Mock lets you make the decision on a -per-mock-object basis. - -Suppose your test uses a mock class `MockFoo`: - -``` -TEST(...) { - MockFoo mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -If a method of `mock_foo` other than `DoThis()` is called, it will be -reported by Google Mock as a warning. However, if you rewrite your -test to use `NiceMock<MockFoo>` instead, the warning will be gone, -resulting in a cleaner test output: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used -wherever `MockFoo` is accepted. - -It also works if `MockFoo`'s constructor takes some arguments, as -`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors: - -``` -using ::testing::NiceMock; - -TEST(...) { - NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -The usage of `StrictMock` is similar, except that it makes all -uninteresting calls failures: - -``` -using ::testing::StrictMock; - -TEST(...) { - StrictMock<MockFoo> mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... - - // The test will fail if a method of mock_foo other than DoThis() - // is called. -} -``` - -There are some caveats though (I don't like them just as much as the -next guy, but sadly they are side effects of C++'s limitations): - - 1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock<StrictMock<MockFoo> >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). - 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) - -Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort. - -## Simplifying the Interface without Breaking Existing Code ## - -Sometimes a method has a long list of arguments that is mostly -uninteresting. For example, - -``` -class LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) = 0; -}; -``` - -This method's argument list is lengthy and hard to work with (let's -say that the `message` argument is not even 0-terminated). If we mock -it as is, using the mock will be awkward. If, however, we try to -simplify this interface, we'll need to fix all clients depending on -it, which is often infeasible. - -The trick is to re-dispatch the method in the mock class: - -``` -class ScopedMockLog : public LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - Log(severity, full_filename, std::string(message, message_len)); - } - - // Implements the mock method: - // - // void Log(LogSeverity severity, - // const string& file_path, - // const string& message); - MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, - const string& message)); -}; -``` - -By defining a new mock method with a trimmed argument list, we make -the mock class much more user-friendly. - -## Alternative to Mocking Concrete Classes ## - -Often you may find yourself using classes that don't implement -interfaces. In order to test your code that uses such a class (let's -call it `Concrete`), you may be tempted to make the methods of -`Concrete` virtual and then mock it. - -Try not to do that. - -Making a non-virtual function virtual is a big decision. It creates an -extension point where subclasses can tweak your class' behavior. This -weakens your control on the class because now it's harder to maintain -the class' invariants. You should make a function virtual only when -there is a valid reason for a subclass to override it. - -Mocking concrete classes directly is problematic as it creates a tight -coupling between the class and the tests - any small change in the -class may invalidate your tests and make test maintenance a pain. - -To avoid such problems, many programmers have been practicing "coding -to interfaces": instead of talking to the `Concrete` class, your code -would define an interface and talk to it. Then you implement that -interface as an adaptor on top of `Concrete`. In tests, you can easily -mock that interface to observe how your code is doing. - -This technique incurs some overhead: - - * You pay the cost of virtual function calls (usually not a problem). - * There is more abstraction for the programmers to learn. - -However, it can also bring significant benefits in addition to better -testability: - - * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. - * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. - -Some people worry that if everyone is practicing this technique, they -will end up writing lots of redundant code. This concern is totally -understandable. However, there are two reasons why it may not be the -case: - - * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. - * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. - -You need to weigh the pros and cons carefully for your particular -problem, but I'd like to assure you that the Java community has been -practicing this for a long time and it's a proven effective technique -applicable in a wide variety of situations. :-) - -## Delegating Calls to a Fake ## - -Some times you have a non-trivial fake implementation of an -interface. For example: - -``` -class Foo { - public: - virtual ~Foo() {} - virtual char DoThis(int n) = 0; - virtual void DoThat(const char* s, int* p) = 0; -}; - -class FakeFoo : public Foo { - public: - virtual char DoThis(int n) { - return (n > 0) ? '+' : - (n < 0) ? '-' : '0'; - } - - virtual void DoThat(const char* s, int* p) { - *p = strlen(s); - } -}; -``` - -Now you want to mock this interface such that you can set expectations -on it. However, you also want to use `FakeFoo` for the default -behavior, as duplicating it in the mock object is, well, a lot of -work. - -When you define the mock class using Google Mock, you can have it -delegate its default action to a fake class you already have, using -this pattern: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - // Normal mock method definitions using Google Mock. - MOCK_METHOD1(DoThis, char(int n)); - MOCK_METHOD2(DoThat, void(const char* s, int* p)); - - // Delegates the default actions of the methods to a FakeFoo object. - // This must be called *before* the custom ON_CALL() statements. - void DelegateToFake() { - ON_CALL(*this, DoThis(_)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); - ON_CALL(*this, DoThat(_, _)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); - } - private: - FakeFoo fake_; // Keeps an instance of the fake in the mock. -}; -``` - -With that, you can use `MockFoo` in your tests as usual. Just remember -that if you don't explicitly set an action in an `ON_CALL()` or -`EXPECT_CALL()`, the fake will be called upon to do it: - -``` -using ::testing::_; - -TEST(AbcTest, Xyz) { - MockFoo foo; - foo.DelegateToFake(); // Enables the fake for delegation. - - // Put your ON_CALL(foo, ...)s here, if any. - - // No action specified, meaning to use the default action. - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(foo, DoThat(_, _)); - - int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. - foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); -} -``` - -**Some tips:** - - * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. - * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. - * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double) const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()` method.). - * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. - -Regarding the tip on mixing a mock and a fake, here's an example on -why it may be a bad sign: Suppose you have a class `System` for -low-level system operations. In particular, it does file and I/O -operations. And suppose you want to test how your code uses `System` -to do I/O, and you just want the file operations to work normally. If -you mock out the entire `System` class, you'll have to provide a fake -implementation for the file operation part, which suggests that -`System` is taking on too many roles. - -Instead, you can define a `FileOps` interface and an `IOOps` interface -and split `System`'s functionalities into the two. Then you can mock -`IOOps` without mocking `FileOps`. - -## Delegating Calls to a Real Object ## - -When using testing doubles (mocks, fakes, stubs, and etc), sometimes -their behaviors will differ from those of the real objects. This -difference could be either intentional (as in simulating an error such -that you can test the error handling code) or unintentional. If your -mocks have different behaviors than the real objects by mistake, you -could end up with code that passes the tests but fails in production. - -You can use the _delegating-to-real_ technique to ensure that your -mock has the same behavior as the real object while retaining the -ability to validate calls. This technique is very similar to the -delegating-to-fake technique, the difference being that we use a real -object instead of a fake. Here's an example: - -``` -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MockFoo() { - // By default, all calls are delegated to the real object. - ON_CALL(*this, DoThis()) - .WillByDefault(Invoke(&real_, &Foo::DoThis)); - ON_CALL(*this, DoThat(_)) - .WillByDefault(Invoke(&real_, &Foo::DoThat)); - ... - } - MOCK_METHOD0(DoThis, ...); - MOCK_METHOD1(DoThat, ...); - ... - private: - Foo real_; -}; -... - - MockFoo mock; - - EXPECT_CALL(mock, DoThis()) - .Times(3); - EXPECT_CALL(mock, DoThat("Hi")) - .Times(AtLeast(1)); - ... use mock in test ... -``` - -With this, Google Mock will verify that your code made the right calls -(with the right arguments, in the right order, called the right number -of times, etc), and a real object will answer the calls (so the -behavior will be the same as in production). This gives you the best -of both worlds. - -## Delegating Calls to a Parent Class ## - -Ideally, you should code to interfaces, whose methods are all pure -virtual. In reality, sometimes you do need to mock a virtual method -that is not pure (i.e, it already has an implementation). For example: - -``` -class Foo { - public: - virtual ~Foo(); - - virtual void Pure(int n) = 0; - virtual int Concrete(const char* str) { ... } -}; - -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); -}; -``` - -Sometimes you may want to call `Foo::Concrete()` instead of -`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub -action, or perhaps your test doesn't need to mock `Concrete()` at all -(but it would be oh-so painful to have to define a new mock class -whenever you don't need to mock one of its methods). - -The trick is to leave a back door in your mock class for accessing the -real methods in the base class: - -``` -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: - -``` -using ::testing::_; -using ::testing::Invoke; -... - EXPECT_CALL(foo, Concrete(_)) - .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -or tell the mock object that you don't want to mock `Concrete()`: - -``` -using ::testing::Invoke; -... - ON_CALL(foo, Concrete(_)) - .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do -that, `MockFoo::Concrete()` will be called (and cause an infinite -recursion) since `Foo::Concrete()` is virtual. That's just how C++ -works.) - -# Using Matchers # - -## Matching Argument Values Exactly ## - -You can specify exactly which arguments a mock method is expecting: - -``` -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(5)) - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", bar)); -``` - -## Using Simple Matchers ## - -You can use matchers to match arguments that have a certain property: - -``` -using ::testing::Ge; -using ::testing::NotNull; -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", NotNull())); - // The second argument must not be NULL. -``` - -A frequently used matcher is `_`, which matches anything: - -``` -using ::testing::_; -using ::testing::NotNull; -... - EXPECT_CALL(foo, DoThat(_, NotNull())); -``` - -## Combining Matchers ## - -You can build complex matchers from existing ones using `AllOf()`, -`AnyOf()`, and `Not()`: - -``` -using ::testing::AllOf; -using ::testing::Gt; -using ::testing::HasSubstr; -using ::testing::Ne; -using ::testing::Not; -... - // The argument must be > 5 and != 10. - EXPECT_CALL(foo, DoThis(AllOf(Gt(5), - Ne(10)))); - - // The first argument must not contain sub-string "blah". - EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), - NULL)); -``` - -## Casting Matchers ## - -Google Mock matchers are statically typed, meaning that the compiler -can catch your mistake if you use a matcher of the wrong type (for -example, if you use `Eq(5)` to match a `string` argument). Good for -you! - -Sometimes, however, you know what you're doing and want the compiler -to give you some slack. One example is that you have a matcher for -`long` and the argument you want to match is `int`. While the two -types aren't exactly the same, there is nothing really wrong with -using a `Matcher<long>` to match an `int` - after all, we can first -convert the `int` argument to a `long` before giving it to the -matcher. - -To support this need, Google Mock gives you the -`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type -`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the -type `m` accepts): - - 1. Type `T` can be implicitly cast to type `U`; - 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and - 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). - -The code won't compile if any of these conditions isn't met. - -Here's one example: - -``` -using ::testing::SafeMatcherCast; - -// A base class and a child class. -class Base { ... }; -class Derived : public Base { ... }; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(DoThis, void(Derived* derived)); -}; -... - - MockFoo foo; - // m is a Matcher<Base*> we got from somewhere. - EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m))); -``` - -If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar -function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works -as long as you can `static_cast` type `T` to type `U`. - -`MatcherCast` essentially lets you bypass C++'s type system -(`static_cast` isn't always safe as it could throw away information, -for example), so be careful not to misuse/abuse it. - -## Selecting Between Overloaded Functions ## - -If you expect an overloaded function to be called, the compiler may -need some help on which overloaded version it is. - -To disambiguate functions overloaded on the const-ness of this object, -use the `Const()` argument wrapper. - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - ... - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -... - - MockFoo foo; - Bar bar1, bar2; - EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). - .WillOnce(ReturnRef(bar1)); - EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). - .WillOnce(ReturnRef(bar2)); -``` - -(`Const()` is defined by Google Mock and returns a `const` reference -to its argument.) - -To disambiguate overloaded functions with the same number of arguments -but different argument types, you may need to specify the exact type -of a matcher, either by wrapping your matcher in `Matcher<type>()`, or -using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`, -etc): - -``` -using ::testing::An; -using ::testing::Lt; -using ::testing::Matcher; -using ::testing::TypedEq; - -class MockPrinter : public Printer { - public: - MOCK_METHOD1(Print, void(int n)); - MOCK_METHOD1(Print, void(char c)); -}; - -TEST(PrinterTest, Print) { - MockPrinter printer; - - EXPECT_CALL(printer, Print(An<int>())); // void Print(int); - EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int); - EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char); - - printer.Print(3); - printer.Print(6); - printer.Print('a'); -} -``` - -## Performing Different Actions Based on the Arguments ## - -When a mock method is called, the _last_ matching expectation that's -still active will be selected (think "newer overrides older"). So, you -can make a method do different things depending on its argument values -like this: - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Return; -... - // The default case. - EXPECT_CALL(foo, DoThis(_)) - .WillRepeatedly(Return('b')); - - // The more specific case. - EXPECT_CALL(foo, DoThis(Lt(5))) - .WillRepeatedly(Return('a')); -``` - -Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will -be returned; otherwise `'b'` will be returned. - -## Matching Multiple Arguments as a Whole ## - -Sometimes it's not enough to match the arguments individually. For -example, we may want to say that the first argument must be less than -the second argument. The `With()` clause allows us to match -all arguments of a mock function as a whole. For example, - -``` -using ::testing::_; -using ::testing::Lt; -using ::testing::Ne; -... - EXPECT_CALL(foo, InRange(Ne(0), _)) - .With(Lt()); -``` - -says that the first argument of `InRange()` must not be 0, and must be -less than the second argument. - -The expression inside `With()` must be a matcher of type -`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the -types of the function arguments. - -You can also write `AllArgs(m)` instead of `m` inside `.With()`. The -two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable -than `.With(Lt())`. - -You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments -(as a tuple) against `m`. For example, - -``` -using ::testing::_; -using ::testing::AllOf; -using ::testing::Args; -using ::testing::Lt; -... - EXPECT_CALL(foo, Blah(_, _, _)) - .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); -``` - -says that `Blah()` will be called with arguments `x`, `y`, and `z` where -`x < y < z`. - -As a convenience and example, Google Mock provides some matchers for -2-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_7_CheatSheet.md) for -the complete list. - -Note that if you want to pass the arguments to a predicate of your own -(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be -written to take a `tr1::tuple` as its argument; Google Mock will pass the `n` -selected arguments as _one_ single tuple to the predicate. - -## Using Matchers as Predicates ## - -Have you noticed that a matcher is just a fancy predicate that also -knows how to describe itself? Many existing algorithms take predicates -as arguments (e.g. those defined in STL's `<algorithm>` header), and -it would be a shame if Google Mock matchers are not allowed to -participate. - -Luckily, you can use a matcher where a unary predicate functor is -expected by wrapping it inside the `Matches()` function. For example, - -``` -#include <algorithm> -#include <vector> - -std::vector<int> v; -... -// How many elements in v are >= 10? -const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); -``` - -Since you can build complex matchers from simpler ones easily using -Google Mock, this gives you a way to conveniently construct composite -predicates (doing the same using STL's `<functional>` header is just -painful). For example, here's a predicate that's satisfied by any -number that is >= 0, <= 100, and != 50: - -``` -Matches(AllOf(Ge(0), Le(100), Ne(50))) -``` - -## Using Matchers in Google Test Assertions ## - -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in -[Google Test](http://code.google.com/p/googletest/) assertions. It's -called `ASSERT_THAT` and `EXPECT_THAT`: - -``` - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a Google Test test you can write: - -``` -#include "gmock/gmock.h" - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; -... - - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and -`Baz()`, and verifies that: - - * `Foo()` returns a string that starts with `"Hello"`. - * `Bar()` returns a string that matches regular expression `"Line \\d+"`. - * `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that _they read like -English_. They generate informative messages too. For example, if the -first `EXPECT_THAT()` above fails, the message will be something like: - -``` -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the -[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds -`assertThat()` to JUnit. - -## Using Predicates as Matchers ## - -Google Mock provides a built-in set of matchers. In case you find them -lacking, you can use an arbitray unary predicate function or functor -as a matcher - as long as the predicate accepts a value of the type -you want. You do this by wrapping the predicate inside the `Truly()` -function, for example: - -``` -using ::testing::Truly; - -int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } -... - - // Bar() must be called with an even number. - EXPECT_CALL(foo, Bar(Truly(IsEven))); -``` - -Note that the predicate function / functor doesn't have to return -`bool`. It works as long as the return value can be used as the -condition in statement `if (condition) ...`. - -## Matching Arguments that Are Not Copyable ## - -When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves -away a copy of `bar`. When `Foo()` is called later, Google Mock -compares the argument to `Foo()` with the saved copy of `bar`. This -way, you don't need to worry about `bar` being modified or destroyed -after the `EXPECT_CALL()` is executed. The same is true when you use -matchers like `Eq(bar)`, `Le(bar)`, and so on. - -But what if `bar` cannot be copied (i.e. has no copy constructor)? You -could define your own matcher function and use it with `Truly()`, as -the previous couple of recipes have shown. Or, you may be able to get -away from it if you can guarantee that `bar` won't be changed after -the `EXPECT_CALL()` is executed. Just tell Google Mock that it should -save a reference to `bar`, instead of a copy of it. Here's how: - -``` -using ::testing::Eq; -using ::testing::ByRef; -using ::testing::Lt; -... - // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); - - // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); -``` - -Remember: if you do this, don't change `bar` after the -`EXPECT_CALL()`, or the result is undefined. - -## Validating a Member of an Object ## - -Often a mock function takes a reference to object as an argument. When -matching the argument, you may not want to compare the entire object -against a fixed object, as that may be over-specification. Instead, -you may need to validate a certain member variable or the result of a -certain getter method of the object. You can do this with `Field()` -and `Property()`. More specifically, - -``` -Field(&Foo::bar, m) -``` - -is a matcher that matches a `Foo` object whose `bar` member variable -satisfies matcher `m`. - -``` -Property(&Foo::baz, m) -``` - -is a matcher that matches a `Foo` object whose `baz()` method returns -a value that satisfies matcher `m`. - -For example: - -> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | -|:-----------------------------|:-----------------------------------| -> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - -Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no -argument and be declared as `const`. - -BTW, `Field()` and `Property()` can also match plain pointers to -objects. For instance, - -``` -Field(&Foo::number, Ge(3)) -``` - -matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, -the match will always fail regardless of the inner matcher. - -What if you want to validate more than one members at the same time? -Remember that there is `AllOf()`. - -## Validating the Value Pointed to by a Pointer Argument ## - -C++ functions often take pointers as arguments. You can use matchers -like `IsNull()`, `NotNull()`, and other comparison matchers to match a -pointer, but what if you want to make sure the value _pointed to_ by -the pointer, instead of the pointer itself, has a certain property? -Well, you can use the `Pointee(m)` matcher. - -`Pointee(m)` matches a pointer iff `m` matches the value the pointer -points to. For example: - -``` -using ::testing::Ge; -using ::testing::Pointee; -... - EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); -``` - -expects `foo.Bar()` to be called with a pointer that points to a value -greater than or equal to 3. - -One nice thing about `Pointee()` is that it treats a `NULL` pointer as -a match failure, so you can write `Pointee(m)` instead of - -``` - AllOf(NotNull(), Pointee(m)) -``` - -without worrying that a `NULL` pointer will crash your test. - -Also, did we tell you that `Pointee()` works with both raw pointers -**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and -etc)? - -What if you have a pointer to pointer? You guessed it - you can use -nested `Pointee()` to probe deeper inside the value. For example, -`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer -that points to a number less than 3 (what a mouthful...). - -## Testing a Certain Property of an Object ## - -Sometimes you want to specify that an object argument has a certain -property, but there is no existing matcher that does this. If you want -good error messages, you should define a matcher. If you want to do it -quick and dirty, you could get away with writing an ordinary function. - -Let's say you have a mock function that takes an object of type `Foo`, -which has an `int bar()` method and an `int baz()` method, and you -want to constrain that the argument's `bar()` value plus its `baz()` -value is a given number. Here's how you can define a matcher to do it: - -``` -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> { - public: - explicit BarPlusBazEqMatcher(int expected_sum) - : expected_sum_(expected_sum) {} - - virtual bool MatchAndExplain(const Foo& foo, - MatchResultListener* listener) const { - return (foo.bar() + foo.baz()) == expected_sum_; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "bar() + baz() equals " << expected_sum_; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "bar() + baz() does not equal " << expected_sum_; - } - private: - const int expected_sum_; -}; - -inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); -} - -... - - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; -``` - -## Matching Containers ## - -Sometimes an STL container (e.g. list, vector, map, ...) is passed to -a mock function and you may want to validate it. Since most STL -containers support the `==` operator, you can write -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. - -Sometimes, though, you may want to be more flexible (for example, the -first element must be an exact match, but the second element can be -any positive number, and so on). Also, containers used in tests often -have a small number of elements, and having to define the expected -container out-of-line is a bit of a hassle. - -You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in -such cases: - -``` -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::Gt; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); -``` - -The above matcher says that the container must have 4 elements, which -must be 1, greater than 0, anything, and 5 respectively. - -If you instead write: - -``` -using ::testing::_; -using ::testing::Gt; -using ::testing::UnorderedElementsAre; -... - - MOCK_METHOD1(Foo, void(const vector<int>& numbers)); -... - - EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); -``` - -It means that the container must have 4 elements, which under some -permutation must be 1, greater than 0, anything, and 5 respectively. - -`ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0 -to 10 arguments. If more are needed, you can place them in a C-style -array and use `ElementsAreArray()` or `UnorderedElementsAreArray()` -instead: - -``` -using ::testing::ElementsAreArray; -... - - // ElementsAreArray accepts an array of element values. - const int expected_vector1[] = { 1, 5, 2, 4, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); - - // Or, an array of element matchers. - Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); -``` - -In case the array needs to be dynamically created (and therefore the -array size cannot be inferred by the compiler), you can give -`ElementsAreArray()` an additional argument to specify the array size: - -``` -using ::testing::ElementsAreArray; -... - int* const expected_vector3 = new int[count]; - ... fill expected_vector3 with values ... - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); -``` - -**Tips:** - - * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. - * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers. - * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. - * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). - -## Sharing Matchers ## - -Under the hood, a Google Mock matcher object consists of a pointer to -a ref-counted implementation object. Copying matchers is allowed and -very efficient, as only the pointer is copied. When the last matcher -that references the implementation object dies, the implementation -object will be deleted. - -Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it everytime. Just assign it to a -matcher variable and use that variable repeatedly! For example, - -``` - Matcher<int> in_range = AllOf(Gt(5), Le(10)); - ... use in_range as a matcher in multiple EXPECT_CALLs ... -``` - -# Setting Expectations # - -## Knowing When to Expect ## - -`ON_CALL` is likely the single most under-utilized construct in Google Mock. - -There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too). - -Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints. - -This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests? - -The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed. - -Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself. - -So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them). - -## Ignoring Uninteresting Calls ## - -If you are not interested in how a mock method is called, just don't -say anything about it. In this case, if the method is ever called, -Google Mock will perform its default action to allow the test program -to continue. If you are not happy with the default action taken by -Google Mock, you can override it using `DefaultValue<T>::Set()` -(described later in this document) or `ON_CALL()`. - -Please note that once you expressed interest in a particular mock -method (via `EXPECT_CALL()`), all invocations to it must match some -expectation. If this function is called but the arguments don't match -any `EXPECT_CALL()` statement, it will be an error. - -## Disallowing Unexpected Calls ## - -If a mock method shouldn't be called at all, explicitly say so: - -``` -using ::testing::_; -... - EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -If some calls to the method are allowed, but the rest are not, just -list all the expected calls: - -``` -using ::testing::AnyNumber; -using ::testing::Gt; -... - EXPECT_CALL(foo, Bar(5)); - EXPECT_CALL(foo, Bar(Gt(10))) - .Times(AnyNumber()); -``` - -A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` -statements will be an error. - -## Expecting Ordered Calls ## - -Although an `EXPECT_CALL()` statement defined earlier takes precedence -when Google Mock tries to match a function call with an expectation, -by default calls don't have to happen in the order `EXPECT_CALL()` -statements are written. For example, if the arguments match the -matchers in the third `EXPECT_CALL()`, but not those in the first two, -then the third expectation will be used. - -If you would rather have all calls occur in the order of the -expectations, put the `EXPECT_CALL()` statements in a block where you -define a variable of type `InSequence`: - -``` - using ::testing::_; - using ::testing::InSequence; - - { - InSequence s; - - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(bar, DoThat(_)) - .Times(2); - EXPECT_CALL(foo, DoThis(6)); - } -``` - -In this example, we expect a call to `foo.DoThis(5)`, followed by two -calls to `bar.DoThat()` where the argument can be anything, which are -in turn followed by a call to `foo.DoThis(6)`. If a call occurred -out-of-order, Google Mock will report an error. - -## Expecting Partially Ordered Calls ## - -Sometimes requiring everything to occur in a predetermined order can -lead to brittle tests. For example, we may care about `A` occurring -before both `B` and `C`, but aren't interested in the relative order -of `B` and `C`. In this case, the test should reflect our real intent, -instead of being overly constraining. - -Google Mock allows you to impose an arbitrary DAG (directed acyclic -graph) on the calls. One way to express the DAG is to use the -[After](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#The_After_Clause) clause of `EXPECT_CALL`. - -Another way is via the `InSequence()` clause (not the same as the -`InSequence` class), which we borrowed from jMock 2. It's less -flexible than `After()`, but more convenient when you have long chains -of sequential calls, as it doesn't require you to come up with -different names for the expectations in the chains. Here's how it -works: - -If we view `EXPECT_CALL()` statements as nodes in a graph, and add an -edge from node A to node B wherever A must occur before B, we can get -a DAG. We use the term "sequence" to mean a directed path in this -DAG. Now, if we decompose the DAG into sequences, we just need to know -which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the orginal DAG. - -So, to specify the partial order on the expectations we need to do two -things: first to define some `Sequence` objects, and then for each -`EXPECT_CALL()` say which `Sequence` objects it is part -of. Expectations in the same sequence must occur in the order they are -written. For example, - -``` - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(foo, A()) - .InSequence(s1, s2); - EXPECT_CALL(bar, B()) - .InSequence(s1); - EXPECT_CALL(bar, C()) - .InSequence(s2); - EXPECT_CALL(foo, D()) - .InSequence(s2); -``` - -specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> -C -> D`): - -``` - +---> B - | - A ---| - | - +---> C ---> D -``` - -This means that A must occur before B and C, and C must occur before -D. There's no restriction about the order other than these. - -## Controlling When an Expectation Retires ## - -When a mock method is called, Google Mock only consider expectations -that are still active. An expectation is active when created, and -becomes inactive (aka _retires_) when a call that has to occur later -has occurred. For example, in - -``` - using ::testing::_; - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 - .Times(AnyNumber()) - .InSequence(s1, s2); - EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 - .InSequence(s1); - EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 - .InSequence(s2); -``` - -as soon as either #2 or #3 is matched, #1 will retire. If a warning -`"File too large."` is logged after this, it will be an error. - -Note that an expectation doesn't retire automatically when it's -saturated. For example, - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 -``` - -says that there will be exactly one warning with the message `"File -too large."`. If the second warning contains this message too, #2 will -match again and result in an upper-bound-violated error. - -If this is not what you want, you can ask an expectation to retire as -soon as it becomes saturated: - -``` -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 - .RetiresOnSaturation(); -``` - -Here #2 can be used only once, so if you have two warnings with the -message `"File too large."`, the first will match #2 and the second -will match #1 - there will be no error. - -# Using Actions # - -## Returning References from Mock Methods ## - -If a mock function's return type is a reference, you need to use -`ReturnRef()` instead of `Return()` to return a result: - -``` -using ::testing::ReturnRef; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetBar, Bar&()); -}; -... - - MockFoo foo; - Bar bar; - EXPECT_CALL(foo, GetBar()) - .WillOnce(ReturnRef(bar)); -``` - -## Returning Live Values from Mock Methods ## - -The `Return(x)` action saves a copy of `x` when the action is -_created_, and always returns the same value whenever it's -executed. Sometimes you may want to instead return the _live_ value of -`x` (i.e. its value at the time when the action is _executed_.). - -If the mock function's return type is a reference, you can do it using -`ReturnRef(x)`, as shown in the previous recipe ("Returning References -from Mock Methods"). However, Google Mock doesn't let you use -`ReturnRef()` in a mock function whose return type is not a reference, -as doing that usually indicates a user error. So, what shall you do? - -You may be tempted to try `ByRef()`: - -``` -using testing::ByRef; -using testing::Return; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetValue, int()); -}; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(Return(ByRef(x))); - x = 42; - EXPECT_EQ(42, foo.GetValue()); -``` - -Unfortunately, it doesn't work here. The above code will fail with error: - -``` -Value of: foo.GetValue() - Actual: 0 -Expected: 42 -``` - -The reason is that `Return(value)` converts `value` to the actual -return type of the mock function at the time when the action is -_created_, not when it is _executed_. (This behavior was chosen for -the action to be safe when `value` is a proxy object that references -some temporary objects.) As a result, `ByRef(x)` is converted to an -`int` value (instead of a `const int&`) when the expectation is set, -and `Return(ByRef(x))` will always return 0. - -`ReturnPointee(pointer)` was provided to solve this problem -specifically. It returns the value pointed to by `pointer` at the time -the action is _executed_: - -``` -using testing::ReturnPointee; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(ReturnPointee(&x)); // Note the & here. - x = 42; - EXPECT_EQ(42, foo.GetValue()); // This will succeed now. -``` - -## Combining Actions ## - -Want to do more than one thing when a function is called? That's -fine. `DoAll()` allow you to do sequence of actions every time. Only -the return value of the last action in the sequence will be used. - -``` -using ::testing::DoAll; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Bar, bool(int n)); -}; -... - - EXPECT_CALL(foo, Bar(_)) - .WillOnce(DoAll(action_1, - action_2, - ... - action_n)); -``` - -## Mocking Side Effects ## - -Sometimes a method exhibits its effect not via returning a value but -via side effects. For example, it may change some global state or -modify an output argument. To mock side effects, in general you can -define your own action by implementing `::testing::ActionInterface`. - -If all you need to do is to change an output argument, the built-in -`SetArgPointee()` action is convenient: - -``` -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - MOCK_METHOD2(Mutate, void(bool mutate, int* value)); - ... -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, Mutate(true, _)) - .WillOnce(SetArgPointee<1>(5)); -``` - -In this example, when `mutator.Mutate()` is called, we will assign 5 -to the `int` variable pointed to by argument #1 -(0-based). - -`SetArgPointee()` conveniently makes an internal copy of the -value you pass to it, removing the need to keep the value in scope and -alive. The implication however is that the value must have a copy -constructor and assignment operator. - -If the mock method also needs to return a value as well, you can chain -`SetArgPointee()` with `Return()` using `DoAll()`: - -``` -using ::testing::_; -using ::testing::Return; -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - ... - MOCK_METHOD1(MutateInt, bool(int* value)); -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, MutateInt(_)) - .WillOnce(DoAll(SetArgPointee<0>(5), - Return(true))); -``` - -If the output argument is an array, use the -`SetArrayArgument<N>(first, last)` action instead. It copies the -elements in source range `[first, last)` to the array pointed to by -the `N`-th (0-based) argument: - -``` -using ::testing::NotNull; -using ::testing::SetArrayArgument; - -class MockArrayMutator : public ArrayMutator { - public: - MOCK_METHOD2(Mutate, void(int* values, int num_values)); - ... -}; -... - - MockArrayMutator mutator; - int values[5] = { 1, 2, 3, 4, 5 }; - EXPECT_CALL(mutator, Mutate(NotNull(), 5)) - .WillOnce(SetArrayArgument<0>(values, values + 5)); -``` - -This also works when the argument is an output iterator: - -``` -using ::testing::_; -using ::testing::SeArrayArgument; - -class MockRolodex : public Rolodex { - public: - MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >)); - ... -}; -... - - MockRolodex rolodex; - vector<string> names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); - EXPECT_CALL(rolodex, GetNames(_)) - .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); -``` - -## Changing a Mock Object's Behavior Based on the State ## - -If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: - -``` -using ::testing::InSequence; -using ::testing::Return; - -... - { - InSequence seq; - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(true)); - EXPECT_CALL(my_mock, Flush()); - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(false)); - } - my_mock.FlushIfDirty(); -``` - -This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. - -If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: - -``` -using ::testing::_; -using ::testing::SaveArg; -using ::testing::Return; - -ACTION_P(ReturnPointee, p) { return *p; } -... - int previous_value = 0; - EXPECT_CALL(my_mock, GetPrevValue()) - .WillRepeatedly(ReturnPointee(&previous_value)); - EXPECT_CALL(my_mock, UpdateValue(_)) - .WillRepeatedly(SaveArg<0>(&previous_value)); - my_mock.DoSomethingToUpdateValue(); -``` - -Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. - -## Setting the Default Value for a Return Type ## - -If a mock method's return type is a built-in C++ type or pointer, by -default it will return 0 when invoked. You only need to specify an -action if this default value doesn't work for you. - -Sometimes, you may want to change this default value, or you may want -to specify a default value for types Google Mock doesn't know -about. You can do this using the `::testing::DefaultValue` class -template: - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD0(CalculateBar, Bar()); -}; -... - - Bar default_bar; - // Sets the default return value for type Bar. - DefaultValue<Bar>::Set(default_bar); - - MockFoo foo; - - // We don't need to specify an action here, as the default - // return value works for us. - EXPECT_CALL(foo, CalculateBar()); - - foo.CalculateBar(); // This should return default_bar. - - // Unsets the default return value. - DefaultValue<Bar>::Clear(); -``` - -Please note that changing the default value for a type can make you -tests hard to understand. We recommend you to use this feature -judiciously. For example, you may want to make sure the `Set()` and -`Clear()` calls are right next to the code that uses your mock. - -## Setting the Default Actions for a Mock Method ## - -You've learned how to change the default value of a given -type. However, this may be too coarse for your purpose: perhaps you -have two mock methods with the same return type and you want them to -have different behaviors. The `ON_CALL()` macro allows you to -customize your mock's behavior at the method level: - -``` -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Gt; -using ::testing::Return; -... - ON_CALL(foo, Sign(_)) - .WillByDefault(Return(-1)); - ON_CALL(foo, Sign(0)) - .WillByDefault(Return(0)); - ON_CALL(foo, Sign(Gt(0))) - .WillByDefault(Return(1)); - - EXPECT_CALL(foo, Sign(_)) - .Times(AnyNumber()); - - foo.Sign(5); // This should return 1. - foo.Sign(-9); // This should return -1. - foo.Sign(0); // This should return 0. -``` - -As you may have guessed, when there are more than one `ON_CALL()` -statements, the news order take precedence over the older ones. In -other words, the **last** one that matches the function arguments will -be used. This matching order allows you to set up the common behavior -in a mock object's constructor or the test fixture's set-up phase and -specialize the mock's behavior later. - -## Using Functions/Methods/Functors as Actions ## - -If the built-in actions don't suit you, you can easily use an existing -function, method, or functor as an action: - -``` -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(Sum, int(int x, int y)); - MOCK_METHOD1(ComplexJob, bool(int x)); -}; - -int CalculateSum(int x, int y) { return x + y; } - -class Helper { - public: - bool ComplexJob(int x); -}; -... - - MockFoo foo; - Helper helper; - EXPECT_CALL(foo, Sum(_, _)) - .WillOnce(Invoke(CalculateSum)); - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); - - foo.Sum(5, 6); // Invokes CalculateSum(5, 6). - foo.ComplexJob(10); // Invokes helper.ComplexJob(10); -``` - -The only requirement is that the type of the function, etc must be -_compatible_ with the signature of the mock function, meaning that the -latter's arguments can be implicitly converted to the corresponding -arguments of the former, and the former's return type can be -implicitly converted to that of the latter. So, you can invoke -something whose type is _not_ exactly the same as the mock function, -as long as it's safe to do so - nice, huh? - -## Invoking a Function/Method/Functor Without Arguments ## - -`Invoke()` is very useful for doing actions that are more complex. It -passes the mock function's arguments to the function or functor being -invoked such that the callee has the full context of the call to work -with. If the invoked function is not interested in some or all of the -arguments, it can simply ignore them. - -Yet, a common pattern is that a test author wants to invoke a function -without the arguments of the mock function. `Invoke()` allows her to -do that using a wrapper function that throws away the arguments before -invoking an underlining nullary function. Needless to say, this can be -tedious and obscures the intent of the test. - -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except -that it doesn't pass the mock function's arguments to the -callee. Here's an example: - -``` -using ::testing::_; -using ::testing::InvokeWithoutArgs; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(ComplexJob, bool(int n)); -}; - -bool Job1() { ... } -... - - MockFoo foo; - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)); - - foo.ComplexJob(10); // Invokes Job1(). -``` - -## Invoking an Argument of the Mock Function ## - -Sometimes a mock function will receive a function pointer or a functor -(in other words, a "callable") as an argument, e.g. - -``` -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); -}; -``` - -and you may want to invoke this callable argument: - -``` -using ::testing::_; -... - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(...); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -Arghh, you need to refer to a mock function argument but C++ has no -lambda (yet), so you have to define your own action. :-( Or do you -really? - -Well, Google Mock has an action to solve _exactly_ this problem: - -``` - InvokeArgument<N>(arg_1, arg_2, ..., arg_m) -``` - -will invoke the `N`-th (0-based) argument the mock function receives, -with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is -a function pointer or a functor, Google Mock handles them both. - -With that, you could write: - -``` -using ::testing::_; -using ::testing::InvokeArgument; -... - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(InvokeArgument<1>(5)); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -What if the callable takes an argument by reference? No problem - just -wrap it inside `ByRef()`: - -``` -... - MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); -... -using ::testing::_; -using ::testing::ByRef; -using ::testing::InvokeArgument; -... - - MockFoo foo; - Helper helper; - ... - EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callable. -``` - -What if the callable takes an argument by reference and we do **not** -wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a -copy_ of the argument, and pass a _reference to the copy_, instead of -a reference to the original value, to the callable. This is especially -handy when the argument is a temporary value: - -``` -... - MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); -... -using ::testing::_; -using ::testing::InvokeArgument; -... - - MockFoo foo; - ... - EXPECT_CALL(foo, DoThat(_)) - .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); - // Will execute (*f)(5.0, string("Hi")), where f is the function pointer - // DoThat() receives. Note that the values 5.0 and string("Hi") are - // temporary and dead once the EXPECT_CALL() statement finishes. Yet - // it's fine to perform this action later, since a copy of the values - // are kept inside the InvokeArgument action. -``` - -## Ignoring an Action's Result ## - -Sometimes you have an action that returns _something_, but you need an -action that returns `void` (perhaps you want to use it in a mock -function that returns `void`, or perhaps it needs to be used in -`DoAll()` and it's not the last in the list). `IgnoreResult()` lets -you do that. For example: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -int Process(const MyData& data); -string DoSomething(); - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Abc, void(const MyData& data)); - MOCK_METHOD0(Xyz, bool()); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, Abc(_)) - // .WillOnce(Invoke(Process)); - // The above line won't compile as Process() returns int but Abc() needs - // to return void. - .WillOnce(IgnoreResult(Invoke(Process))); - - EXPECT_CALL(foo, Xyz()) - .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), - // Ignores the string DoSomething() returns. - Return(true))); -``` - -Note that you **cannot** use `IgnoreResult()` on an action that already -returns `void`. Doing so will lead to ugly compiler errors. - -## Selecting an Action's Arguments ## - -Say you have a mock function `Foo()` that takes seven arguments, and -you have a custom action that you want to invoke when `Foo()` is -called. Trouble is, the custom action only wants three arguments: - -``` -using ::testing::_; -using ::testing::Invoke; -... - MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight)); -... - -bool IsVisibleInQuadrant1(bool visible, int x, int y) { - return visible && x >= 0 && y >= 0; -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( -``` - -To please the compiler God, you can to define an "adaptor" that has -the same signature as `Foo()` and calls the custom action with the -right arguments: - -``` -using ::testing::_; -using ::testing::Invoke; - -bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, - const map<pair<int, int>, double>& weight, - double min_weight, double max_wight) { - return IsVisibleInQuadrant1(visible, x, y); -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. -``` - -But isn't this awkward? - -Google Mock provides a generic _action adaptor_, so you can spend your -time minding more important business than writing your own -adaptors. Here's the syntax: - -``` - WithArgs<N1, N2, ..., Nk>(action) -``` - -creates an action that passes the arguments of the mock function at -the given indices (0-based) to the inner `action` and performs -it. Using `WithArgs`, our original example can be written as: - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::WithArgs; -... - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); - // No need to define your own adaptor. -``` - -For better readability, Google Mock also gives you: - - * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and - * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. - -As you may have realized, `InvokeWithoutArgs(...)` is just syntactic -sugar for `WithoutArgs(Inovke(...))`. - -Here are more tips: - - * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. - * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. - * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. - * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. - -## Ignoring Arguments in Action Functions ## - -The selecting-an-action's-arguments recipe showed us one way to make a -mock function and an action with incompatible argument lists fit -together. The downside is that wrapping the action in -`WithArgs<...>()` can get tedious for people writing the tests. - -If you are defining a function, method, or functor to be used with -`Invoke*()`, and you are not interested in some of its arguments, an -alternative to `WithArgs` is to declare the uninteresting arguments as -`Unused`. This makes the definition less cluttered and less fragile in -case the types of the uninteresting arguments change. It could also -increase the chance the action function can be reused. For example, -given - -``` - MOCK_METHOD3(Foo, double(const string& label, double x, double y)); - MOCK_METHOD3(Bar, double(int index, double x, double y)); -``` - -instead of - -``` -using ::testing::_; -using ::testing::Invoke; - -double DistanceToOriginWithLabel(const string& label, double x, double y) { - return sqrt(x*x + y*y); -} - -double DistanceToOriginWithIndex(int index, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOriginWithLabel)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOriginWithIndex)); -``` - -you could write - -``` -using ::testing::_; -using ::testing::Invoke; -using ::testing::Unused; - -double DistanceToOrigin(Unused, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOrigin)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOrigin)); -``` - -## Sharing Actions ## - -Just like matchers, a Google Mock action object consists of a pointer -to a ref-counted implementation object. Therefore copying actions is -also allowed and very efficient. When the last action that references -the implementation object dies, the implementation object will be -deleted. - -If you have some complex action that you want to use again and again, -you may not have to build it from scratch everytime. If the action -doesn't have an internal state (i.e. if it always does the same thing -no matter how many times it has been called), you can assign it to an -action variable and use that variable repeatedly. For example: - -``` - Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5), - Return(true)); - ... use set_flag in .WillOnce() and .WillRepeatedly() ... -``` - -However, if the action has its own state, you may be surprised if you -share the action object. Suppose you have an action factory -`IncrementCounter(init)` which creates an action that increments and -returns a counter whose initial value is `init`, using two actions -created from the same expression and using a shared action will -exihibit different behaviors. Example: - -``` - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(IncrementCounter(0)); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(IncrementCounter(0)); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. -``` - -versus - -``` - Action<int()> increment = IncrementCounter(0); - - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(increment); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(increment); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 3 - the counter is shared. -``` - -# Misc Recipes on Using Google Mock # - -## Making the Compilation Faster ## - -Believe it or not, the _vast majority_ of the time spent on compiling -a mock class is in generating its constructor and destructor, as they -perform non-trivial tasks (e.g. verification of the -expectations). What's more, mock methods with different signatures -have different types and thus their constructors/destructors need to -be generated by the compiler separately. As a result, if you mock many -different types of methods, compiling your mock class can get really -slow. - -If you are experiencing slow compilation, you can move the definition -of your mock class' constructor and destructor out of the class body -and into a `.cpp` file. This way, even if you `#include` your mock -class in N files, the compiler only needs to generate its constructor -and destructor once, resulting in a much faster compilation. - -Let's illustrate the idea using an example. Here's the definition of a -mock class before applying this recipe: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // Since we don't declare the constructor or the destructor, - // the compiler will generate them in every translation unit - // where this mock class is used. - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` - -After the change, it would look like: - -``` -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // The constructor and destructor are declared, but not defined, here. - MockFoo(); - virtual ~MockFoo(); - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` -and -``` -// File mock_foo.cpp. -#include "path/to/mock_foo.h" - -// The definitions may appear trivial, but the functions actually do a -// lot of things through the constructors/destructors of the member -// variables used to implement the mock methods. -MockFoo::MockFoo() {} -MockFoo::~MockFoo() {} -``` - -## Forcing a Verification ## - -When it's being destoyed, your friendly mock object will automatically -verify that all expectations on it have been satisfied, and will -generate [Google Test](http://code.google.com/p/googletest/) failures -if not. This is convenient as it leaves you with one less thing to -worry about. That is, unless you are not sure if your mock object will -be destoyed. - -How could it be that your mock object won't eventually be destroyed? -Well, it might be created on the heap and owned by the code you are -testing. Suppose there's a bug in that code and it doesn't delete the -mock object properly - you could end up with a passing test when -there's actually a bug. - -Using a heap checker is a good idea and can alleviate the concern, but -its implementation may not be 100% reliable. So, sometimes you do want -to _force_ Google Mock to verify a mock object before it is -(hopefully) destructed. You can do this with -`Mock::VerifyAndClearExpectations(&mock_object)`: - -``` -TEST(MyServerTest, ProcessesRequest) { - using ::testing::Mock; - - MockFoo* const foo = new MockFoo; - EXPECT_CALL(*foo, ...)...; - // ... other expectations ... - - // server now owns foo. - MyServer server(foo); - server.ProcessRequest(...); - - // In case that server's destructor will forget to delete foo, - // this will verify the expectations anyway. - Mock::VerifyAndClearExpectations(foo); -} // server is destroyed when it goes out of scope here. -``` - -**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a -`bool` to indicate whether the verification was successful (`true` for -yes), so you can wrap that function call inside a `ASSERT_TRUE()` if -there is no point going further when the verification has failed. - -## Using Check Points ## - -Sometimes you may want to "reset" a mock object at various check -points in your test: at each check point, you verify that all existing -expectations on the mock object have been satisfied, and then you set -some new expectations on it as if it's newly created. This allows you -to work with a mock object in "phases" whose sizes are each -manageable. - -One such scenario is that in your test's `SetUp()` function, you may -want to put the object you are testing into a certain state, with the -help from a mock object. Once in the desired state, you want to clear -all expectations on the mock, such that in the `TEST_F` body you can -set fresh expectations on it. - -As you may have figured out, the `Mock::VerifyAndClearExpectations()` -function we saw in the previous recipe can help you here. Or, if you -are using `ON_CALL()` to set default actions on the mock object and -want to clear the default actions as well, use -`Mock::VerifyAndClear(&mock_object)` instead. This function does what -`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the -same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. - -Another trick you can use to achieve the same effect is to put the -expectations in sequences and insert calls to a dummy "check-point" -function at specific places. Then you can verify that the mock -function calls do happen at the right time. For example, if you are -exercising code: - -``` -Foo(1); -Foo(2); -Foo(3); -``` - -and want to verify that `Foo(1)` and `Foo(3)` both invoke -`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: - -``` -using ::testing::MockFunction; - -TEST(FooTest, InvokesBarCorrectly) { - MyMock mock; - // Class MockFunction<F> has exactly one mock method. It is named - // Call() and has type F. - MockFunction<void(string check_point_name)> check; - { - InSequence s; - - EXPECT_CALL(mock, Bar("a")); - EXPECT_CALL(check, Call("1")); - EXPECT_CALL(check, Call("2")); - EXPECT_CALL(mock, Bar("a")); - } - Foo(1); - check.Call("1"); - Foo(2); - check.Call("2"); - Foo(3); -} -``` - -The expectation spec says that the first `Bar("a")` must happen before -check point "1", the second `Bar("a")` must happen after check point "2", -and nothing should happen between the two check points. The explicit -check points make it easy to tell which `Bar("a")` is called by which -call to `Foo()`. - -## Mocking Destructors ## - -Sometimes you want to make sure a mock object is destructed at the -right time, e.g. after `bar->A()` is called but before `bar->B()` is -called. We already know that you can specify constraints on the order -of mock function calls, so all we need to do is to mock the destructor -of the mock function. - -This sounds simple, except for one problem: a destructor is a special -function with special syntax and special semantics, and the -`MOCK_METHOD0` macro doesn't work for it: - -``` - MOCK_METHOD0(~MockFoo, void()); // Won't compile! -``` - -The good news is that you can use a simple pattern to achieve the same -effect. First, add a mock function `Die()` to your mock class and call -it in the destructor, like this: - -``` -class MockFoo : public Foo { - ... - // Add the following two lines to the mock class. - MOCK_METHOD0(Die, void()); - virtual ~MockFoo() { Die(); } -}; -``` - -(If the name `Die()` clashes with an existing symbol, choose another -name.) Now, we have translated the problem of testing when a `MockFoo` -object dies to testing when its `Die()` method is called: - -``` - MockFoo* foo = new MockFoo; - MockBar* bar = new MockBar; - ... - { - InSequence s; - - // Expects *foo to die after bar->A() and before bar->B(). - EXPECT_CALL(*bar, A()); - EXPECT_CALL(*foo, Die()); - EXPECT_CALL(*bar, B()); - } -``` - -And that's that. - -## Using Google Mock and Threads ## - -**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on -platforms where Google Mock is thread-safe. Currently these are only -platforms that support the pthreads library (this includes Linux and Mac). -To make it thread-safe on other platforms we only need to implement -some synchronization operations in `"gtest/internal/gtest-port.h"`. - -In a **unit** test, it's best if you could isolate and test a piece of -code in a single-threaded context. That avoids race conditions and -dead locks, and makes debugging your test much easier. - -Yet many programs are multi-threaded, and sometimes to test something -we need to pound on it from more than one thread. Google Mock works -for this purpose too. - -Remember the steps for using a mock: - - 1. Create a mock object `foo`. - 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. - 1. The code under test calls methods of `foo`. - 1. Optionally, verify and reset the mock. - 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. - -If you follow the following simple rules, your mocks and threads can -live happily togeter: - - * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. - * Obviously, you can do step #1 without locking. - * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? - * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. - -If you violate the rules (for example, if you set expectations on a -mock while another thread is calling its methods), you get undefined -behavior. That's not fun, so don't do it. - -Google Mock guarantees that the action for a mock function is done in -the same thread that called the mock function. For example, in - -``` - EXPECT_CALL(mock, Foo(1)) - .WillOnce(action1); - EXPECT_CALL(mock, Foo(2)) - .WillOnce(action2); -``` - -if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, -Google Mock will execute `action1` in thread 1 and `action2` in thread -2. - -Google Mock does _not_ impose a sequence on actions performed in -different threads (doing so may create deadlocks as the actions may -need to cooperate). This means that the execution of `action1` and -`action2` in the above example _may_ interleave. If this is a problem, -you should add proper synchronization logic to `action1` and `action2` -to make the test thread-safe. - - -Also, remember that `DefaultValue<T>` is a global resource that -potentially affects _all_ living mock objects in your -program. Naturally, you won't want to mess with it from multiple -threads or when there still are mocks in action. - -## Controlling How Much Information Google Mock Prints ## - -When Google Mock sees something that has the potential of being an -error (e.g. a mock function with no expectation is called, a.k.a. an -uninteresting call, which is allowed but perhaps you forgot to -explicitly ban the call), it prints some warning messages, including -the arguments of the function and the return value. Hopefully this -will remind you to take a look and see if there is indeed a problem. - -Sometimes you are confident that your tests are correct and may not -appreciate such friendly messages. Some other times, you are debugging -your tests or learning about the behavior of the code you are testing, -and wish you could observe every mock call that happens (including -argument values and the return value). Clearly, one size doesn't fit -all. - -You can control how much Google Mock tells you using the -`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string -with three possible values: - - * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. - * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. - * `error`: Google Mock will print errors only (least verbose). - -Alternatively, you can adjust the value of that flag from within your -tests like so: - -``` - ::testing::FLAGS_gmock_verbose = "error"; -``` - -Now, judiciously use the right flag to enable Google Mock serve you better! - -## Gaining Super Vision into Mock Calls ## - -You have a test using Google Mock. It fails: Google Mock tells you -that some expectations aren't satisfied. However, you aren't sure why: -Is there a typo somewhere in the matchers? Did you mess up the order -of the `EXPECT_CALL`s? Or is the code under test doing something -wrong? How can you find out the cause? - -Won't it be nice if you have X-ray vision and can actually see the -trace of all `EXPECT_CALL`s and mock method calls as they are made? -For each call, would you like to see its actual argument values and -which `EXPECT_CALL` Google Mock thinks it matches? - -You can unlock this power by running your test with the -`--gmock_verbose=info` flag. For example, given the test program: - -``` -using testing::_; -using testing::HasSubstr; -using testing::Return; - -class MockFoo { - public: - MOCK_METHOD2(F, void(const string& x, const string& y)); -}; - -TEST(Foo, Bar) { - MockFoo mock; - EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); - EXPECT_CALL(mock, F("a", "b")); - EXPECT_CALL(mock, F("c", HasSubstr("d"))); - - mock.F("a", "good"); - mock.F("a", "b"); -} -``` - -if you run it with `--gmock_verbose=info`, you will see this output: - -``` -[ RUN ] Foo.Bar - -foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked -foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked -foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked -foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... - Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good") -foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... - Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b") -foo_test.cc:16: Failure -Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... - Expected: to be called once - Actual: never called - unsatisfied and active -[ FAILED ] Foo.Bar -``` - -Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo -and should actually be `"a"`. With the above message, you should see -that the actual `F("a", "good")` call is matched by the first -`EXPECT_CALL`, not the third as you thought. From that it should be -obvious that the third `EXPECT_CALL` is written wrong. Case solved. - -## Running Tests in Emacs ## - -If you build and run your tests in Emacs, the source file locations of -Google Mock and [Google Test](http://code.google.com/p/googletest/) -errors will be highlighted. Just press `<Enter>` on one of them and -you'll be taken to the offending line. Or, you can just type `C-x `` -to jump to the next error. - -To make it even easier, you can add the following lines to your -`~/.emacs` file: - -``` -(global-set-key "\M-m" 'compile) ; m is for make -(global-set-key [M-down] 'next-error) -(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) -``` - -Then you can type `M-m` to start a build, or `M-up`/`M-down` to move -back and forth between errors. - -## Fusing Google Mock Source Files ## - -Google Mock's implementation consists of dozens of files (excluding -its own tests). Sometimes you may want them to be packaged up in -fewer files 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_gmock_files.py` in the `scripts/` directory -(starting with release 1.2.0). Assuming you have Python 2.4 or above -installed on your machine, just go to that directory and run -``` -python fuse_gmock_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. -These three files contain everything you need to use Google Mock (and -Google Test). Just copy them to anywhere you want and you are ready -to write tests and use mocks. You can use the -[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests -against them. - -# Extending Google Mock # - -## Writing New Matchers Quickly ## - -The `MATCHER*` family of macros can be used to define custom matchers -easily. The syntax: - -``` -MATCHER(name, description_string_expression) { statements; } -``` - -will define a matcher with the given name that executes the -statements, which must return a `bool` to indicate if the match -succeeds. Inside the statements, you can refer to the value being -matched by `arg`, and refer to its type by `arg_type`. - -The description string is a `string`-typed expression that documents -what the matcher does, and is used to generate the failure message -when the match fails. It can (and should) reference the special -`bool` variable `negation`, and should evaluate to the description of -the matcher when `negation` is `false`, or that of the matcher's -negation when `negation` is `true`. - -For convenience, we allow the description string to be empty (`""`), -in which case Google Mock will use the sequence of words in the -matcher name as the description. - -For example: -``` -MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } -``` -allows you to write -``` - // Expects mock_foo.Bar(n) to be called where n is divisible by 7. - EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); -``` -or, -``` -using ::testing::Not; -... - EXPECT_THAT(some_expression, IsDivisibleBy7()); - EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); -``` -If the above assertions fail, they will print something like: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 -... - Value of: some_other_expression - Expected: not (is divisible by 7) - Actual: 21 -``` -where the descriptions `"is divisible by 7"` and `"not (is divisible -by 7)"` are automatically calculated from the matcher name -`IsDivisibleBy7`. - -As you may have noticed, the auto-generated descriptions (especially -those for the negation) may not be so great. You can always override -them with a string expression of your own: -``` -MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + - " divisible by 7") { - return (arg % 7) == 0; -} -``` - -Optionally, you can stream additional information to a hidden argument -named `result_listener` to explain the match result. For example, a -better definition of `IsDivisibleBy7` is: -``` -MATCHER(IsDivisibleBy7, "") { - if ((arg % 7) == 0) - return true; - - *result_listener << "the remainder is " << (arg % 7); - return false; -} -``` - -With this definition, the above assertion will give a better message: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 (the remainder is 6) -``` - -You should let `MatchAndExplain()` print _any additional information_ -that can help a user understand the match result. Note that it should -explain why the match succeeds in case of a success (unless it's -obvious) - this is useful when the matcher is used inside -`Not()`. There is no need to print the argument value itself, as -Google Mock already prints it for you. - -**Notes:** - - 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. - 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. - -## Writing New Parameterized Matchers Quickly ## - -Sometimes you'll want to define a matcher that has parameters. For that you -can use the macro: -``` -MATCHER_P(name, param_name, description_string) { statements; } -``` -where the description string can be either `""` or a string expression -that references `negation` and `param_name`. - -For example: -``` -MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -``` -will allow you to write: -``` - EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -``` -which may lead to this message (assuming `n` is 10): -``` - Value of: Blah("a") - Expected: has absolute value 10 - Actual: -9 -``` - -Note that both the matcher description and its parameter are -printed, making the message human-friendly. - -In the matcher definition body, you can write `foo_type` to -reference the type of a parameter named `foo`. For example, in the -body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write -`value_type` to refer to the type of `value`. - -Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to -`MATCHER_P10` to support multi-parameter matchers: -``` -MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } -``` - -Please note that the custom description string is for a particular -**instance** of the matcher, where the parameters have been bound to -actual values. Therefore usually you'll want the parameter values to -be part of the description. Google Mock lets you do that by -referencing the matcher parameters in the description string -expression. - -For example, -``` - using ::testing::PrintToString; - MATCHER_P2(InClosedRange, low, hi, - std::string(negation ? "isn't" : "is") + " in range [" + - PrintToString(low) + ", " + PrintToString(hi) + "]") { - return low <= arg && arg <= hi; - } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the message: -``` - Expected: is in range [4, 6] -``` - -If you specify `""` as the description, the failure message will -contain the sequence of words in the matcher name followed by the -parameter values printed as a tuple. For example, -``` - MATCHER_P2(InClosedRange, low, hi, "") { ... } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the text: -``` - Expected: in closed range (4, 6) -``` - -For the purpose of typing, you can view -``` -MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -``` -as shorthand for -``` -template <typename p1_type, ..., typename pk_type> -FooMatcherPk<p1_type, ..., pk_type> -Foo(p1_type p1, ..., pk_type pk) { ... } -``` - -When you write `Foo(v1, ..., vk)`, the compiler infers the types of -the parameters `v1`, ..., and `vk` for you. If you are not happy with -the result of the type inference, you can specify the types by -explicitly instantiating the template, as in `Foo<long, bool>(5, false)`. -As said earlier, you don't get to (or need to) specify -`arg_type` as that's determined by the context in which the matcher -is used. - -You can assign the result of expression `Foo(p1, ..., pk)` to a -variable of type `FooMatcherPk<p1_type, ..., pk_type>`. This can be -useful when composing matchers. Matchers that don't have a parameter -or have only one parameter have special types: you can assign `Foo()` -to a `FooMatcher`-typed variable, and assign `Foo(p)` to a -`FooMatcherP<p_type>`-typed variable. - -While you can instantiate a matcher template with reference types, -passing the parameters by pointer usually makes your code more -readable. If, however, you still want to pass a parameter by -reference, be aware that in the failure message generated by the -matcher you will see the value of the referenced object but not its -address. - -You can overload matchers with different numbers of parameters: -``` -MATCHER_P(Blah, a, description_string_1) { ... } -MATCHER_P2(Blah, a, b, description_string_2) { ... } -``` - -While it's tempting to always use the `MATCHER*` macros when defining -a new matcher, you should also consider implementing -`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see -the recipes that follow), especially if you need to use the matcher a -lot. While these approaches require more work, they give you more -control on the types of the value being matched and the matcher -parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers -based on parameter types (as opposed to just based on the number of -parameters). - -## Writing New Monomorphic Matchers ## - -A matcher of argument type `T` implements -`::testing::MatcherInterface<T>` and does two things: it tests whether a -value of type `T` matches the matcher, and can describe what kind of -values it matches. The latter ability is used for generating readable -error messages when expectations are violated. - -The interface looks like this: - -``` -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template <typename T> - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - ::std::ostream* stream(); -}; - -template <typename T> -class MatcherInterface { - public: - virtual ~MatcherInterface(); - - // Returns true iff the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; -}; -``` - -If you need a custom matcher but `Truly()` is not a good option (for -example, you may not be happy with the way `Truly(predicate)` -describes itself, or you may want your matcher to be polymorphic as -`Eq(value)` is), you can define a matcher to do whatever you want in -two steps: first implement the matcher interface, and then define a -factory function to create a matcher instance. The second step is not -strictly needed but it makes the syntax of using the matcher nicer. - -For example, you can define a matcher to test whether an `int` is -divisible by 7 and then use it like this: -``` -using ::testing::MakeMatcher; -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { - return (n % 7) == 0; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "is divisible by 7"; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "is not divisible by 7"; - } -}; - -inline Matcher<int> DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); -} -... - - EXPECT_CALL(foo, Bar(DivisibleBy7())); -``` - -You may improve the matcher message by streaming additional -information to the `listener` argument in `MatchAndExplain()`: - -``` -class DivisibleBy7Matcher : public MatcherInterface<int> { - public: - virtual bool MatchAndExplain(int n, - MatchResultListener* listener) const { - const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; - } - return remainder == 0; - } - ... -}; -``` - -Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: -``` -Value of: x -Expected: is divisible by 7 - Actual: 23 (the remainder is 2) -``` - -## Writing New Polymorphic Matchers ## - -You've learned how to write your own matchers in the previous -recipe. Just one problem: a matcher created using `MakeMatcher()` only -works for one particular type of arguments. If you want a -_polymorphic_ matcher that works with arguments of several types (for -instance, `Eq(x)` can be used to match a `value` as long as `value` == -`x` compiles -- `value` and `x` don't have to share the same type), -you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit -involved. - -Fortunately, most of the time you can define a polymorphic matcher -easily with the help of `MakePolymorphicMatcher()`. Here's how you can -define `NotNull()` as an example: - -``` -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -using ::testing::NotNull; -using ::testing::PolymorphicMatcher; - -class NotNullMatcher { - public: - // To implement a polymorphic matcher, first define a COPYABLE class - // that has three members MatchAndExplain(), DescribeTo(), and - // DescribeNegationTo(), like the following. - - // In this example, we want to use NotNull() with any pointer, so - // MatchAndExplain() accepts a pointer of any type as its first argument. - // In general, you can define MatchAndExplain() as an ordinary method or - // a method template, or even overload it. - template <typename T> - bool MatchAndExplain(T* p, - MatchResultListener* /* listener */) const { - return p != NULL; - } - - // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } - - // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } -}; - -// To construct a polymorphic matcher, pass an instance of the class -// to MakePolymorphicMatcher(). Note the return type. -inline PolymorphicMatcher<NotNullMatcher> NotNull() { - return MakePolymorphicMatcher(NotNullMatcher()); -} -... - - EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. -``` - -**Note:** Your polymorphic matcher class does **not** need to inherit from -`MatcherInterface` or any other class, and its methods do **not** need -to be virtual. - -Like in a monomorphic matcher, you may explain the match result by -streaming additional information to the `listener` argument in -`MatchAndExplain()`. - -## Writing New Cardinalities ## - -A cardinality is used in `Times()` to tell Google Mock how many times -you expect a call to occur. It doesn't have to be exact. For example, -you can say `AtLeast(5)` or `Between(2, 4)`. - -If the built-in set of cardinalities doesn't suit you, you are free to -define your own by implementing the following interface (in namespace -`testing`): - -``` -class CardinalityInterface { - public: - virtual ~CardinalityInterface(); - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; -``` - -For example, to specify that a call must occur even number of times, -you can write - -``` -using ::testing::Cardinality; -using ::testing::CardinalityInterface; -using ::testing::MakeCardinality; - -class EvenNumberCardinality : public CardinalityInterface { - public: - virtual bool IsSatisfiedByCallCount(int call_count) const { - return (call_count % 2) == 0; - } - - virtual bool IsSaturatedByCallCount(int call_count) const { - return false; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "called even number of times"; - } -}; - -Cardinality EvenNumber() { - return MakeCardinality(new EvenNumberCardinality); -} -... - - EXPECT_CALL(foo, Bar(3)) - .Times(EvenNumber()); -``` - -## Writing New Actions Quickly ## - -If the built-in actions don't work for you, and you find it -inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` -family to quickly define a new action that can be used in your code as -if it's a built-in action. - -By writing -``` -ACTION(name) { statements; } -``` -in a namespace scope (i.e. not inside a class or function), you will -define an action with the given name that executes the statements. -The value returned by `statements` will be used as the return value of -the action. Inside the statements, you can refer to the K-th -(0-based) argument of the mock function as `argK`. For example: -``` -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -``` -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments. Rest assured that your code is type-safe though: -you'll get a compiler error if `*arg1` doesn't support the `++` -operator, or if the type of `++(*arg1)` isn't compatible with the mock -function's return type. - -Another example: -``` -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -``` -int DoSomething(bool flag, int* ptr); -``` -we have: -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `std::tr1::tuple<bool, int*>` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Writing New Parameterized Actions Quickly ## - -Sometimes you'll want to parameterize an action you define. For that -we have another macro -``` -ACTION_P(name, param) { statements; } -``` - -For example, -``` -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -``` -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. For example, in the body of -`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. - -Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -``` -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -``` -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -You can also easily define actions overloaded on the number of parameters: -``` -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -## Restricting the Type of an Argument or Parameter in an ACTION ## - -For maximum brevity and reusability, the `ACTION*` macros don't ask -you to provide the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -``` -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq<const char*, arg1_type>(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion in Google Test -that verifies two types are the same. - -## Writing New Action Templates Quickly ## - -Sometimes you want to give an action explicit template parameters that -cannot be inferred from its value parameters. `ACTION_TEMPLATE()` -supports that and can be viewed as an extension to `ACTION()` and -`ACTION_P*()`. - -The syntax: -``` -ACTION_TEMPLATE(ActionName, - HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), - AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -``` - -defines an action template that takes _m_ explicit template parameters -and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is -between 0 and 10. `name_i` is the name of the i-th template -parameter, and `kind_i` specifies whether it's a `typename`, an -integral constant, or a template. `p_i` is the name of the i-th value -parameter. - -Example: -``` -// DuplicateArg<k, T>(output) converts the k-th argument of the mock -// function to type T and copies it to *output. -ACTION_TEMPLATE(DuplicateArg, - // Note the comma between int and k: - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(output)) { - *output = T(std::tr1::get<k>(args)); -} -``` - -To create an instance of an action template, write: -``` - ActionName<t1, ..., t_m>(v1, ..., v_n) -``` -where the `t`s are the template arguments and the -`v`s are the value arguments. The value argument -types are inferred by the compiler. For example: -``` -using ::testing::_; -... - int n; - EXPECT_CALL(mock, Foo(_, _)) - .WillOnce(DuplicateArg<1, unsigned char>(&n)); -``` - -If you want to explicitly specify the value argument types, you can -provide additional template arguments: -``` - ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) -``` -where `u_i` is the desired type of `v_i`. - -`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the -number of value parameters, but not on the number of template -parameters. Without the restriction, the meaning of the following is -unclear: - -``` - OverloadedAction<int, bool>(x); -``` - -Are we using a single-template-parameter action where `bool` refers to -the type of `x`, or a two-template-parameter action where the compiler -is asked to infer the type of `x`? - -## Using the ACTION Object's Type ## - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` | -| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of value -parameters, or the action definitions cannot be overloaded on the -number of them. - -## Writing New Monomorphic Actions ## - -While the `ACTION*` macros are very convenient, sometimes they are -inappropriate. For example, despite the tricks shown in the previous -recipes, they don't let you directly specify the types of the mock -function arguments and the action parameters, which in general leads -to unoptimized compiler error messages that can baffle unfamiliar -users. They also don't allow overloading actions based on parameter -types without jumping through some hoops. - -An alternative to the `ACTION*` macros is to implement -`::testing::ActionInterface<F>`, where `F` is the type of the mock -function in which the action will be used. For example: - -``` -template <typename F>class ActionInterface { - public: - virtual ~ActionInterface(); - - // Performs the action. Result is the return type of function type - // F, and ArgumentTuple is the tuple of arguments of F. - // - // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>. - virtual Result Perform(const ArgumentTuple& args) = 0; -}; - -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::MakeAction; - -typedef int IncrementMethod(int*); - -class IncrementArgumentAction : public ActionInterface<IncrementMethod> { - public: - virtual int Perform(const tr1::tuple<int*>& args) { - int* p = tr1::get<0>(args); // Grabs the first argument. - return *p++; - } -}; - -Action<IncrementMethod> IncrementArgument() { - return MakeAction(new IncrementArgumentAction); -} -... - - EXPECT_CALL(foo, Baz(_)) - .WillOnce(IncrementArgument()); - - int n = 5; - foo.Baz(&n); // Should return 5 and change n to 6. -``` - -## Writing New Polymorphic Actions ## - -The previous recipe showed you how to define your own action. This is -all good, except that you need to know the type of the function in -which the action will be used. Sometimes that can be a problem. For -example, if you want to use the action in functions with _different_ -types (e.g. like `Return()` and `SetArgPointee()`). - -If an action can be used in several types of mock functions, we say -it's _polymorphic_. The `MakePolymorphicAction()` function template -makes it easy to define such an action: - -``` -namespace testing { - -template <typename Impl> -PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl); - -} // namespace testing -``` - -As an example, let's define an action that returns the second argument -in the mock function's argument list. The first step is to define an -implementation class: - -``` -class ReturnSecondArgumentAction { - public: - template <typename Result, typename ArgumentTuple> - Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use tr1::get<i>(args). - return tr1::get<1>(args); - } -}; -``` - -This implementation class does _not_ need to inherit from any -particular class. What matters is that it must have a `Perform()` -method template. This method template takes the mock function's -arguments as a tuple in a **single** argument, and returns the result of -the action. It can be either `const` or not, but must be invokable -with exactly one template argument, which is the result type. In other -words, you must be able to call `Perform<R>(args)` where `R` is the -mock function's return type and `args` is its arguments in a tuple. - -Next, we use `MakePolymorphicAction()` to turn an instance of the -implementation class into the polymorphic action we need. It will be -convenient to have a wrapper for this: - -``` -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; - -PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() { - return MakePolymorphicAction(ReturnSecondArgumentAction()); -} -``` - -Now, you can use this polymorphic action the same way you use the -built-in ones: - -``` -using ::testing::_; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, int(bool flag, int n)); - MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(ReturnSecondArgument()); - EXPECT_CALL(foo, DoThat(_, _, _)) - .WillOnce(ReturnSecondArgument()); - ... - foo.DoThis(true, 5); // Will return 5. - foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". -``` - -## Teaching Google Mock How to Print Your Values ## - -When an uninteresting or unexpected call occurs, Google Mock prints the -argument values and the stack trace to help you debug. Assertion -macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in -question when the assertion fails. Google Mock and Google Test do this using -Google Test's 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. -[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/AdvancedGuide#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. \ No newline at end of file diff --git a/googlemock/docs/v1_7/Documentation.md b/googlemock/docs/v1_7/Documentation.md deleted file mode 100644 index d9181f28..00000000 --- a/googlemock/docs/v1_7/Documentation.md +++ /dev/null @@ -1,12 +0,0 @@ -This page lists all documentation wiki pages for Google Mock **(the SVN trunk version)** -- **if you use a released version of Google Mock, please read the documentation for that specific version instead.** - - * [ForDummies](V1_7_ForDummies.md) -- start here if you are new to Google Mock. - * [CheatSheet](V1_7_CheatSheet.md) -- a quick reference. - * [CookBook](V1_7_CookBook.md) -- recipes for doing various tasks using Google Mock. - * [FrequentlyAskedQuestions](V1_7_FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Mock, read: - - * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [Pump Manual](http://code.google.com/p/googletest/wiki/PumpManual) -- how we generate some of Google Mock's source files. \ No newline at end of file diff --git a/googlemock/docs/v1_7/ForDummies.md b/googlemock/docs/v1_7/ForDummies.md deleted file mode 100644 index ee03c5b9..00000000 --- a/googlemock/docs/v1_7/ForDummies.md +++ /dev/null @@ -1,439 +0,0 @@ - - -(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](http://code.google.com/p/googlemock/wiki/V1_7_FrequentlyAskedQuestions#How_am_I_supposed_to_make_sense_of_these_horrible_template_error).) - -# What Is Google C++ Mocking Framework? # -When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). - -**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: - - * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. - * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. - -If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. - -**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. - -Using Google Mock involves three basic steps: - - 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; - 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; - 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. - -# Why Google Mock? # -While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distance to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad hoc restrictions. - * The knowledge you gained from using one mock doesn't transfer to the next. - -In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. - -Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: - - * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". - * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). - * Your tests are brittle as some resources they use are unreliable (e.g. the network). - * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. - * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. - * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. - -We encourage you to use Google Mock as: - - * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! - * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. - -# Getting Started # -Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. - -# A Case for Mock Turtles # -Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: - -``` -class Turtle { - ... - virtual ~Turtle() {} - virtual void PenUp() = 0; - virtual void PenDown() = 0; - virtual void Forward(int distance) = 0; - virtual void Turn(int degrees) = 0; - virtual void GoTo(int x, int y) = 0; - virtual int GetX() const = 0; - virtual int GetY() const = 0; -}; -``` - -(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) - -You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. - -Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. - -# Writing the Mock Class # -If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) - -## How to Define It ## -Using the `Turtle` interface as example, here are the simple steps you need to follow: - - 1. Derive a class `MockTurtle` from `Turtle`. - 1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods), it's much more involved). Count how many arguments it has. - 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. - 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). - 1. Repeat until all virtual functions you want to mock are done. - -After the process, you should have something like: - -``` -#include "gmock/gmock.h" // Brings in Google Mock. -class MockTurtle : public Turtle { - public: - ... - MOCK_METHOD0(PenUp, void()); - MOCK_METHOD0(PenDown, void()); - MOCK_METHOD1(Forward, void(int distance)); - MOCK_METHOD1(Turn, void(int degrees)); - MOCK_METHOD2(GoTo, void(int x, int y)); - MOCK_CONST_METHOD0(GetX, int()); - MOCK_CONST_METHOD0(GetY, int()); -}; -``` - -You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. - -**Tip:** If even this is too much work for you, you'll find the -`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line -tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, -and it will print the definition of the mock class for you. Due to the -complexity of the C++ language, this script may not always work, but -it can be quite handy when it does. For more details, read the [user documentation](http://code.google.com/p/googlemock/source/browse/trunk/scripts/generator/README). - -## Where to Put It ## -When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) - -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. - -Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - -# Using Mocks in Tests # -Once you have a mock class, using it is easy. The typical work flow is: - - 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). - 1. Create some mock objects. - 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). - 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. - 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. - -Here's an example: - -``` -#include "path/to/mock-turtle.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" -using ::testing::AtLeast; // #1 - -TEST(PainterTest, CanDrawSomething) { - MockTurtle turtle; // #2 - EXPECT_CALL(turtle, PenDown()) // #3 - .Times(AtLeast(1)); - - Painter painter(&turtle); // #4 - - EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); -} // #5 - -int main(int argc, char** argv) { - // The following line must be executed to initialize Google Mock - // (and Google Test) before running the tests. - ::testing::InitGoogleMock(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: - -``` -path/to/my_test.cc:119: Failure -Actual function call count doesn't match this expectation: -Actually: never called; -Expected: called at least once. -``` - -**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on the line number displayed in the error message to jump right to the failed expectation. - -**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. - -**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. - -This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. - -Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. - -## Using Google Mock with Any Testing Framework ## -If you want to use something other than Google Test (e.g. [CppUnit](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) or -[CxxTest](http://cxxtest.tigris.org/)) as your testing framework, just change the `main()` function in the previous section to: -``` -int main(int argc, char** argv) { - // The following line causes Google Mock to throw an exception on failure, - // which will be interpreted by your testing framework as a test failure. - ::testing::GTEST_FLAG(throw_on_failure) = true; - ::testing::InitGoogleMock(&argc, argv); - ... whatever your testing framework requires ... -} -``` - -This approach has a catch: it makes Google Mock throw an exception -from a mock object's destructor sometimes. With some compilers, this -sometimes causes the test program to crash. You'll still be able to -notice that the test has failed, but it's not a graceful failure. - -A better solution is to use Google Test's -[event listener API](http://code.google.com/p/googletest/wiki/AdvancedGuide#Extending_Google_Test_by_Handling_Test_Events) -to report a test failure to your testing framework properly. You'll need to -implement the `OnTestPartResult()` method of the event listener interface, but it -should be straightforward. - -If this turns out to be too much work, we suggest that you stick with -Google Test, which works with Google Mock seamlessly (in fact, it is -technically part of Google Mock.). If there is a reason that you -cannot use Google Test, please let us know. - -# Setting Expectations # -The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." - -## General Syntax ## -In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: - -``` -EXPECT_CALL(mock_object, method(matchers)) - .Times(cardinality) - .WillOnce(action) - .WillRepeatedly(action); -``` - -The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) - -The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. - -This syntax is designed to make an expectation read like English. For example, you can probably guess that - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .Times(5) - .WillOnce(Return(100)) - .WillOnce(Return(150)) - .WillRepeatedly(Return(200)); -``` - -says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). - -**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. - -## Matchers: What Arguments Do We Expect? ## -When a mock function takes arguments, we must specify what arguments we are expecting; for example: - -``` -// Expects the turtle to move forward by 100 units. -EXPECT_CALL(turtle, Forward(100)); -``` - -Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": - -``` -using ::testing::_; -... -// Expects the turtle to move forward. -EXPECT_CALL(turtle, Forward(_)); -``` - -`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. - -A list of built-in matchers can be found in the [CheatSheet](V1_7_CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: - -``` -using ::testing::Ge;... -EXPECT_CALL(turtle, Forward(Ge(100))); -``` - -This checks that the turtle will be told to go forward by at least 100 units. - -## Cardinalities: How Many Times Will It Be Called? ## -The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. - -An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. - -We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](V1_7_CheatSheet.md). - -The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: - - * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. - * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. - * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. - -**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? - -## Actions: What Should It Do? ## -Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. - -First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). If you don't say anything, this behavior will be used. - -Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillOnce(Return(300)); -``` - -This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillRepeatedly(Return(300)); -``` - -says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. - -Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). - -What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#Actions). - -**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: - -``` -int n = 100; -EXPECT_CALL(turtle, GetX()) -.Times(4) -.WillRepeatedly(Return(n++)); -``` - -Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](V1_7_CookBook.md). - -Time for another quiz! What do you think the following means? - -``` -using ::testing::Return;... -EXPECT_CALL(turtle, GetY()) -.Times(4) -.WillOnce(Return(100)); -``` - -Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. - -## Using Multiple Expectations ## -So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. - -By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: - -``` -using ::testing::_;... -EXPECT_CALL(turtle, Forward(_)); // #1 -EXPECT_CALL(turtle, Forward(10)) // #2 - .Times(2); -``` - -If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. - -**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. - -## Ordered vs Unordered Calls ## -By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. - -Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: - -``` -using ::testing::InSequence;... -TEST(FooTest, DrawsLineSegment) { - ... - { - InSequence dummy; - - EXPECT_CALL(turtle, PenDown()); - EXPECT_CALL(turtle, Forward(100)); - EXPECT_CALL(turtle, PenUp()); - } - Foo(); -} -``` - -By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. - -In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. - -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](V1_7_CookBook#Expecting_Partially_Ordered_Calls.md).) - -## All Expectations Are Sticky (Unless Said Otherwise) ## -Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? - -After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): - -``` -using ::testing::_;... -EXPECT_CALL(turtle, GoTo(_, _)) // #1 - .Times(AnyNumber()); -EXPECT_CALL(turtle, GoTo(0, 0)) // #2 - .Times(2); -``` - -Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. - -This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). - -Simple? Let's see if you've really understood it: what does the following code say? - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)); -} -``` - -If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! - -One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: - -``` -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); -} -``` - -And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: - -``` -using ::testing::InSequence; -using ::testing::Return; -... -{ - InSequence s; - - for (int i = 1; i <= n; i++) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); - } -} -``` - -By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). - -## Uninteresting Calls ## -A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. - -In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. - -# What Now? # -Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. - -Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](V1_7_CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. \ No newline at end of file diff --git a/googlemock/docs/v1_7/FrequentlyAskedQuestions.md b/googlemock/docs/v1_7/FrequentlyAskedQuestions.md deleted file mode 100644 index fa21233a..00000000 --- a/googlemock/docs/v1_7/FrequentlyAskedQuestions.md +++ /dev/null @@ -1,628 +0,0 @@ - - -Please send your questions to the -[googlemock](http://groups.google.com/group/googlemock) discussion -group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first. - -## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## - -In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Nonvirtual_Methods). - -## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## - -After version 1.4.0 of Google Mock was released, we had an idea on how -to make it easier to write matchers that can generate informative -messages efficiently. We experimented with this idea and liked what -we saw. Therefore we decided to implement it. - -Unfortunately, this means that if you have defined your own matchers -by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, -your definitions will no longer compile. Matchers defined using the -`MATCHER*` family of macros are not affected. - -Sorry for the hassle if your matchers are affected. We believe it's -in everyone's long-term interest to make this change sooner than -later. Fortunately, it's usually not hard to migrate an existing -matcher to the new API. Here's what you need to do: - -If you wrote your matcher like this: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` - -you'll need to change it to: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` -(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second -argument of type `MatchResultListener*`.) - -If you were also using `ExplainMatchResultTo()` to improve the matcher -message: -``` -// Old matcher definition that doesn't work with the lastest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - - virtual void ExplainMatchResultTo(MyType value, - ::std::ostream* os) const { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Foo property is " << value.GetFoo(); - } - ... -}; -``` - -you should move the logic of `ExplainMatchResultTo()` into -`MatchAndExplain()`, using the `MatchResultListener` argument where -the `::std::ostream` was used: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface<MyType> { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Foo property is " << value.GetFoo(); - return value.GetFoo() > 5; - } - ... -}; -``` - -If your matcher is defined using `MakePolymorphicMatcher()`: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you should rename the `Matches()` method to `MatchAndExplain()` and -add a `MatchResultListener*` argument (the same as what you need to do -for matchers defined by implementing `MatcherInterface`): -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -If your polymorphic matcher uses `ExplainMatchResultTo()` for better -failure messages: -``` -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -void ExplainMatchResultTo(const MyGreatMatcher& matcher, - MyType value, - ::std::ostream* os) { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Bar property is " << value.GetBar(); -} -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you'll need to move the logic inside `ExplainMatchResultTo()` to -`MatchAndExplain()`: -``` -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Bar property is " << value.GetBar(); - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -For more information, you can read these -[two](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Monomorphic_Matchers) -[recipes](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Matchers) -from the cookbook. As always, you -are welcome to post questions on `googlemock@googlegroups.com` if you -need any help. - -## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## - -Google Mock works out of the box with Google Test. However, it's easy -to configure it to work with any testing framework of your choice. -[Here](http://code.google.com/p/googlemock/wiki/V1_7_ForDummies#Using_Google_Mock_with_Any_Testing_Framework) is how. - -## How am I supposed to make sense of these horrible template errors? ## - -If you are confused by the compiler errors gcc threw at you, -try consulting the _Google Mock Doctor_ tool first. What it does is to -scan stdin for gcc error messages, and spit out diagnoses on the -problems (we call them diseases) your code has. - -To "install", run command: -``` -alias gmd='<path to googlemock>/scripts/gmock_doctor.py' -``` - -To use it, do: -``` -<your-favorite-build-command> <your-test> 2>&1 | gmd -``` - -For example: -``` -make my_test 2>&1 | gmd -``` - -Or you can run `gmd` and copy-n-paste gcc's error messages to it. - -## Can I mock a variadic function? ## - -You cannot mock a variadic function (i.e. a function taking ellipsis -(`...`) arguments) directly in Google Mock. - -The problem is that in general, there is _no way_ for a mock object to -know how many arguments are passed to the variadic method, and what -the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into his head. - -Therefore, to mock such a function, the _user_ must teach the mock -object how to figure out the number of arguments and their types. One -way to do it is to provide overloaded versions of the function. - -Ellipsis arguments are inherited from C and not really a C++ feature. -They are unsafe to use and don't work with arguments that have -constructors or destructors. Therefore we recommend to avoid them in -C++ as much as possible. - -## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## - -If you compile this using Microsoft Visual C++ 2005 SP1: -``` -class Foo { - ... - virtual void Bar(const int i) = 0; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Bar, void(const int i)); -}; -``` -You may get the following warning: -``` -warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier -``` - -This is a MSVC bug. The same code compiles fine with gcc ,for -example. If you use Visual C++ 2008 SP1, you would get the warning: -``` -warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers -``` - -In C++, if you _declare_ a function with a `const` parameter, the -`const` modifier is _ignored_. Therefore, the `Foo` base class above -is equivalent to: -``` -class Foo { - ... - virtual void Bar(int i) = 0; // int or const int? Makes no difference. -}; -``` - -In fact, you can _declare_ Bar() with an `int` parameter, and _define_ -it with a `const int` parameter. The compiler will still match them -up. - -Since making a parameter `const` is meaningless in the method -_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. -That should workaround the VC bug. - -Note that we are talking about the _top-level_ `const` modifier here. -If the function parameter is passed by pointer or reference, declaring -the _pointee_ or _referee_ as `const` is still meaningful. For -example, the following two declarations are _not_ equivalent: -``` -void Bar(int* p); // Neither p nor *p is const. -void Bar(const int* p); // p is not const, but *p is. -``` - -## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## - -We've noticed that when the `/clr` compiler flag is used, Visual C++ -uses 5~6 times as much memory when compiling a mock class. We suggest -to avoid `/clr` when compiling native C++ mocks. - -## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## - -You might want to run your test with -`--gmock_verbose=info`. This flag lets Google Mock print a trace -of every mock function call it receives. By studying the trace, -you'll gain insights on why the expectations you set are not met. - -## How can I assert that a function is NEVER called? ## - -``` -EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## - -When Google Mock detects a failure, it prints relevant information -(the mock function arguments, the state of relevant expectations, and -etc) to help the user debug. If another failure is detected, Google -Mock will do the same, including printing the state of relevant -expectations. - -Sometimes an expectation's state didn't change between two failures, -and you'll see the same description of the state twice. They are -however _not_ redundant, as they refer to _different points in time_. -The fact they are the same _is_ interesting information. - -## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## - -Does the class (hopefully a pure interface) you are mocking have a -virtual destructor? - -Whenever you derive from a base class, make sure its destructor is -virtual. Otherwise Bad Things will happen. Consider the following -code: - -``` -class Base { - public: - // Not virtual, but should be. - ~Base() { ... } - ... -}; - -class Derived : public Base { - public: - ... - private: - std::string value_; -}; - -... - Base* p = new Derived; - ... - delete p; // Surprise! ~Base() will be called, but ~Derived() will not - // - value_ is leaked. -``` - -By changing `~Base()` to virtual, `~Derived()` will be correctly -called when `delete p` is executed, and the heap checker -will be happy. - -## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## - -When people complain about this, often they are referring to code like: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. However, I have to write the expectations in the -// reverse order. This sucks big time!!! -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); -``` - -The problem is that they didn't pick the **best** way to express the test's -intent. - -By default, expectations don't have to be matched in _any_ particular -order. If you want them to match in a certain order, you need to be -explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's -easy to accidentally over-specify your tests, and we want to make it -harder to do so. - -There are two better ways to write the test spec. You could either -put the expectations in sequence: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. Using a sequence, we can write the expectations -// in their natural order. -{ - InSequence s; - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -} -``` - -or you can put the sequence of actions in the same expectation: - -``` -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -``` - -Back to the original questions: why does Google Mock search the -expectations (and `ON_CALL`s) from back to front? Because this -allows a user to set up a mock's behavior for the common case early -(e.g. in the mock's constructor or the test fixture's set-up phase) -and customize it with more specific rules later. If Google Mock -searches from front to back, this very useful pattern won't be -possible. - -## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## - -When choosing between being neat and being safe, we lean toward the -latter. So the answer is that we think it's better to show the -warning. - -Often people write `ON_CALL`s in the mock object's -constructor or `SetUp()`, as the default behavior rarely changes from -test to test. Then in the test body they set the expectations, which -are often different for each test. Having an `ON_CALL` in the set-up -part of a test doesn't mean that the calls are expected. If there's -no `EXPECT_CALL` and the method is called, it's possibly an error. If -we quietly let the call go through without notifying the user, bugs -may creep in unnoticed. - -If, however, you are sure that the calls are OK, you can write - -``` -EXPECT_CALL(foo, Bar(_)) - .WillRepeatedly(...); -``` - -instead of - -``` -ON_CALL(foo, Bar(_)) - .WillByDefault(...); -``` - -This tells Google Mock that you do expect the calls and no warning should be -printed. - -Also, you can control the verbosity using the `--gmock_verbose` flag. -If you find the output too noisy when debugging, just choose a less -verbose level. - -## How can I delete the mock function's argument in an action? ## - -If you find yourself needing to perform some action that's not -supported by Google Mock directly, remember that you can define your own -actions using -[MakeAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Actions) or -[MakePolymorphicAction()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Writing_New_Polymorphic_Actions), -or you can write a stub function and invoke it using -[Invoke()](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Using_Functions_Methods_Functors). - -## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## - -What?! I think it's beautiful. :-) - -While which syntax looks more natural is a subjective matter to some -extent, Google Mock's syntax was chosen for several practical advantages it -has. - -Try to mock a function that takes a map as an argument: -``` -virtual int GetSize(const map<int, std::string>& m); -``` - -Using the proposed syntax, it would be: -``` -MOCK_METHOD1(GetSize, int, const map<int, std::string>& m); -``` - -Guess what? You'll get a compiler error as the compiler thinks that -`const map<int, std::string>& m` are **two**, not one, arguments. To work -around this you can use `typedef` to give the map type a name, but -that gets in the way of your work. Google Mock's syntax avoids this -problem as the function's argument types are protected inside a pair -of parentheses: -``` -// This compiles fine. -MOCK_METHOD1(GetSize, int(const map<int, std::string>& m)); -``` - -You still need a `typedef` if the return type contains an unprotected -comma, but that's much rarer. - -Other advantages include: - 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. - 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. - 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! - -## My code calls a static/global function. Can I mock it? ## - -You can, but you need to make some changes. - -In general, if you find yourself needing to mock a static function, -it's a sign that your modules are too tightly coupled (and less -flexible, less reusable, less testable, etc). You are probably better -off defining a small interface and call the function through that -interface, which then can be easily mocked. It's a bit of work -initially, but usually pays for itself quickly. - -This Google Testing Blog -[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html) -says it excellently. Check it out. - -## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## - -I know it's not a question, but you get an answer for free any way. :-) - -With Google Mock, you can create mocks in C++ easily. And people might be -tempted to use them everywhere. Sometimes they work great, and -sometimes you may find them, well, a pain to use. So, what's wrong in -the latter case? - -When you write a test without using mocks, you exercise the code and -assert that it returns the correct value or that the system is in an -expected state. This is sometimes called "state-based testing". - -Mocks are great for what some call "interaction-based" testing: -instead of checking the system state at the very end, mock objects -verify that they are invoked the right way and report an error as soon -as it arises, giving you a handle on the precise context in which the -error was triggered. This is often more effective and economical to -do than state-based testing. - -If you are doing state-based testing and using a test double just to -simulate the real object, you are probably better off using a fake. -Using a mock in this case causes pain, as it's not a strong point for -mocks to perform complex actions. If you experience this and think -that mocks suck, you are just not using the right tool for your -problem. Or, you might be trying to solve the wrong problem. :-) - -## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## - -By all means, NO! It's just an FYI. - -What it means is that you have a mock function, you haven't set any -expectations on it (by Google Mock's rule this means that you are not -interested in calls to this function and therefore it can be called -any number of times), and it is called. That's OK - you didn't say -it's not OK to call the function! - -What if you actually meant to disallow this function to be called, but -forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While -one can argue that it's the user's fault, Google Mock tries to be nice and -prints you a note. - -So, when you see the message and believe that there shouldn't be any -uninteresting calls, you should investigate what's going on. To make -your life easier, Google Mock prints the function name and arguments -when an uninteresting call is encountered. - -## I want to define a custom action. Should I use Invoke() or implement the action interface? ## - -Either way is fine - you want to choose the one that's more convenient -for your circumstance. - -Usually, if your action is for a particular function type, defining it -using `Invoke()` should be easier; if your action can be used in -functions of different types (e.g. if you are defining -`Return(value)`), `MakePolymorphicAction()` is -easiest. Sometimes you want precise control on what types of -functions the action can be used in, and implementing -`ActionInterface` is the way to go here. See the implementation of -`Return()` in `include/gmock/gmock-actions.h` for an example. - -## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## - -You got this error as Google Mock has no idea what value it should return -when the mock method is called. `SetArgPointee()` says what the -side effect is, but doesn't say what the return value should be. You -need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. - -See this [recipe](http://code.google.com/p/googlemock/wiki/V1_7_CookBook#Mocking_Side_Effects) for more details and an example. - - -## My question is not in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. read other [wiki pages](http://code.google.com/p/googlemock/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), - 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). - -Please note that creating an issue in the -[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. \ No newline at end of file diff --git a/googlemock/include/gmock/gmock-actions.h b/googlemock/include/gmock/gmock-actions.h index b3f654af..845c8232 100644 --- a/googlemock/include/gmock/gmock-actions.h +++ b/googlemock/include/gmock/gmock-actions.h @@ -1,1205 +1,1205 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used actions. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE # include <errno.h> #endif #include <algorithm> #include <string> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #if GTEST_HAS_STD_TYPE_TRAITS_ // Defined by gtest-port.h via gmock-port.h. #include <type_traits> #endif namespace testing { // To implement an action Foo, define: // 1. a class FooAction that implements the ActionInterface interface, and // 2. a factory function that creates an Action object from a // const FooAction*. // // The two-level delegation design follows that of Matcher, providing // consistency for extension developers. It also eases ownership // management as Action objects can now be copied like plain values. namespace internal { template <typename F1, typename F2> class ActionAdaptor; // BuiltInDefaultValueGetter<T, true>::Get() returns a // default-constructed T value. BuiltInDefaultValueGetter<T, // false>::Get() crashes with an error. // // This primary template is used when kDefaultConstructible is true. template <typename T, bool kDefaultConstructible> struct BuiltInDefaultValueGetter { static T Get() { return T(); } }; template <typename T> struct BuiltInDefaultValueGetter<T, false> { static T Get() { Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); return internal::Invalid<T>(); // The above statement will never be reached, but is required in // order for this function to compile. } }; // BuiltInDefaultValue<T>::Get() returns the "built-in" default value // for type T, which is NULL when T is a raw pointer type, 0 when T is // a numeric type, false when T is bool, or "" when T is string or // std::string. In addition, in C++11 and above, it turns a // default-constructed T value if T is default constructible. For any // other type T, the built-in default T value is undefined, and the // function will abort the process. template <typename T> class BuiltInDefaultValue { public: #if GTEST_HAS_STD_TYPE_TRAITS_ // This function returns true iff type T has a built-in default value. static bool Exists() { return ::std::is_default_constructible<T>::value; } static T Get() { return BuiltInDefaultValueGetter< T, ::std::is_default_constructible<T>::value>::Get(); } #else // GTEST_HAS_STD_TYPE_TRAITS_ // This function returns true iff type T has a built-in default value. static bool Exists() { return false; } static T Get() { return BuiltInDefaultValueGetter<T, false>::Get(); } #endif // GTEST_HAS_STD_TYPE_TRAITS_ }; // This partial specialization says that we use the same built-in // default value for T and const T. template <typename T> class BuiltInDefaultValue<const T> { public: static bool Exists() { return BuiltInDefaultValue<T>::Exists(); } static T Get() { return BuiltInDefaultValue<T>::Get(); } }; // This partial specialization defines the default values for pointer // types. template <typename T> class BuiltInDefaultValue<T*> { public: static bool Exists() { return true; } static T* Get() { return NULL; } }; // The following specializations define the default values for // specific types we care about. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ template <> \ class BuiltInDefaultValue<type> { \ public: \ static bool Exists() { return true; } \ static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT #if GTEST_HAS_GLOBAL_STRING GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, ""); #endif // GTEST_HAS_GLOBAL_STRING GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); // There's no need for a default action for signed wchar_t, as that // type is the same as wchar_t for gcc, and invalid for MSVC. // // There's also no need for a default action for unsigned wchar_t, as // that type is the same as unsigned int for gcc, and invalid for // MSVC. #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT #endif GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ } // namespace internal // When an unexpected function call is encountered, Google Mock will // let it return a default value if the user has specified one for its // return type, or if the return type has a built-in default value; // otherwise Google Mock won't know what value to return and will have // to abort the process. // // The DefaultValue<T> class allows a user to specify the // default value for a type T that is both copyable and publicly // destructible (i.e. anything that can be used as a function return // type). The usage is: // // // Sets the default value for type T to be foo. // DefaultValue<T>::Set(foo); template <typename T> class DefaultValue { public: // Sets the default value for type T; requires T to be // copy-constructable and have a public destructor. static void Set(T x) { delete producer_; producer_ = new FixedValueProducer(x); } // Provides a factory function to be called to generate the default value. // This method can be used even if T is only move-constructible, but it is not // limited to that case. typedef T (*FactoryFunction)(); static void SetFactory(FactoryFunction factory) { delete producer_; producer_ = new FactoryValueProducer(factory); } // Unsets the default value for type T. static void Clear() { delete producer_; producer_ = NULL; } // Returns true iff the user has set the default value for type T. static bool IsSet() { return producer_ != NULL; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); } // Returns the default value for type T if the user has set one; // otherwise returns the built-in default value. Requires that Exists() // is true, which ensures that the return value is well-defined. static T Get() { return producer_ == NULL ? internal::BuiltInDefaultValue<T>::Get() : producer_->Produce(); } private: class ValueProducer { public: virtual ~ValueProducer() {} virtual T Produce() = 0; }; class FixedValueProducer : public ValueProducer { public: explicit FixedValueProducer(T value) : value_(value) {} virtual T Produce() { return value_; } private: const T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); }; class FactoryValueProducer : public ValueProducer { public: explicit FactoryValueProducer(FactoryFunction factory) : factory_(factory) {} virtual T Produce() { return factory_(); } private: const FactoryFunction factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); }; static ValueProducer* producer_; }; // This partial specialization allows a user to set default values for // reference types. template <typename T> class DefaultValue<T&> { public: // Sets the default value for type T&. static void Set(T& x) { // NOLINT address_ = &x; } // Unsets the default value for type T&. static void Clear() { address_ = NULL; } // Returns true iff the user has set the default value for type T&. static bool IsSet() { return address_ != NULL; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); } // Returns the default value for type T& if the user has set one; // otherwise returns the built-in default value if there is one; // otherwise aborts the process. static T& Get() { return address_ == NULL ? internal::BuiltInDefaultValue<T&>::Get() : *address_; } private: static T* address_; }; // This specialization allows DefaultValue<void>::Get() to // compile. template <> class DefaultValue<void> { public: static bool Exists() { return true; } static void Get() {} }; // Points to the user-set default value for type T. template <typename T> typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL; // Points to the user-set default value for type T&. template <typename T> T* DefaultValue<T&>::address_ = NULL; // Implement this interface to define an action for function type F. template <typename F> class ActionInterface { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; ActionInterface() {} virtual ~ActionInterface() {} // Performs the action. This method is not const, as in general an // action can have side effects and be stateful. For example, a // get-the-next-element-from-the-collection action will need to // remember the current element. virtual Result Perform(const ArgumentTuple& args) = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); }; // An Action<F> is a copyable and IMMUTABLE (except by assignment) // object that represents an action to be taken when a mock function // of type F is called. The implementation of Action<T> is just a // linked_ptr to const ActionInterface<T>, so copying is fairly cheap. // Don't inherit from Action! // // You can view an object implementing ActionInterface<F> as a // concrete action (including its current state), and an Action<F> // object as a handle to it. template <typename F> class Action { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; // Constructs a null Action. Needed for storing Action objects in // STL containers. Action() : impl_(NULL) {} // Constructs an Action from its implementation. A NULL impl is // used to represent the "do-default" action. explicit Action(ActionInterface<F>* impl) : impl_(impl) {} // Copy constructor. Action(const Action& action) : impl_(action.impl_) {} // This constructor allows us to turn an Action<Func> object into an // Action<F>, as long as F's arguments can be implicitly converted // to Func's and Func's return type can be implicitly converted to // F's. template <typename Func> explicit Action(const Action<Func>& action); // Returns true iff this is the DoDefault() action. bool IsDoDefault() const { return impl_.get() == NULL; } // Performs the action. Note that this method is const even though // the corresponding method in ActionInterface is not. The reason // is that a const Action<F> means that it cannot be re-bound to // another concrete action, not that the concrete action it binds to // cannot change state. (Think of the difference between a const // pointer and a pointer to const.) Result Perform(const ArgumentTuple& args) const { internal::Assert( !IsDoDefault(), __FILE__, __LINE__, "You are using DoDefault() inside a composite action like " "DoAll() or WithArgs(). This is not supported for technical " "reasons. Please instead spell out the default action, or " "assign the default action to an Action variable and use " "the variable in various places."); return impl_->Perform(args); } private: template <typename F1, typename F2> friend class internal::ActionAdaptor; internal::linked_ptr<ActionInterface<F> > impl_; }; // The PolymorphicAction class template makes it easy to implement a // polymorphic action (i.e. an action that can be used in mock // functions of than one type, e.g. Return()). // // To define a polymorphic action, a user first provides a COPYABLE // implementation class that has a Perform() method template: // // class FooAction { // public: // template <typename Result, typename ArgumentTuple> // Result Perform(const ArgumentTuple& args) const { // // Processes the arguments and returns a result, using // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple. // } // ... // }; // // Then the user creates the polymorphic action using // MakePolymorphicAction(object) where object has type FooAction. See // the definition of Return(void) and SetArgumentPointee<N>(value) for // complete examples. template <typename Impl> class PolymorphicAction { public: explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} template <typename F> operator Action<F>() const { return Action<F>(new MonomorphicImpl<F>(impl_)); } private: template <typename F> class MonomorphicImpl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} virtual Result Perform(const ArgumentTuple& args) { return impl_.template Perform<Result>(args); } private: Impl impl_; GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); }; Impl impl_; GTEST_DISALLOW_ASSIGN_(PolymorphicAction); }; // Creates an Action from its implementation and returns it. The // created Action object owns the implementation. template <typename F> Action<F> MakeAction(ActionInterface<F>* impl) { return Action<F>(impl); } // Creates a polymorphic action from its implementation. This is // easier to use than the PolymorphicAction<Impl> constructor as it // doesn't require you to explicitly write the template argument, e.g. // // MakePolymorphicAction(foo); // vs // PolymorphicAction<TypeOfFoo>(foo); template <typename Impl> inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) { return PolymorphicAction<Impl>(impl); } namespace internal { // Allows an Action<F2> object to pose as an Action<F1>, as long as F2 // and F1 are compatible. template <typename F1, typename F2> class ActionAdaptor : public ActionInterface<F1> { public: typedef typename internal::Function<F1>::Result Result; typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple; explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {} virtual Result Perform(const ArgumentTuple& args) { return impl_->Perform(args); } private: const internal::linked_ptr<ActionInterface<F2> > impl_; GTEST_DISALLOW_ASSIGN_(ActionAdaptor); }; // Helper struct to specialize ReturnAction to execute a move instead of a copy // on return. Useful for move-only types, but could be used on any type. template <typename T> struct ByMoveWrapper { explicit ByMoveWrapper(T value) : payload(internal::move(value)) {} T payload; }; // Implements the polymorphic Return(x) action, which can be used in // any function that returns the type of x, regardless of the argument // types. // // Note: The value passed into Return must be converted into // Function<F>::Result when this action is cast to Action<F> rather than // when that action is performed. This is important in scenarios like // // MOCK_METHOD1(Method, T(U)); // ... // { // Foo foo; // X x(&foo); // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x)); // } // // In the example above the variable x holds reference to foo which leaves // scope and gets destroyed. If copying X just copies a reference to foo, // that copy will be left with a hanging reference. If conversion to T // makes a copy of foo, the above code is safe. To support that scenario, we // need to make sure that the type conversion happens inside the EXPECT_CALL // statement, and conversion of the result of Return to Action<T(U)> is a // good place for that. // template <typename R> class ReturnAction { public: // Constructs a ReturnAction object from the value to be returned. // 'value' is passed by value instead of by const reference in order // to allow Return("string literal") to compile. explicit ReturnAction(R value) : value_(new R(internal::move(value))) {} // This template type conversion operator allows Return(x) to be // used in ANY function that returns x's type. template <typename F> operator Action<F>() const { // Assert statement belongs here because this is the best place to verify // conditions on F. It produces the clearest error messages // in most compilers. // Impl really belongs in this scope as a local class but can't // because MSVC produces duplicate symbols in different translation units // in this case. Until MS fixes that bug we put Impl into the class scope // and put the typedef both here (for use in assert statement) and // in the Impl class. But both definitions must be the same. typedef typename Function<F>::Result Result; GTEST_COMPILE_ASSERT_( !is_reference<Result>::value, use_ReturnRef_instead_of_Return_to_return_a_reference); return Action<F>(new Impl<R, F>(value_)); } private: // Implements the Return(x) action for a particular function type F. template <typename R_, typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; // The implicit cast is necessary when Result has more than one // single-argument constructor (e.g. Result is std::vector<int>) and R // has a type conversion operator template. In that case, value_(value) // won't compile as the compiler doesn't known which constructor of // Result to call. ImplicitCast_ forces the compiler to convert R to // Result without considering explicit constructors, thus resolving the // ambiguity. value_ is then initialized using its copy constructor. explicit Impl(const linked_ptr<R>& value) : value_before_cast_(*value), value_(ImplicitCast_<Result>(value_before_cast_)) {} virtual Result Perform(const ArgumentTuple&) { return value_; } private: GTEST_COMPILE_ASSERT_(!is_reference<Result>::value, Result_cannot_be_a_reference_type); // We save the value before casting just in case it is being cast to a // wrapper type. R value_before_cast_; Result value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); }; // Partially specialize for ByMoveWrapper. This version of ReturnAction will // move its contents instead. template <typename R_, typename F> class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const linked_ptr<R>& wrapper) : performed_(false), wrapper_(wrapper) {} virtual Result Perform(const ArgumentTuple&) { GTEST_CHECK_(!performed_) << "A ByMove() action should only be performed once."; performed_ = true; return internal::move(wrapper_->payload); } private: bool performed_; const linked_ptr<R> wrapper_; GTEST_DISALLOW_ASSIGN_(Impl); }; const linked_ptr<R> value_; GTEST_DISALLOW_ASSIGN_(ReturnAction); }; // Implements the ReturnNull() action. class ReturnNullAction { public: // Allows ReturnNull() to be used in any pointer-returning function. In C++11 // this is enforced by returning nullptr, and in non-C++11 by asserting a // pointer type on compile time. template <typename Result, typename ArgumentTuple> static Result Perform(const ArgumentTuple&) { #if GTEST_LANG_CXX11 return nullptr; #else GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value, ReturnNull_can_be_used_to_return_a_pointer_only); return NULL; #endif // GTEST_LANG_CXX11 } }; // Implements the Return() action. class ReturnVoidAction { public: // Allows Return() to be used in any void-returning function. template <typename Result, typename ArgumentTuple> static void Perform(const ArgumentTuple&) { CompileAssertTypesEqual<void, Result>(); } }; // Implements the polymorphic ReturnRef(x) action, which can be used // in any function that returns a reference to the type of x, // regardless of the argument types. template <typename T> class ReturnRefAction { public: // Constructs a ReturnRefAction object from the reference to be returned. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT // This template type conversion operator allows ReturnRef(x) to be // used in ANY function that returns a reference to x's type. template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; // Asserts that the function return type is a reference. This // catches the user error of using ReturnRef(x) when Return(x) // should be used, and generates some helpful error message. GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value, use_Return_instead_of_ReturnRef_to_return_a_value); return Action<F>(new Impl<F>(ref_)); } private: // Implements the ReturnRef(x) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(T& ref) : ref_(ref) {} // NOLINT virtual Result Perform(const ArgumentTuple&) { return ref_; } private: T& ref_; GTEST_DISALLOW_ASSIGN_(Impl); }; T& ref_; GTEST_DISALLOW_ASSIGN_(ReturnRefAction); }; // Implements the polymorphic ReturnRefOfCopy(x) action, which can be // used in any function that returns a reference to the type of x, // regardless of the argument types. template <typename T> class ReturnRefOfCopyAction { public: // Constructs a ReturnRefOfCopyAction object from the reference to // be returned. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT // This template type conversion operator allows ReturnRefOfCopy(x) to be // used in ANY function that returns a reference to x's type. template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; // Asserts that the function return type is a reference. This // catches the user error of using ReturnRefOfCopy(x) when Return(x) // should be used, and generates some helpful error message. GTEST_COMPILE_ASSERT_( internal::is_reference<Result>::value, use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); return Action<F>(new Impl<F>(value_)); } private: // Implements the ReturnRefOfCopy(x) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const T& value) : value_(value) {} // NOLINT virtual Result Perform(const ArgumentTuple&) { return value_; } private: T value_; GTEST_DISALLOW_ASSIGN_(Impl); }; const T value_; GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); }; // Implements the polymorphic DoDefault() action. class DoDefaultAction { public: // This template type conversion operator allows DoDefault() to be // used in any function. template <typename F> operator Action<F>() const { return Action<F>(NULL); } }; // Implements the Assign action to set a given pointer referent to a // particular value. template <typename T1, typename T2> class AssignAction { public: AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& /* args */) const { *ptr_ = value_; } private: T1* const ptr_; const T2 value_; GTEST_DISALLOW_ASSIGN_(AssignAction); }; #if !GTEST_OS_WINDOWS_MOBILE // Implements the SetErrnoAndReturn action to simulate return from // various system calls and libc functions. template <typename T> class SetErrnoAndReturnAction { public: SetErrnoAndReturnAction(int errno_value, T result) : errno_(errno_value), result_(result) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& /* args */) const { errno = errno_; return result_; } private: const int errno_; const T result_; GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction); }; #endif // !GTEST_OS_WINDOWS_MOBILE // Implements the SetArgumentPointee<N>(x) action for any function // whose N-th argument (0-based) is a pointer to x's type. The // template parameter kIsProto is true iff type A is ProtocolMessage, // proto2::Message, or a sub-class of those. template <size_t N, typename A, bool kIsProto> class SetArgumentPointeeAction { public: // Constructs an action that sets the variable pointed to by the // N-th function argument to 'value'. explicit SetArgumentPointeeAction(const A& value) : value_(value) {} template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); *::testing::get<N>(args) = value_; } private: const A value_; GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); }; template <size_t N, typename Proto> class SetArgumentPointeeAction<N, Proto, true> { public: // Constructs an action that sets the variable pointed to by the // N-th function argument to 'proto'. Both ProtocolMessage and // proto2::Message have the CopyFrom() method, so the same // implementation works for both. explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) { proto_->CopyFrom(proto); } template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); ::testing::get<N>(args)->CopyFrom(*proto_); } private: const internal::linked_ptr<Proto> proto_; GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); }; // Implements the InvokeWithoutArgs(f) action. The template argument // FunctionImpl is the implementation type of f, which can be either a // function pointer or a functor. InvokeWithoutArgs(f) can be used as an // Action<F> as long as f's type is compatible with F (i.e. f can be // assigned to a tr1::function<F>). template <typename FunctionImpl> class InvokeWithoutArgsAction { public: // The c'tor makes a copy of function_impl (either a function // pointer or a functor). explicit InvokeWithoutArgsAction(FunctionImpl function_impl) : function_impl_(function_impl) {} // Allows InvokeWithoutArgs(f) to be used as any action whose type is // compatible with f. template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple&) { return function_impl_(); } private: FunctionImpl function_impl_; GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction); }; // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. template <class Class, typename MethodPtr> class InvokeMethodWithoutArgsAction { public: InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr) : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple&) const { return (obj_ptr_->*method_ptr_)(); } private: Class* const obj_ptr_; const MethodPtr method_ptr_; GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction); }; // Implements the IgnoreResult(action) action. template <typename A> class IgnoreResultAction { public: explicit IgnoreResultAction(const A& action) : action_(action) {} template <typename F> operator Action<F>() const { // Assert statement belongs here because this is the best place to verify // conditions on F. It produces the clearest error messages // in most compilers. // Impl really belongs in this scope as a local class but can't // because MSVC produces duplicate symbols in different translation units // in this case. Until MS fixes that bug we put Impl into the class scope // and put the typedef both here (for use in assert statement) and // in the Impl class. But both definitions must be the same. typedef typename internal::Function<F>::Result Result; // Asserts at compile time that F returns void. CompileAssertTypesEqual<void, Result>(); return Action<F>(new Impl<F>(action_)); } private: template <typename F> class Impl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const A& action) : action_(action) {} virtual void Perform(const ArgumentTuple& args) { // Performs the action and ignores its result. action_.Perform(args); } private: // Type OriginalFunction is the same as F except that its return // type is IgnoredValue. typedef typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction; const Action<OriginalFunction> action_; GTEST_DISALLOW_ASSIGN_(Impl); }; const A action_; GTEST_DISALLOW_ASSIGN_(IgnoreResultAction); }; // A ReferenceWrapper<T> object represents a reference to type T, // which can be either const or not. It can be explicitly converted // from, and implicitly converted to, a T&. Unlike a reference, // ReferenceWrapper<T> can be copied and can survive template type // inference. This is used to support by-reference arguments in the // InvokeArgument<N>(...) action. The idea was from "reference // wrappers" in tr1, which we don't have in our source tree yet. template <typename T> class ReferenceWrapper { public: // Constructs a ReferenceWrapper<T> object from a T&. explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT // Allows a ReferenceWrapper<T> object to be implicitly converted to // a T&. operator T&() const { return *pointer_; } private: T* pointer_; }; // Allows the expression ByRef(x) to be printed as a reference to x. template <typename T> void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) { T& value = ref; UniversalPrinter<T&>::Print(value, os); } // Does two actions sequentially. Used for implementing the DoAll(a1, // a2, ...) action. template <typename Action1, typename Action2> class DoBothAction { public: DoBothAction(Action1 action1, Action2 action2) : action1_(action1), action2_(action2) {} // This template type conversion operator allows DoAll(a1, ..., a_n) // to be used in ANY function of compatible type. template <typename F> operator Action<F>() const { return Action<F>(new Impl<F>(action1_, action2_)); } private: // Implements the DoAll(...) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::MakeResultVoid VoidResult; Impl(const Action<VoidResult>& action1, const Action<F>& action2) : action1_(action1), action2_(action2) {} virtual Result Perform(const ArgumentTuple& args) { action1_.Perform(args); return action2_.Perform(args); } private: const Action<VoidResult> action1_; const Action<F> action2_; GTEST_DISALLOW_ASSIGN_(Impl); }; Action1 action1_; Action2 action2_; GTEST_DISALLOW_ASSIGN_(DoBothAction); }; } // namespace internal // An Unused object can be implicitly constructed from ANY value. // This is handy when defining actions that ignore some or all of the // mock function arguments. For example, given // // MOCK_METHOD3(Foo, double(const string& label, double x, double y)); // MOCK_METHOD3(Bar, double(int index, double x, double y)); // // instead of // // double DistanceToOriginWithLabel(const string& label, double x, double y) { // return sqrt(x*x + y*y); // } // double DistanceToOriginWithIndex(int index, double x, double y) { // return sqrt(x*x + y*y); // } // ... -// EXEPCT_CALL(mock, Foo("abc", _, _)) +// EXPECT_CALL(mock, Foo("abc", _, _)) // .WillOnce(Invoke(DistanceToOriginWithLabel)); -// EXEPCT_CALL(mock, Bar(5, _, _)) +// EXPECT_CALL(mock, Bar(5, _, _)) // .WillOnce(Invoke(DistanceToOriginWithIndex)); // // you could write // // // We can declare any uninteresting argument as Unused. // double DistanceToOrigin(Unused, double x, double y) { // return sqrt(x*x + y*y); // } // ... -// EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); -// EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); +// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); typedef internal::IgnoredValue Unused; // This constructor allows us to turn an Action<From> object into an // Action<To>, as long as To's arguments can be implicitly converted // to From's and From's return type cann be implicitly converted to // To's. template <typename To> template <typename From> Action<To>::Action(const Action<From>& from) : impl_(new internal::ActionAdaptor<To, From>(from)) {} // Creates an action that returns 'value'. 'value' is passed by value // instead of const reference - otherwise Return("string literal") // will trigger a compiler error about using array as initializer. template <typename R> internal::ReturnAction<R> Return(R value) { return internal::ReturnAction<R>(internal::move(value)); } // Creates an action that returns NULL. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() { return MakePolymorphicAction(internal::ReturnNullAction()); } // Creates an action that returns from a void function. inline PolymorphicAction<internal::ReturnVoidAction> Return() { return MakePolymorphicAction(internal::ReturnVoidAction()); } // Creates an action that returns the reference to a variable. template <typename R> inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT return internal::ReturnRefAction<R>(x); } // Creates an action that returns the reference to a copy of the // argument. The copy is created when the action is constructed and // lives as long as the action. template <typename R> inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) { return internal::ReturnRefOfCopyAction<R>(x); } // Modifies the parent action (a Return() action) to perform a move of the // argument instead of a copy. // Return(ByMove()) actions can only be executed once and will assert this // invariant. template <typename R> internal::ByMoveWrapper<R> ByMove(R x) { return internal::ByMoveWrapper<R>(internal::move(x)); } // Creates an action that does the default action for the give mock function. inline internal::DoDefaultAction DoDefault() { return internal::DoDefaultAction(); } // Creates an action that sets the variable pointed by the N-th // (0-based) function argument to 'value'. template <size_t N, typename T> PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value> > SetArgPointee(const T& x) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value>(x)); } #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) // This overload allows SetArgPointee() to accept a string literal. // GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish // this overload from the templated version and emit a compile error. template <size_t N> PolymorphicAction< internal::SetArgumentPointeeAction<N, const char*, false> > SetArgPointee(const char* p) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, const char*, false>(p)); } template <size_t N> PolymorphicAction< internal::SetArgumentPointeeAction<N, const wchar_t*, false> > SetArgPointee(const wchar_t* p) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, const wchar_t*, false>(p)); } #endif // The following version is DEPRECATED. template <size_t N, typename T> PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value> > SetArgumentPointee(const T& x) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value>(x)); } // Creates an action that sets a pointer referent to a given value. template <typename T1, typename T2> PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) { return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); } #if !GTEST_OS_WINDOWS_MOBILE // Creates an action that sets errno and returns the appropriate error. template <typename T> PolymorphicAction<internal::SetErrnoAndReturnAction<T> > SetErrnoAndReturn(int errval, T result) { return MakePolymorphicAction( internal::SetErrnoAndReturnAction<T>(errval, result)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Various overloads for InvokeWithoutArgs(). // Creates an action that invokes 'function_impl' with no argument. template <typename FunctionImpl> PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> > InvokeWithoutArgs(FunctionImpl function_impl) { return MakePolymorphicAction( internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl)); } // Creates an action that invokes the given method on the given object // with no argument. template <class Class, typename MethodPtr> PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> > InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) { return MakePolymorphicAction( internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>( obj_ptr, method_ptr)); } // Creates an action that performs an_action and throws away its // result. In other words, it changes the return type of an_action to // void. an_action MUST NOT return void, or the code won't compile. template <typename A> inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) { return internal::IgnoreResultAction<A>(an_action); } // Creates a reference wrapper for the given L-value. If necessary, // you can explicitly specify the type of the reference. For example, // suppose 'derived' is an object of type Derived, ByRef(derived) // would wrap a Derived&. If you want to wrap a const Base& instead, // where Base is a base class of Derived, just write: // // ByRef<const Base>(derived) template <typename T> inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT return internal::ReferenceWrapper<T>(l_value); } } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/googlemock/include/gmock/gmock-matchers.h b/googlemock/include/gmock/gmock-matchers.h index 9ade5b64..3a97c438 100644 --- a/googlemock/include/gmock/gmock-matchers.h +++ b/googlemock/include/gmock/gmock-matchers.h @@ -1,4397 +1,4397 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used argument matchers. More // matchers can be defined by the user implementing the // MatcherInterface<T> interface if necessary. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #include <math.h> #include <algorithm> #include <iterator> #include <limits> #include <ostream> // NOLINT #include <sstream> #include <string> #include <utility> #include <vector> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" #if GTEST_HAS_STD_INITIALIZER_LIST_ # include <initializer_list> // NOLINT -- must be after gtest.h #endif namespace testing { // To implement a matcher Foo for type T, define: // 1. a class FooMatcherImpl that implements the // MatcherInterface<T> interface, and // 2. a factory function that creates a Matcher<T> object from a // FooMatcherImpl*. // // The two-level delegation design makes it possible to allow a user // to write "v" instead of "Eq(v)" where a Matcher is expected, which // is impossible if we pass matchers by pointers. It also eases // ownership management as Matcher objects can now be copied like // plain values. // MatchResultListener is an abstract class. Its << operator can be // used by a matcher to explain why a value matches or doesn't match. // // TODO(wan@google.com): add method // bool InterestedInWhy(bool result) const; // to indicate whether the listener is interested in why the match // result is 'result'. class MatchResultListener { public: // Creates a listener object with the given underlying ostream. The // listener does not own the ostream, and does not dereference it // in the constructor or destructor. explicit MatchResultListener(::std::ostream* os) : stream_(os) {} virtual ~MatchResultListener() = 0; // Makes this class abstract. // Streams x to the underlying ostream; does nothing if the ostream // is NULL. template <typename T> MatchResultListener& operator<<(const T& x) { if (stream_ != NULL) *stream_ << x; return *this; } // Returns the underlying ostream. ::std::ostream* stream() { return stream_; } // Returns true iff the listener is interested in an explanation of // the match result. A matcher's MatchAndExplain() method can use // this information to avoid generating the explanation when no one // intends to hear it. bool IsInterested() const { return stream_ != NULL; } private: ::std::ostream* const stream_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); }; inline MatchResultListener::~MatchResultListener() { } // An instance of a subclass of this knows how to describe itself as a // matcher. class MatcherDescriberInterface { public: virtual ~MatcherDescriberInterface() {} // Describes this matcher to an ostream. The function should print // a verb phrase that describes the property a value matching this // matcher should have. The subject of the verb phrase is the value // being matched. For example, the DescribeTo() method of the Gt(7) // matcher prints "is greater than 7". virtual void DescribeTo(::std::ostream* os) const = 0; // Describes the negation of this matcher to an ostream. For // example, if the description of this matcher is "is greater than // 7", the negated description could be "is not greater than 7". // You are not required to override this when implementing // MatcherInterface, but it is highly advised so that your matcher // can produce good error messages. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "not ("; DescribeTo(os); *os << ")"; } }; // The implementation of a matcher. template <typename T> class MatcherInterface : public MatcherDescriberInterface { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener' if necessary (see the next paragraph), in // the form of a non-restrictive relative clause ("which ...", // "whose ...", etc) that describes x. For example, the // MatchAndExplain() method of the Pointee(...) matcher should // generate an explanation like "which points to ...". // // Implementations of MatchAndExplain() should add an explanation of // the match result *if and only if* they can provide additional // information that's not already present (or not obvious) in the // print-out of x and the matcher's description. Whether the match // succeeds is not a factor in deciding whether an explanation is // needed, as sometimes the caller needs to print a failure message // when the match succeeds (e.g. when the matcher is used inside // Not()). // // For example, a "has at least 10 elements" matcher should explain // what the actual element count is, regardless of the match result, // as it is useful information to the reader; on the other hand, an // "is empty" matcher probably only needs to explain what the actual // size is when the match fails, as it's redundant to say that the // size is 0 when the value is already known to be empty. // // You should override this method when defining a new matcher. // // It's the responsibility of the caller (Google Mock) to guarantee // that 'listener' is not NULL. This helps to simplify a matcher's // implementation when it doesn't care about the performance, as it // can talk to 'listener' without checking its validity first. // However, in order to implement dummy listeners efficiently, // listener->stream() may be NULL. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; // Inherits these methods from MatcherDescriberInterface: // virtual void DescribeTo(::std::ostream* os) const = 0; // virtual void DescribeNegationTo(::std::ostream* os) const; }; // A match result listener that stores the explanation in a string. class StringMatchResultListener : public MatchResultListener { public: StringMatchResultListener() : MatchResultListener(&ss_) {} // Returns the explanation accumulated so far. std::string str() const { return ss_.str(); } // Clears the explanation accumulated so far. void Clear() { ss_.str(""); } private: ::std::stringstream ss_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); }; namespace internal { struct AnyEq { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a == b; } }; struct AnyNe { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a != b; } }; struct AnyLt { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a < b; } }; struct AnyGt { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a > b; } }; struct AnyLe { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a <= b; } }; struct AnyGe { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a >= b; } }; // A match result listener that ignores the explanation. class DummyMatchResultListener : public MatchResultListener { public: DummyMatchResultListener() : MatchResultListener(NULL) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener); }; // A match result listener that forwards the explanation to a given // ostream. The difference between this and MatchResultListener is // that the former is concrete. class StreamMatchResultListener : public MatchResultListener { public: explicit StreamMatchResultListener(::std::ostream* os) : MatchResultListener(os) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); }; // An internal class for implementing Matcher<T>, which will derive // from it. We put functionalities common to all Matcher<T> // specializations here to avoid code duplication. template <typename T> class MatcherBase { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener'. bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } // Returns true iff this matcher matches x. bool Matches(T x) const { DummyMatchResultListener dummy; return MatchAndExplain(x, &dummy); } // Describes this matcher to an ostream. void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } // Describes the negation of this matcher to an ostream. void DescribeNegationTo(::std::ostream* os) const { impl_->DescribeNegationTo(os); } // Explains why x matches, or doesn't match, the matcher. void ExplainMatchResultTo(T x, ::std::ostream* os) const { StreamMatchResultListener listener(os); MatchAndExplain(x, &listener); } // Returns the describer for this matcher object; retains ownership // of the describer, which is only guaranteed to be alive when // this matcher object is alive. const MatcherDescriberInterface* GetDescriber() const { return impl_.get(); } protected: MatcherBase() {} // Constructs a matcher from its implementation. explicit MatcherBase(const MatcherInterface<T>* impl) : impl_(impl) {} virtual ~MatcherBase() {} private: // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar // interfaces. The former dynamically allocates a chunk of memory // to hold the reference count, while the latter tracks all // references using a circular linked list without allocating // memory. It has been observed that linked_ptr performs better in // typical scenarios. However, shared_ptr can out-perform // linked_ptr when there are many more uses of the copy constructor // than the default constructor. // // If performance becomes a problem, we should see if using // shared_ptr helps. ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_; }; } // namespace internal // A Matcher<T> is a copyable and IMMUTABLE (except by assignment) // object that can check whether a value of type T matches. The // implementation of Matcher<T> is just a linked_ptr to const // MatcherInterface<T>, so copying is fairly cheap. Don't inherit // from Matcher! template <typename T> class Matcher : public internal::MatcherBase<T> { public: // Constructs a null matcher. Needed for storing Matcher objects in STL // containers. A default-constructed matcher is not yet initialized. You // cannot use it until a valid value has been assigned to it. explicit Matcher() {} // NOLINT // Constructs a matcher from its implementation. explicit Matcher(const MatcherInterface<T>* impl) : internal::MatcherBase<T>(impl) {} // Implicit constructor here allows people to write // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes Matcher(T value); // NOLINT }; // The following two specializations allow the user to write str // instead of Eq(str) and "foo" instead of Eq("foo") when a string // matcher is expected. template <> class GTEST_API_ Matcher<const internal::string&> : public internal::MatcherBase<const internal::string&> { public: Matcher() {} explicit Matcher(const MatcherInterface<const internal::string&>* impl) : internal::MatcherBase<const internal::string&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; template <> class GTEST_API_ Matcher<internal::string> : public internal::MatcherBase<internal::string> { public: Matcher() {} explicit Matcher(const MatcherInterface<internal::string>* impl) : internal::MatcherBase<internal::string>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; #if GTEST_HAS_STRING_PIECE_ // The following two specializations allow the user to write str // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece // matcher is expected. template <> class GTEST_API_ Matcher<const StringPiece&> : public internal::MatcherBase<const StringPiece&> { public: Matcher() {} explicit Matcher(const MatcherInterface<const StringPiece&>* impl) : internal::MatcherBase<const StringPiece&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT // Allows the user to pass StringPieces directly. Matcher(StringPiece s); // NOLINT }; template <> class GTEST_API_ Matcher<StringPiece> : public internal::MatcherBase<StringPiece> { public: Matcher() {} explicit Matcher(const MatcherInterface<StringPiece>* impl) : internal::MatcherBase<StringPiece>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT // Allows the user to pass StringPieces directly. Matcher(StringPiece s); // NOLINT }; #endif // GTEST_HAS_STRING_PIECE_ // The PolymorphicMatcher class template makes it easy to implement a // polymorphic matcher (i.e. a matcher that can match values of more // than one type, e.g. Eq(n) and NotNull()). // // To define a polymorphic matcher, a user should provide an Impl // class that has a DescribeTo() method and a DescribeNegationTo() // method, and define a member function (or member function template) // // bool MatchAndExplain(const Value& value, // MatchResultListener* listener) const; // // See the definition of NotNull() for a complete example. template <class Impl> class PolymorphicMatcher { public: explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {} // Returns a mutable reference to the underlying matcher // implementation object. Impl& mutable_impl() { return impl_; } // Returns an immutable reference to the underlying matcher // implementation object. const Impl& impl() const { return impl_; } template <typename T> operator Matcher<T>() const { return Matcher<T>(new MonomorphicImpl<T>(impl_)); } private: template <typename T> class MonomorphicImpl : public MatcherInterface<T> { public: explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { impl_.DescribeNegationTo(os); } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_.MatchAndExplain(x, listener); } private: const Impl impl_; GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); }; Impl impl_; GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher); }; // Creates a matcher from its implementation. This is easier to use // than the Matcher<T> constructor as it doesn't require you to // explicitly write the template argument, e.g. // // MakeMatcher(foo); // vs // Matcher<const string&>(foo); template <typename T> inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) { return Matcher<T>(impl); } // Creates a polymorphic matcher from its implementation. This is // easier to use than the PolymorphicMatcher<Impl> constructor as it // doesn't require you to explicitly write the template argument, e.g. // // MakePolymorphicMatcher(foo); // vs // PolymorphicMatcher<TypeOfFoo>(foo); template <class Impl> inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) { return PolymorphicMatcher<Impl>(impl); } // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // The MatcherCastImpl class template is a helper for implementing // MatcherCast(). We need this helper in order to partially // specialize the implementation of MatcherCast() (C++ allows // class/struct templates to be partially specialized, but not // function templates.). // This general version is used when MatcherCast()'s argument is a // polymorphic matcher (i.e. something that can be converted to a // Matcher but is not one yet; for example, Eq(value)) or a value (for // example, "hello"). template <typename T, typename M> class MatcherCastImpl { public: static Matcher<T> Cast(const M& polymorphic_matcher_or_value) { // M can be a polymorhic matcher, in which case we want to use // its conversion operator to create Matcher<T>. Or it can be a value // that should be passed to the Matcher<T>'s constructor. // // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a // polymorphic matcher because it'll be ambiguous if T has an implicit // constructor from M (this usually happens when T has an implicit // constructor from any type). // // It won't work to unconditionally implict_cast // polymorphic_matcher_or_value to Matcher<T> because it won't trigger // a user-defined conversion from M to T if one exists (assuming M is // a value). return CastImpl( polymorphic_matcher_or_value, BooleanConstant< internal::ImplicitlyConvertible<M, Matcher<T> >::value>()); } private: static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) { // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic // matcher. It must be a value then. Use direct initialization to create // a matcher. return Matcher<T>(ImplicitCast_<T>(value)); } static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, BooleanConstant<true>) { // M is implicitly convertible to Matcher<T>, which means that either // M is a polymorhpic matcher or Matcher<T> has an implicit constructor // from M. In both cases using the implicit conversion will produce a // matcher. // // Even if T has an implicit constructor from M, it won't be called because // creating Matcher<T> would require a chain of two user-defined conversions // (first to create T from M and then to create Matcher<T> from T). return polymorphic_matcher_or_value; } }; // This more specialized version is used when MatcherCast()'s argument // is already a Matcher. This only compiles when type T can be // statically converted to type U. template <typename T, typename U> class MatcherCastImpl<T, Matcher<U> > { public: static Matcher<T> Cast(const Matcher<U>& source_matcher) { return Matcher<T>(new Impl(source_matcher)); } private: class Impl : public MatcherInterface<T> { public: explicit Impl(const Matcher<U>& source_matcher) : source_matcher_(source_matcher) {} // We delegate the matching logic to the source matcher. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return source_matcher_.MatchAndExplain(static_cast<U>(x), listener); } virtual void DescribeTo(::std::ostream* os) const { source_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { source_matcher_.DescribeNegationTo(os); } private: const Matcher<U> source_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; }; // This even more specialized version is used for efficiently casting // a matcher to its own type. template <typename T> class MatcherCastImpl<T, Matcher<T> > { public: static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; } }; } // namespace internal // In order to be safe and clear, casting between different matcher // types is done explicitly via MatcherCast<T>(m), which takes a // matcher m and returns a Matcher<T>. It compiles only when T can be // statically converted to the argument type of m. template <typename T, typename M> inline Matcher<T> MatcherCast(const M& matcher) { return internal::MatcherCastImpl<T, M>::Cast(matcher); } // Implements SafeMatcherCast(). // // We use an intermediate class to do the actual safe casting as Nokia's // Symbian compiler cannot decide between // template <T, M> ... (M) and // template <T, U> ... (const Matcher<U>&) // for function templates but can for member function templates. template <typename T> class SafeMatcherCastImpl { public: // This overload handles polymorphic matchers and values only since // monomorphic matchers are handled by the next one. template <typename M> static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) { return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value); } // This overload handles monomorphic matchers. // // In general, if type T can be implicitly converted to type U, we can // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is // contravariant): just keep a copy of the original Matcher<U>, convert the // argument from type T to U, and then pass it to the underlying Matcher<U>. // The only exception is when U is a reference and T is not, as the // underlying Matcher<U> may be interested in the argument's address, which // is not preserved in the conversion from T to U. template <typename U> static inline Matcher<T> Cast(const Matcher<U>& matcher) { // Enforce that T can be implicitly converted to U. GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value), T_must_be_implicitly_convertible_to_U); // Enforce that we are not converting a non-reference type T to a reference // type U. GTEST_COMPILE_ASSERT_( internal::is_reference<T>::value || !internal::is_reference<U>::value, - cannot_convert_non_referentce_arg_to_reference); + cannot_convert_non_reference_arg_to_reference); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; GTEST_COMPILE_ASSERT_( kTIsOther || kUIsOther || (internal::LosslessArithmeticConvertible<RawT, RawU>::value), conversion_of_arithmetic_types_must_be_lossless); return MatcherCast<T>(matcher); } }; template <typename T, typename M> inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) { return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher); } // A<T>() returns a matcher that matches any value of type T. template <typename T> Matcher<T> A(); // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // If the explanation is not empty, prints it to the ostream. inline void PrintIfNotEmpty(const std::string& explanation, ::std::ostream* os) { if (explanation != "" && os != NULL) { *os << ", " << explanation; } } // Returns true if the given type name is easy to read by a human. // This is used to decide whether printing the type of a value might // be helpful. inline bool IsReadableTypeName(const std::string& type_name) { // We consider a type name readable if it's short or doesn't contain // a template or function type. return (type_name.length() <= 20 || type_name.find_first_of("<(") == std::string::npos); } // Matches the value against the given matcher, prints the value and explains // the match result to the listener. Returns the match result. // 'listener' must not be NULL. // Value cannot be passed by const reference, because some matchers take a // non-const argument. template <typename Value, typename T> bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher, MatchResultListener* listener) { if (!listener->IsInterested()) { // If the listener is not interested, we do not need to construct the // inner explanation. return matcher.Matches(value); } StringMatchResultListener inner_listener; const bool match = matcher.MatchAndExplain(value, &inner_listener); UniversalPrint(value, listener->stream()); #if GTEST_HAS_RTTI const std::string& type_name = GetTypeName<Value>(); if (IsReadableTypeName(type_name)) *listener->stream() << " (of type " << type_name << ")"; #endif PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } // An internal helper class for doing compile-time loop on a tuple's // fields. template <size_t N> class TuplePrefix { public: // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true // iff the first N fields of matcher_tuple matches the first N // fields of value_tuple, respectively. template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple)); } // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os) // describes failures in matching the first N fields of matchers // against the first N fields of values. If there is no failure, // nothing will be streamed to os. template <typename MatcherTuple, typename ValueTuple> static void ExplainMatchFailuresTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { // First, describes failures in the first N - 1 fields. TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os); // Then describes the failure (if any) in the (N - 1)-th (0-based) // field. typename tuple_element<N - 1, MatcherTuple>::type matcher = get<N - 1>(matchers); typedef typename tuple_element<N - 1, ValueTuple>::type Value; Value value = get<N - 1>(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { // TODO(wan): include in the message the name of the parameter // as used in MOCK_METHOD*() when possible. *os << " Expected arg #" << N - 1 << ": "; get<N - 1>(matchers).DescribeTo(os); *os << "\n Actual: "; // We remove the reference in type Value to prevent the // universal printer from printing the address of value, which // isn't interesting to the user most of the time. The // matcher's MatchAndExplain() method handles the case when // the address is interesting. internal::UniversalPrint(value, os); PrintIfNotEmpty(listener.str(), os); *os << "\n"; } } }; // The base case. template <> class TuplePrefix<0> { public: template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& /* matcher_tuple */, const ValueTuple& /* value_tuple */) { return true; } template <typename MatcherTuple, typename ValueTuple> static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, const ValueTuple& /* values */, ::std::ostream* /* os */) {} }; // TupleMatches(matcher_tuple, value_tuple) returns true iff all // matchers in matcher_tuple match the corresponding fields in // value_tuple. It is a compiler error if matcher_tuple and // value_tuple have different number of fields or incompatible field // types. template <typename MatcherTuple, typename ValueTuple> bool TupleMatches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { // Makes sure that matcher_tuple and value_tuple have the same // number of fields. GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value == tuple_size<ValueTuple>::value, matcher_and_value_have_different_numbers_of_fields); return TuplePrefix<tuple_size<ValueTuple>::value>:: Matches(matcher_tuple, value_tuple); } // Describes failures in matching matchers against values. If there // is no failure, nothing will be streamed to os. template <typename MatcherTuple, typename ValueTuple> void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( matchers, values, os); } // TransformTupleValues and its helper. // // TransformTupleValuesHelper hides the internal machinery that // TransformTupleValues uses to implement a tuple traversal. template <typename Tuple, typename Func, typename OutIter> class TransformTupleValuesHelper { private: typedef ::testing::tuple_size<Tuple> TupleSize; public: // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. // Returns the final value of 'out' in case the caller needs it. static OutIter Run(Func f, const Tuple& t, OutIter out) { return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out); } private: template <typename Tup, size_t kRemainingSize> struct IterateOverTuple { OutIter operator() (Func f, const Tup& t, OutIter out) const { *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t)); return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out); } }; template <typename Tup> struct IterateOverTuple<Tup, 0> { OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const { return out; } }; }; // Successively invokes 'f(element)' on each element of the tuple 't', // appending each result to the 'out' iterator. Returns the final value // of 'out'. template <typename Tuple, typename Func, typename OutIter> OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out); } // Implements A<T>(). template <typename T> class AnyMatcherImpl : public MatcherInterface<T> { public: virtual bool MatchAndExplain( T /* x */, MatchResultListener* /* listener */) const { return true; } virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; } virtual void DescribeNegationTo(::std::ostream* os) const { // This is mostly for completeness' safe, as it's not very useful // to write Not(A<bool>()). However we cannot completely rule out // such a possibility, and it doesn't hurt to be prepared. *os << "never matches"; } }; // Implements _, a matcher that matches any value of any // type. This is a polymorphic matcher, so we need a template type // conversion operator to make it appearing as a Matcher<T> for any // type T. class AnythingMatcher { public: template <typename T> operator Matcher<T>() const { return A<T>(); } }; // Implements a matcher that compares a given value with a // pre-supplied value using one of the ==, <=, <, etc, operators. The // two values being compared don't have to have the same type. // // The matcher defined here is polymorphic (for example, Eq(5) can be // used to match an int, a short, a double, etc). Therefore we use // a template type conversion operator in the implementation. // // The following template definition assumes that the Rhs parameter is // a "bare" type (i.e. neither 'const T' nor 'T&'). template <typename D, typename Rhs, typename Op> class ComparisonBase { public: explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {} template <typename Lhs> operator Matcher<Lhs>() const { return MakeMatcher(new Impl<Lhs>(rhs_)); } private: template <typename Lhs> class Impl : public MatcherInterface<Lhs> { public: explicit Impl(const Rhs& rhs) : rhs_(rhs) {} virtual bool MatchAndExplain( Lhs lhs, MatchResultListener* /* listener */) const { return Op()(lhs, rhs_); } virtual void DescribeTo(::std::ostream* os) const { *os << D::Desc() << " "; UniversalPrint(rhs_, os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << D::NegatedDesc() << " "; UniversalPrint(rhs_, os); } private: Rhs rhs_; GTEST_DISALLOW_ASSIGN_(Impl); }; Rhs rhs_; GTEST_DISALLOW_ASSIGN_(ComparisonBase); }; template <typename Rhs> class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> { public: explicit EqMatcher(const Rhs& rhs) : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { } static const char* Desc() { return "is equal to"; } static const char* NegatedDesc() { return "isn't equal to"; } }; template <typename Rhs> class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> { public: explicit NeMatcher(const Rhs& rhs) : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { } static const char* Desc() { return "isn't equal to"; } static const char* NegatedDesc() { return "is equal to"; } }; template <typename Rhs> class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> { public: explicit LtMatcher(const Rhs& rhs) : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { } static const char* Desc() { return "is <"; } static const char* NegatedDesc() { return "isn't <"; } }; template <typename Rhs> class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> { public: explicit GtMatcher(const Rhs& rhs) : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { } static const char* Desc() { return "is >"; } static const char* NegatedDesc() { return "isn't >"; } }; template <typename Rhs> class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> { public: explicit LeMatcher(const Rhs& rhs) : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { } static const char* Desc() { return "is <="; } static const char* NegatedDesc() { return "isn't <="; } }; template <typename Rhs> class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> { public: explicit GeMatcher(const Rhs& rhs) : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { } static const char* Desc() { return "is >="; } static const char* NegatedDesc() { return "isn't >="; } }; // Implements the polymorphic IsNull() matcher, which matches any raw or smart // pointer that is NULL. class IsNullMatcher { public: template <typename Pointer> bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { #if GTEST_LANG_CXX11 return p == nullptr; #else // GTEST_LANG_CXX11 return GetRawPointer(p) == NULL; #endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; } }; // Implements the polymorphic NotNull() matcher, which matches any raw or smart // pointer that is not NULL. class NotNullMatcher { public: template <typename Pointer> bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { #if GTEST_LANG_CXX11 return p != nullptr; #else // GTEST_LANG_CXX11 return GetRawPointer(p) != NULL; #endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } }; // Ref(variable) matches any argument that is a reference to // 'variable'. This matcher is polymorphic as it can match any // super type of the type of 'variable'. // // The RefMatcher template class implements Ref(variable). It can // only be instantiated with a reference type. This prevents a user // from mistakenly using Ref(x) to match a non-reference function // argument. For example, the following will righteously cause a // compiler error: // // int n; // Matcher<int> m1 = Ref(n); // This won't compile. // Matcher<int&> m2 = Ref(n); // This will compile. template <typename T> class RefMatcher; template <typename T> class RefMatcher<T&> { // Google Mock is a generic framework and thus needs to support // mocking any function types, including those that take non-const // reference arguments. Therefore the template parameter T (and // Super below) can be instantiated to either a const type or a // non-const type. public: // RefMatcher() takes a T& instead of const T&, as we want the // compiler to catch using Ref(const_value) as a matcher for a // non-const reference. explicit RefMatcher(T& x) : object_(x) {} // NOLINT template <typename Super> operator Matcher<Super&>() const { // By passing object_ (type T&) to Impl(), which expects a Super&, // we make sure that Super is a super type of T. In particular, // this catches using Ref(const_value) as a matcher for a // non-const reference, as you cannot implicitly convert a const // reference to a non-const reference. return MakeMatcher(new Impl<Super>(object_)); } private: template <typename Super> class Impl : public MatcherInterface<Super&> { public: explicit Impl(Super& x) : object_(x) {} // NOLINT // MatchAndExplain() takes a Super& (as opposed to const Super&) // in order to match the interface MatcherInterface<Super&>. virtual bool MatchAndExplain( Super& x, MatchResultListener* listener) const { *listener << "which is located @" << static_cast<const void*>(&x); return &x == &object_; } virtual void DescribeTo(::std::ostream* os) const { *os << "references the variable "; UniversalPrinter<Super&>::Print(object_, os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "does not reference the variable "; UniversalPrinter<Super&>::Print(object_, os); } private: const Super& object_; GTEST_DISALLOW_ASSIGN_(Impl); }; T& object_; GTEST_DISALLOW_ASSIGN_(RefMatcher); }; // Polymorphic helper functions for narrow and wide string matchers. inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { return String::CaseInsensitiveCStringEquals(lhs, rhs); } inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { return String::CaseInsensitiveWideCStringEquals(lhs, rhs); } // String comparison for narrow or wide strings that can have embedded NUL // characters. template <typename StringType> bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) { // Are the heads equal? if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { return false; } // Skip the equal heads. const typename StringType::value_type nul = 0; const size_t i1 = s1.find(nul), i2 = s2.find(nul); // Are we at the end of either s1 or s2? if (i1 == StringType::npos || i2 == StringType::npos) { return i1 == i2; } // Are the tails equal? return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1)); } // String matchers. // Implements equality-based string matchers like StrEq, StrCaseNe, and etc. template <typename StringType> class StrEqualityMatcher { public: StrEqualityMatcher(const StringType& str, bool expect_eq, bool case_sensitive) : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { if (s == NULL) { return !expect_eq_; } return MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); const bool eq = case_sensitive_ ? s2 == string_ : CaseInsensitiveStringEquals(s2, string_); return expect_eq_ == eq; } void DescribeTo(::std::ostream* os) const { DescribeToHelper(expect_eq_, os); } void DescribeNegationTo(::std::ostream* os) const { DescribeToHelper(!expect_eq_, os); } private: void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { *os << (expect_eq ? "is " : "isn't "); *os << "equal to "; if (!case_sensitive_) { *os << "(ignoring case) "; } UniversalPrint(string_, os); } const StringType string_; const bool expect_eq_; const bool case_sensitive_; GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher); }; // Implements the polymorphic HasSubstr(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class HasSubstrMatcher { public: explicit HasSubstrMatcher(const StringType& substring) : substring_(substring) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.find(substring_) != StringType::npos; } // Describes what this matcher matches. void DescribeTo(::std::ostream* os) const { *os << "has substring "; UniversalPrint(substring_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "has no substring "; UniversalPrint(substring_, os); } private: const StringType substring_; GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher); }; // Implements the polymorphic StartsWith(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class StartsWithMatcher { public: explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { } // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.length() >= prefix_.length() && s2.substr(0, prefix_.length()) == prefix_; } void DescribeTo(::std::ostream* os) const { *os << "starts with "; UniversalPrint(prefix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't start with "; UniversalPrint(prefix_, os); } private: const StringType prefix_; GTEST_DISALLOW_ASSIGN_(StartsWithMatcher); }; // Implements the polymorphic EndsWith(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class EndsWithMatcher { public: explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.length() >= suffix_.length() && s2.substr(s2.length() - suffix_.length()) == suffix_; } void DescribeTo(::std::ostream* os) const { *os << "ends with "; UniversalPrint(suffix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't end with "; UniversalPrint(suffix_, os); } private: const StringType suffix_; GTEST_DISALLOW_ASSIGN_(EndsWithMatcher); }; // Implements polymorphic matchers MatchesRegex(regex) and // ContainsRegex(regex), which can be used as a Matcher<T> as long as // T can be converted to a string. class MatchesRegexMatcher { public: MatchesRegexMatcher(const RE* regex, bool full_match) : regex_(regex), full_match_(full_match) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(std::string(s), listener); } // Matches anything that can convert to std::string. // // This is a template, not just a plain function with const std::string&, // because StringPiece has some interfering non-explicit constructors. template <class MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const std::string& s2(s); return full_match_ ? RE::FullMatch(s2, *regex_) : RE::PartialMatch(s2, *regex_); } void DescribeTo(::std::ostream* os) const { *os << (full_match_ ? "matches" : "contains") << " regular expression "; UniversalPrinter<std::string>::Print(regex_->pattern(), os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't " << (full_match_ ? "match" : "contain") << " regular expression "; UniversalPrinter<std::string>::Print(regex_->pattern(), os); } private: const internal::linked_ptr<const RE> regex_; const bool full_match_; GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher); }; // Implements a matcher that compares the two fields of a 2-tuple // using one of the ==, <=, <, etc, operators. The two fields being // compared don't have to have the same type. // // The matcher defined here is polymorphic (for example, Eq() can be // used to match a tuple<int, short>, a tuple<const long&, double>, // etc). Therefore we use a template type conversion operator in the // implementation. template <typename D, typename Op> class PairMatchBase { public: template <typename T1, typename T2> operator Matcher< ::testing::tuple<T1, T2> >() const { return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >); } template <typename T1, typename T2> operator Matcher<const ::testing::tuple<T1, T2>&>() const { return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>); } private: static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT return os << D::Desc(); } template <typename Tuple> class Impl : public MatcherInterface<Tuple> { public: virtual bool MatchAndExplain( Tuple args, MatchResultListener* /* listener */) const { return Op()(::testing::get<0>(args), ::testing::get<1>(args)); } virtual void DescribeTo(::std::ostream* os) const { *os << "are " << GetDesc; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "aren't " << GetDesc; } }; }; class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> { public: static const char* Desc() { return "an equal pair"; } }; class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> { public: static const char* Desc() { return "an unequal pair"; } }; class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> { public: static const char* Desc() { return "a pair where the first < the second"; } }; class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> { public: static const char* Desc() { return "a pair where the first > the second"; } }; class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> { public: static const char* Desc() { return "a pair where the first <= the second"; } }; class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> { public: static const char* Desc() { return "a pair where the first >= the second"; } }; // Implements the Not(...) matcher for a particular argument type T. // We do not nest it inside the NotMatcher class template, as that // will prevent different instantiations of NotMatcher from sharing // the same NotMatcherImpl<T> class. template <typename T> class NotMatcherImpl : public MatcherInterface<T> { public: explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {} virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return !matcher_.MatchAndExplain(x, listener); } virtual void DescribeTo(::std::ostream* os) const { matcher_.DescribeNegationTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { matcher_.DescribeTo(os); } private: const Matcher<T> matcher_; GTEST_DISALLOW_ASSIGN_(NotMatcherImpl); }; // Implements the Not(m) matcher, which matches a value that doesn't // match matcher m. template <typename InnerMatcher> class NotMatcher { public: explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {} // This template type conversion operator allows Not(m) to be used // to match any type m can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_))); } private: InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(NotMatcher); }; // Implements the AllOf(m1, m2) matcher for a particular argument type // T. We do not nest it inside the BothOfMatcher class template, as // that will prevent different instantiations of BothOfMatcher from // sharing the same BothOfMatcherImpl<T> class. template <typename T> class BothOfMatcherImpl : public MatcherInterface<T> { public: BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeTo(os); *os << ") and ("; matcher2_.DescribeTo(os); *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeNegationTo(os); *os << ") or ("; matcher2_.DescribeNegationTo(os); *os << ")"; } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { // If either matcher1_ or matcher2_ doesn't match x, we only need // to explain why one of them fails. StringMatchResultListener listener1; if (!matcher1_.MatchAndExplain(x, &listener1)) { *listener << listener1.str(); return false; } StringMatchResultListener listener2; if (!matcher2_.MatchAndExplain(x, &listener2)) { *listener << listener2.str(); return false; } // Otherwise we need to explain why *both* of them match. const std::string s1 = listener1.str(); const std::string s2 = listener2.str(); if (s1 == "") { *listener << s2; } else { *listener << s1; if (s2 != "") { *listener << ", and " << s2; } } return true; } private: const Matcher<T> matcher1_; const Matcher<T> matcher2_; GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl); }; #if GTEST_LANG_CXX11 // MatcherList provides mechanisms for storing a variable number of matchers in // a list structure (ListType) and creating a combining matcher from such a // list. // The template is defined recursively using the following template paramters: // * kSize is the length of the MatcherList. // * Head is the type of the first matcher of the list. // * Tail denotes the types of the remaining matchers of the list. template <int kSize, typename Head, typename... Tail> struct MatcherList { typedef MatcherList<kSize - 1, Tail...> MatcherListTail; typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType; // BuildList stores variadic type values in a nested pair structure. // Example: // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return // the corresponding result of type pair<int, pair<string, float>>. static ListType BuildList(const Head& matcher, const Tail&... tail) { return ListType(matcher, MatcherListTail::BuildList(tail...)); } // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a // constructor taking two Matcher<T>s as input. template <typename T, template <typename /* T */> class CombiningMatcher> static Matcher<T> CreateMatcher(const ListType& matchers) { return Matcher<T>(new CombiningMatcher<T>( SafeMatcherCast<T>(matchers.first), MatcherListTail::template CreateMatcher<T, CombiningMatcher>( matchers.second))); } }; // The following defines the base case for the recursive definition of // MatcherList. template <typename Matcher1, typename Matcher2> struct MatcherList<2, Matcher1, Matcher2> { typedef ::std::pair<Matcher1, Matcher2> ListType; static ListType BuildList(const Matcher1& matcher1, const Matcher2& matcher2) { return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2); } template <typename T, template <typename /* T */> class CombiningMatcher> static Matcher<T> CreateMatcher(const ListType& matchers) { return Matcher<T>(new CombiningMatcher<T>( SafeMatcherCast<T>(matchers.first), SafeMatcherCast<T>(matchers.second))); } }; // VariadicMatcher is used for the variadic implementation of // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). // CombiningMatcher<T> is used to recursively combine the provided matchers // (of type Args...). template <template <typename T> class CombiningMatcher, typename... Args> class VariadicMatcher { public: VariadicMatcher(const Args&... matchers) // NOLINT : matchers_(MatcherListType::BuildList(matchers...)) {} // This template type conversion operator allows an // VariadicMatcher<Matcher1, Matcher2...> object to match any type that // all of the provided matchers (Matcher1, Matcher2, ...) can match. template <typename T> operator Matcher<T>() const { return MatcherListType::template CreateMatcher<T, CombiningMatcher>( matchers_); } private: typedef MatcherList<sizeof...(Args), Args...> MatcherListType; const typename MatcherListType::ListType matchers_; GTEST_DISALLOW_ASSIGN_(VariadicMatcher); }; template <typename... Args> using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>; #endif // GTEST_LANG_CXX11 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which // matches a value that matches all of the matchers m_1, ..., and m_n. template <typename Matcher1, typename Matcher2> class BothOfMatcher { public: BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // BothOfMatcher<Matcher1, Matcher2> object to match any type that // both Matcher1 and Matcher2 can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); } private: Matcher1 matcher1_; Matcher2 matcher2_; GTEST_DISALLOW_ASSIGN_(BothOfMatcher); }; // Implements the AnyOf(m1, m2) matcher for a particular argument type // T. We do not nest it inside the AnyOfMatcher class template, as // that will prevent different instantiations of AnyOfMatcher from // sharing the same EitherOfMatcherImpl<T> class. template <typename T> class EitherOfMatcherImpl : public MatcherInterface<T> { public: EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeTo(os); *os << ") or ("; matcher2_.DescribeTo(os); *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeNegationTo(os); *os << ") and ("; matcher2_.DescribeNegationTo(os); *os << ")"; } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { // If either matcher1_ or matcher2_ matches x, we just need to // explain why *one* of them matches. StringMatchResultListener listener1; if (matcher1_.MatchAndExplain(x, &listener1)) { *listener << listener1.str(); return true; } StringMatchResultListener listener2; if (matcher2_.MatchAndExplain(x, &listener2)) { *listener << listener2.str(); return true; } // Otherwise we need to explain why *both* of them fail. const std::string s1 = listener1.str(); const std::string s2 = listener2.str(); if (s1 == "") { *listener << s2; } else { *listener << s1; if (s2 != "") { *listener << ", and " << s2; } } return false; } private: const Matcher<T> matcher1_; const Matcher<T> matcher2_; GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl); }; #if GTEST_LANG_CXX11 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). template <typename... Args> using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>; #endif // GTEST_LANG_CXX11 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which // matches a value that matches at least one of the matchers m_1, ..., // and m_n. template <typename Matcher1, typename Matcher2> class EitherOfMatcher { public: EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // EitherOfMatcher<Matcher1, Matcher2> object to match any type that // both Matcher1 and Matcher2 can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new EitherOfMatcherImpl<T>( SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); } private: Matcher1 matcher1_; Matcher2 matcher2_; GTEST_DISALLOW_ASSIGN_(EitherOfMatcher); }; // Used for implementing Truly(pred), which turns a predicate into a // matcher. template <typename Predicate> class TrulyMatcher { public: explicit TrulyMatcher(Predicate pred) : predicate_(pred) {} // This method template allows Truly(pred) to be used as a matcher // for type T where T is the argument type of predicate 'pred'. The // argument is passed by reference as the predicate may be // interested in the address of the argument. template <typename T> bool MatchAndExplain(T& x, // NOLINT MatchResultListener* /* listener */) const { // Without the if-statement, MSVC sometimes warns about converting // a value to bool (warning 4800). // // We cannot write 'return !!predicate_(x);' as that doesn't work // when predicate_(x) returns a class convertible to bool but // having no operator!(). if (predicate_(x)) return true; return false; } void DescribeTo(::std::ostream* os) const { *os << "satisfies the given predicate"; } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't satisfy the given predicate"; } private: Predicate predicate_; GTEST_DISALLOW_ASSIGN_(TrulyMatcher); }; // Used for implementing Matches(matcher), which turns a matcher into // a predicate. template <typename M> class MatcherAsPredicate { public: explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {} // This template operator() allows Matches(m) to be used as a // predicate on type T where m is a matcher on type T. // // The argument x is passed by reference instead of by value, as // some matcher may be interested in its address (e.g. as in // Matches(Ref(n))(x)). template <typename T> bool operator()(const T& x) const { // We let matcher_ commit to a particular type here instead of // when the MatcherAsPredicate object was constructed. This // allows us to write Matches(m) where m is a polymorphic matcher // (e.g. Eq(5)). // // If we write Matcher<T>(matcher_).Matches(x) here, it won't // compile when matcher_ has type Matcher<const T&>; if we write // Matcher<const T&>(matcher_).Matches(x) here, it won't compile // when matcher_ has type Matcher<T>; if we just write // matcher_.Matches(x), it won't compile when matcher_ is // polymorphic, e.g. Eq(5). // // MatcherCast<const T&>() is necessary for making the code work // in all of the above situations. return MatcherCast<const T&>(matcher_).Matches(x); } private: M matcher_; GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate); }; // For implementing ASSERT_THAT() and EXPECT_THAT(). The template // argument M must be a type that can be converted to a matcher. template <typename M> class PredicateFormatterFromMatcher { public: explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {} // This template () operator allows a PredicateFormatterFromMatcher // object to act as a predicate-formatter suitable for using with // Google Test's EXPECT_PRED_FORMAT1() macro. template <typename T> AssertionResult operator()(const char* value_text, const T& x) const { // We convert matcher_ to a Matcher<const T&> *now* instead of // when the PredicateFormatterFromMatcher object was constructed, // as matcher_ may be polymorphic (e.g. NotNull()) and we won't // know which type to instantiate it to until we actually see the // type of x here. // // We write SafeMatcherCast<const T&>(matcher_) instead of // Matcher<const T&>(matcher_), as the latter won't compile when // matcher_ has type Matcher<T> (e.g. An<int>()). // We don't write MatcherCast<const T&> either, as that allows // potentially unsafe downcasting of the matcher argument. const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_); StringMatchResultListener listener; if (MatchPrintAndExplain(x, matcher, &listener)) return AssertionSuccess(); ::std::stringstream ss; ss << "Value of: " << value_text << "\n" << "Expected: "; matcher.DescribeTo(&ss); ss << "\n Actual: " << listener.str(); return AssertionFailure() << ss.str(); } private: const M matcher_; GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher); }; // A helper function for converting a matcher to a predicate-formatter // without the user needing to explicitly write the type. This is // used for implementing ASSERT_THAT() and EXPECT_THAT(). // Implementation detail: 'matcher' is received by-value to force decaying. template <typename M> inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(M matcher) { return PredicateFormatterFromMatcher<M>(internal::move(matcher)); } // Implements the polymorphic floating point equality matcher, which matches // two float values using ULP-based approximation or, optionally, a // user-specified epsilon. The template is meant to be instantiated with // FloatType being either float or double. template <typename FloatType> class FloatingEqMatcher { public: // Constructor for FloatingEqMatcher. // The matcher's input will be compared with expected. The matcher treats two // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards, // equality comparisons between NANs will always return false. We specify a // negative max_abs_error_ term to indicate that ULP-based approximation will // be used for comparison. FloatingEqMatcher(FloatType expected, bool nan_eq_nan) : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) { } // Constructor that supports a user-specified max_abs_error that will be used // for comparison instead of ULP-based approximation. The max absolute // should be non-negative. FloatingEqMatcher(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) { GTEST_CHECK_(max_abs_error >= 0) << ", where max_abs_error is" << max_abs_error; } // Implements floating point equality matcher as a Matcher<T>. template <typename T> class Impl : public MatcherInterface<T> { public: Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {} virtual bool MatchAndExplain(T value, MatchResultListener* listener) const { const FloatingPoint<FloatType> actual(value), expected(expected_); // Compares NaNs first, if nan_eq_nan_ is true. if (actual.is_nan() || expected.is_nan()) { if (actual.is_nan() && expected.is_nan()) { return nan_eq_nan_; } // One is nan; the other is not nan. return false; } if (HasMaxAbsError()) { // We perform an equality check so that inf will match inf, regardless // of error bounds. If the result of value - expected_ would result in // overflow or if either value is inf, the default result is infinity, // which should only match if max_abs_error_ is also infinity. if (value == expected_) { return true; } const FloatType diff = value - expected_; if (fabs(diff) <= max_abs_error_) { return true; } if (listener->IsInterested()) { *listener << "which is " << diff << " from " << expected_; } return false; } else { return actual.AlmostEquals(expected); } } virtual void DescribeTo(::std::ostream* os) const { // os->precision() returns the previously set precision, which we // store to restore the ostream to its original configuration // after outputting. const ::std::streamsize old_precision = os->precision( ::std::numeric_limits<FloatType>::digits10 + 2); if (FloatingPoint<FloatType>(expected_).is_nan()) { if (nan_eq_nan_) { *os << "is NaN"; } else { *os << "never matches"; } } else { *os << "is approximately " << expected_; if (HasMaxAbsError()) { *os << " (absolute error <= " << max_abs_error_ << ")"; } } os->precision(old_precision); } virtual void DescribeNegationTo(::std::ostream* os) const { // As before, get original precision. const ::std::streamsize old_precision = os->precision( ::std::numeric_limits<FloatType>::digits10 + 2); if (FloatingPoint<FloatType>(expected_).is_nan()) { if (nan_eq_nan_) { *os << "isn't NaN"; } else { *os << "is anything"; } } else { *os << "isn't approximately " << expected_; if (HasMaxAbsError()) { *os << " (absolute error > " << max_abs_error_ << ")"; } } // Restore original precision. os->precision(old_precision); } private: bool HasMaxAbsError() const { return max_abs_error_ >= 0; } const FloatType expected_; const bool nan_eq_nan_; // max_abs_error will be used for value comparison when >= 0. const FloatType max_abs_error_; GTEST_DISALLOW_ASSIGN_(Impl); }; // The following 3 type conversion operators allow FloatEq(expected) and // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a // Matcher<const float&>, or a Matcher<float&>, but nothing else. // (While Google's C++ coding style doesn't allow arguments passed // by non-const reference, we may see them in code not conforming to // the style. Therefore Google Mock needs to support them.) operator Matcher<FloatType>() const { return MakeMatcher( new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_)); } operator Matcher<const FloatType&>() const { return MakeMatcher( new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); } operator Matcher<FloatType&>() const { return MakeMatcher( new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); } private: const FloatType expected_; const bool nan_eq_nan_; // max_abs_error will be used for value comparison when >= 0. const FloatType max_abs_error_; GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher); }; // Implements the Pointee(m) matcher for matching a pointer whose // pointee matches matcher m. The pointer can be either raw or smart. template <typename InnerMatcher> class PointeeMatcher { public: explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {} // This type conversion operator template allows Pointee(m) to be // used as a matcher for any pointer type whose pointee type is // compatible with the inner matcher, where type Pointer can be // either a raw pointer or a smart pointer. // // The reason we do this instead of relying on // MakePolymorphicMatcher() is that the latter is not flexible // enough for implementing the DescribeTo() method of Pointee(). template <typename Pointer> operator Matcher<Pointer>() const { return MakeMatcher(new Impl<Pointer>(matcher_)); } private: // The monomorphic implementation that works for a particular pointer type. template <typename Pointer> class Impl : public MatcherInterface<Pointer> { public: typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee; explicit Impl(const InnerMatcher& matcher) : matcher_(MatcherCast<const Pointee&>(matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "points to a value that "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "does not point to a value that "; matcher_.DescribeTo(os); } virtual bool MatchAndExplain(Pointer pointer, MatchResultListener* listener) const { if (GetRawPointer(pointer) == NULL) return false; *listener << "which points to "; return MatchPrintAndExplain(*pointer, matcher_, listener); } private: const Matcher<const Pointee&> matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; const InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(PointeeMatcher); }; // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or // reference that matches inner_matcher when dynamic_cast<T> is applied. // The result of dynamic_cast<To> is forwarded to the inner matcher. // If To is a pointer and the cast fails, the inner matcher will receive NULL. // If To is a reference and the cast fails, this matcher returns false // immediately. template <typename To> class WhenDynamicCastToMatcherBase { public: explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher) : matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { GetCastTypeDescription(os); matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { GetCastTypeDescription(os); matcher_.DescribeNegationTo(os); } protected: const Matcher<To> matcher_; static std::string GetToName() { #if GTEST_HAS_RTTI return GetTypeName<To>(); #else // GTEST_HAS_RTTI return "the target type"; #endif // GTEST_HAS_RTTI } private: static void GetCastTypeDescription(::std::ostream* os) { *os << "when dynamic_cast to " << GetToName() << ", "; } GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase); }; // Primary template. // To is a pointer. Cast and forward the result. template <typename To> class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> { public: explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher) : WhenDynamicCastToMatcherBase<To>(matcher) {} template <typename From> bool MatchAndExplain(From from, MatchResultListener* listener) const { // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail? To to = dynamic_cast<To>(from); return MatchPrintAndExplain(to, this->matcher_, listener); } }; // Specialize for references. // In this case we return false if the dynamic_cast fails. template <typename To> class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> { public: explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher) : WhenDynamicCastToMatcherBase<To&>(matcher) {} template <typename From> bool MatchAndExplain(From& from, MatchResultListener* listener) const { // We don't want an std::bad_cast here, so do the cast with pointers. To* to = dynamic_cast<To*>(&from); if (to == NULL) { *listener << "which cannot be dynamic_cast to " << this->GetToName(); return false; } return MatchPrintAndExplain(*to, this->matcher_, listener); } }; // Implements the Field() matcher for matching a field (i.e. member // variable) of an object. template <typename Class, typename FieldType> class FieldMatcher { public: FieldMatcher(FieldType Class::*field, const Matcher<const FieldType&>& matcher) : field_(field), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { *os << "is an object whose given field "; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { *os << "is an object whose given field "; matcher_.DescribeNegationTo(os); } template <typename T> bool MatchAndExplain(const T& value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Field() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given field is "; return MatchPrintAndExplain(obj.*field_, matcher_, listener); } bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a field, it must be a class/struct/union type and // thus cannot be a pointer. Therefore we pass false_type() as // the first argument. return MatchAndExplainImpl(false_type(), *p, listener); } const FieldType Class::*field_; const Matcher<const FieldType&> matcher_; GTEST_DISALLOW_ASSIGN_(FieldMatcher); }; // Implements the Property() matcher for matching a property // (i.e. return value of a getter method) of an object. template <typename Class, typename PropertyType> class PropertyMatcher { public: // The property may have a reference type, so 'const PropertyType&' // may cause double references and fail to compile. That's why we // need GTEST_REFERENCE_TO_CONST, which works regardless of // PropertyType being a reference or not. typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; PropertyMatcher(PropertyType (Class::*property)() const, const Matcher<RefToConstProperty>& matcher) : property_(property), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { *os << "is an object whose given property "; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { *os << "is an object whose given property "; matcher_.DescribeNegationTo(os); } template <typename T> bool MatchAndExplain(const T&value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Property() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given property is "; // Cannot pass the return value (for example, int) to MatchPrintAndExplain, // which takes a non-const reference as argument. #if defined(_PREFAST_ ) && _MSC_VER == 1800 // Workaround bug in VC++ 2013's /analyze parser. // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move posix::Abort(); // To make sure it is never run. return false; #else RefToConstProperty result = (obj.*property_)(); return MatchPrintAndExplain(result, matcher_, listener); #endif } bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a property method, it must be a class/struct/union // type and thus cannot be a pointer. Therefore we pass // false_type() as the first argument. return MatchAndExplainImpl(false_type(), *p, listener); } PropertyType (Class::*property_)() const; const Matcher<RefToConstProperty> matcher_; GTEST_DISALLOW_ASSIGN_(PropertyMatcher); }; // Type traits specifying various features of different functors for ResultOf. // The default template specifies features for functor objects. // Functor classes have to typedef argument_type and result_type // to be compatible with ResultOf. template <typename Functor> struct CallableTraits { typedef typename Functor::result_type ResultType; typedef Functor StorageType; static void CheckIsValid(Functor /* functor */) {} template <typename T> static ResultType Invoke(Functor f, T arg) { return f(arg); } }; // Specialization for function pointers. template <typename ArgType, typename ResType> struct CallableTraits<ResType(*)(ArgType)> { typedef ResType ResultType; typedef ResType(*StorageType)(ArgType); static void CheckIsValid(ResType(*f)(ArgType)) { GTEST_CHECK_(f != NULL) << "NULL function pointer is passed into ResultOf()."; } template <typename T> static ResType Invoke(ResType(*f)(ArgType), T arg) { return (*f)(arg); } }; // Implements the ResultOf() matcher for matching a return value of a // unary function of an object. template <typename Callable> class ResultOfMatcher { public: typedef typename CallableTraits<Callable>::ResultType ResultType; ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher) : callable_(callable), matcher_(matcher) { CallableTraits<Callable>::CheckIsValid(callable_); } template <typename T> operator Matcher<T>() const { return Matcher<T>(new Impl<T>(callable_, matcher_)); } private: typedef typename CallableTraits<Callable>::StorageType CallableStorageType; template <typename T> class Impl : public MatcherInterface<T> { public: Impl(CallableStorageType callable, const Matcher<ResultType>& matcher) : callable_(callable), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const { *listener << "which is mapped by the given callable to "; // Cannot pass the return value (for example, int) to // MatchPrintAndExplain, which takes a non-const reference as argument. ResultType result = CallableTraits<Callable>::template Invoke<T>(callable_, obj); return MatchPrintAndExplain(result, matcher_, listener); } private: // Functors often define operator() as non-const method even though // they are actualy stateless. But we need to use them even when // 'this' is a const pointer. It's the user's responsibility not to // use stateful callables with ResultOf(), which does't guarantee // how many times the callable will be invoked. mutable CallableStorageType callable_; const Matcher<ResultType> matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; // class Impl const CallableStorageType callable_; const Matcher<ResultType> matcher_; GTEST_DISALLOW_ASSIGN_(ResultOfMatcher); }; // Implements a matcher that checks the size of an STL-style container. template <typename SizeMatcher> class SizeIsMatcher { public: explicit SizeIsMatcher(const SizeMatcher& size_matcher) : size_matcher_(size_matcher) { } template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new Impl<Container>(size_matcher_)); } template <typename Container> class Impl : public MatcherInterface<Container> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; typedef typename ContainerView::type::size_type SizeType; explicit Impl(const SizeMatcher& size_matcher) : size_matcher_(MatcherCast<SizeType>(size_matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "size "; size_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "size "; size_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { SizeType size = container.size(); StringMatchResultListener size_listener; const bool result = size_matcher_.MatchAndExplain(size, &size_listener); *listener << "whose size " << size << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(size_listener.str(), listener->stream()); return result; } private: const Matcher<SizeType> size_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const SizeMatcher size_matcher_; GTEST_DISALLOW_ASSIGN_(SizeIsMatcher); }; // Implements a matcher that checks the begin()..end() distance of an STL-style // container. template <typename DistanceMatcher> class BeginEndDistanceIsMatcher { public: explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) : distance_matcher_(distance_matcher) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new Impl<Container>(distance_matcher_)); } template <typename Container> class Impl : public MatcherInterface<Container> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; typedef typename std::iterator_traits< typename ContainerView::type::const_iterator>::difference_type DistanceType; explicit Impl(const DistanceMatcher& distance_matcher) : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "distance between begin() and end() "; distance_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "distance between begin() and end() "; distance_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { #if GTEST_HAS_STD_BEGIN_AND_END_ using std::begin; using std::end; DistanceType distance = std::distance(begin(container), end(container)); #else DistanceType distance = std::distance(container.begin(), container.end()); #endif StringMatchResultListener distance_listener; const bool result = distance_matcher_.MatchAndExplain(distance, &distance_listener); *listener << "whose distance between begin() and end() " << distance << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(distance_listener.str(), listener->stream()); return result; } private: const Matcher<DistanceType> distance_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const DistanceMatcher distance_matcher_; GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher); }; // Implements an equality matcher for any STL-style container whose elements // support ==. This matcher is like Eq(), but its failure explanations provide // more detailed information that is useful when the container is used as a set. // The failure message reports elements that are in one of the operands but not // the other. The failure messages do not report duplicate or out-of-order // elements in the containers (which don't properly matter to sets, but can // occur if the containers are vectors or lists, for example). // // Uses the container's const_iterator, value_type, operator ==, // begin(), and end(). template <typename Container> class ContainerEqMatcher { public: typedef internal::StlContainerView<Container> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; // We make a copy of expected in case the elements in it are modified // after this matcher is created. explicit ContainerEqMatcher(const Container& expected) : expected_(View::Copy(expected)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. (void)testing::StaticAssertTypeEq<Container, GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>(); } void DescribeTo(::std::ostream* os) const { *os << "equals "; UniversalPrint(expected_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "does not equal "; UniversalPrint(expected_, os); } template <typename LhsContainer> bool MatchAndExplain(const LhsContainer& lhs, MatchResultListener* listener) const { // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug // that causes LhsContainer to be a const type sometimes. typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); if (lhs_stl_container == expected_) return true; ::std::ostream* const os = listener->stream(); if (os != NULL) { // Something is different. Check for extra values first. bool printed_header = false; for (typename LhsStlContainer::const_iterator it = lhs_stl_container.begin(); it != lhs_stl_container.end(); ++it) { if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == expected_.end()) { if (printed_header) { *os << ", "; } else { *os << "which has these unexpected elements: "; printed_header = true; } UniversalPrint(*it, os); } } // Now check for missing values. bool printed_header2 = false; for (typename StlContainer::const_iterator it = expected_.begin(); it != expected_.end(); ++it) { if (internal::ArrayAwareFind( lhs_stl_container.begin(), lhs_stl_container.end(), *it) == lhs_stl_container.end()) { if (printed_header2) { *os << ", "; } else { *os << (printed_header ? ",\nand" : "which") << " doesn't have these expected elements: "; printed_header2 = true; } UniversalPrint(*it, os); } } } return false; } private: const StlContainer expected_; GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher); }; // A comparator functor that uses the < operator to compare two values. struct LessComparator { template <typename T, typename U> bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; } }; // Implements WhenSortedBy(comparator, container_matcher). template <typename Comparator, typename ContainerMatcher> class WhenSortedByMatcher { public: WhenSortedByMatcher(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} template <typename LhsContainer> operator Matcher<LhsContainer>() const { return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_)); } template <typename LhsContainer> class Impl : public MatcherInterface<LhsContainer> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; // Transforms std::pair<const Key, Value> into std::pair<Key, Value> // so that we can match associative containers. typedef typename RemoveConstFromKey< typename LhsStlContainer::value_type>::type LhsValue; Impl(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "(when sorted) "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "(when sorted) "; matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(), lhs_stl_container.end()); ::std::sort( sorted_container.begin(), sorted_container.end(), comparator_); if (!listener->IsInterested()) { // If the listener is not interested, we do not need to // construct the inner explanation. return matcher_.Matches(sorted_container); } *listener << "which is "; UniversalPrint(sorted_container, listener->stream()); *listener << " when sorted"; StringMatchResultListener inner_listener; const bool match = matcher_.MatchAndExplain(sorted_container, &inner_listener); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } private: const Comparator comparator_; const Matcher<const ::std::vector<LhsValue>&> matcher_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); }; private: const Comparator comparator_; const ContainerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher); }; // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher // must be able to be safely cast to Matcher<tuple<const T1&, const // T2&> >, where T1 and T2 are the types of elements in the LHS // container and the RHS container respectively. template <typename TupleMatcher, typename RhsContainer> class PointwiseMatcher { public: typedef internal::StlContainerView<RhsContainer> RhsView; typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type RhsValue; // Like ContainerEq, we make a copy of rhs in case the elements in // it are modified after this matcher is created. PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs) : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. (void)testing::StaticAssertTypeEq<RhsContainer, GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>(); } template <typename LhsContainer> operator Matcher<LhsContainer>() const { return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_)); } template <typename LhsContainer> class Impl : public MatcherInterface<LhsContainer> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; typedef typename LhsStlContainer::value_type LhsValue; // We pass the LHS value and the RHS value to the inner matcher by // reference, as they may be expensive to copy. We must use tuple // instead of pair here, as a pair cannot hold references (C++ 98, // 20.2.2 [lib.pairs]). typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)), rhs_(rhs) {} virtual void DescribeTo(::std::ostream* os) const { *os << "contains " << rhs_.size() << " values, where each value and its corresponding value in "; UniversalPrinter<RhsStlContainer>::Print(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't contain exactly " << rhs_.size() << " values, or contains a value x at some index i" << " where x and the i-th value of "; UniversalPrint(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); const size_t actual_size = lhs_stl_container.size(); if (actual_size != rhs_.size()) { *listener << "which contains " << actual_size << " values"; return false; } typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); typename RhsStlContainer::const_iterator right = rhs_.begin(); for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { const InnerMatcherArg value_pair(*left, *right); if (listener->IsInterested()) { StringMatchResultListener inner_listener; if (!mono_tuple_matcher_.MatchAndExplain( value_pair, &inner_listener)) { *listener << "where the value pair ("; UniversalPrint(*left, listener->stream()); *listener << ", "; UniversalPrint(*right, listener->stream()); *listener << ") at index #" << i << " don't match"; PrintIfNotEmpty(inner_listener.str(), listener->stream()); return false; } } else { if (!mono_tuple_matcher_.Matches(value_pair)) return false; } } return true; } private: const Matcher<InnerMatcherArg> mono_tuple_matcher_; const RhsStlContainer rhs_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const TupleMatcher tuple_matcher_; const RhsStlContainer rhs_; GTEST_DISALLOW_ASSIGN_(PointwiseMatcher); }; // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl. template <typename Container> class QuantifierMatcherImpl : public MatcherInterface<Container> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef typename StlContainer::value_type Element; template <typename InnerMatcher> explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) : inner_matcher_( testing::SafeMatcherCast<const Element&>(inner_matcher)) {} // Checks whether: // * All elements in the container match, if all_elements_should_match. // * Any element in the container matches, if !all_elements_should_match. bool MatchAndExplainImpl(bool all_elements_should_match, Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); size_t i = 0; for (typename StlContainer::const_iterator it = stl_container.begin(); it != stl_container.end(); ++it, ++i) { StringMatchResultListener inner_listener; const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); if (matches != all_elements_should_match) { *listener << "whose element #" << i << (matches ? " matches" : " doesn't match"); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return !all_elements_should_match; } } return all_elements_should_match; } protected: const Matcher<const Element&> inner_matcher_; GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl); }; // Implements Contains(element_matcher) for the given argument type Container. // Symmetric to EachMatcherImpl. template <typename Container> class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> { public: template <typename InnerMatcher> explicit ContainsMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl<Container>(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "contains at least one element that "; this->inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't contain any element that "; this->inner_matcher_.DescribeTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(false, container, listener); } private: GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl); }; // Implements Each(element_matcher) for the given argument type Container. // Symmetric to ContainsMatcherImpl. template <typename Container> class EachMatcherImpl : public QuantifierMatcherImpl<Container> { public: template <typename InnerMatcher> explicit EachMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl<Container>(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "only contains elements that "; this->inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "contains some element that "; this->inner_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(true, container, listener); } private: GTEST_DISALLOW_ASSIGN_(EachMatcherImpl); }; // Implements polymorphic Contains(element_matcher). template <typename M> class ContainsMatcher { public: explicit ContainsMatcher(M m) : inner_matcher_(m) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_)); } private: const M inner_matcher_; GTEST_DISALLOW_ASSIGN_(ContainsMatcher); }; // Implements polymorphic Each(element_matcher). template <typename M> class EachMatcher { public: explicit EachMatcher(M m) : inner_matcher_(m) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_)); } private: const M inner_matcher_; GTEST_DISALLOW_ASSIGN_(EachMatcher); }; // Implements Key(inner_matcher) for the given argument pair type. // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an // std::map that contains at least one element whose key is >= 5. template <typename PairType> class KeyMatcherImpl : public MatcherInterface<PairType> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type KeyType; template <typename InnerMatcher> explicit KeyMatcherImpl(InnerMatcher inner_matcher) : inner_matcher_( testing::SafeMatcherCast<const KeyType&>(inner_matcher)) { } // Returns true iff 'key_value.first' (the key) matches the inner matcher. virtual bool MatchAndExplain(PairType key_value, MatchResultListener* listener) const { StringMatchResultListener inner_listener; const bool match = inner_matcher_.MatchAndExplain(key_value.first, &inner_listener); const std::string explanation = inner_listener.str(); if (explanation != "") { *listener << "whose first field is a value " << explanation; } return match; } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "has a key that "; inner_matcher_.DescribeTo(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't have a key that "; inner_matcher_.DescribeTo(os); } private: const Matcher<const KeyType&> inner_matcher_; GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl); }; // Implements polymorphic Key(matcher_for_key). template <typename M> class KeyMatcher { public: explicit KeyMatcher(M m) : matcher_for_key_(m) {} template <typename PairType> operator Matcher<PairType>() const { return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_)); } private: const M matcher_for_key_; GTEST_DISALLOW_ASSIGN_(KeyMatcher); }; // Implements Pair(first_matcher, second_matcher) for the given argument pair // type with its two matchers. See Pair() function below. template <typename PairType> class PairMatcherImpl : public MatcherInterface<PairType> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type FirstType; typedef typename RawPairType::second_type SecondType; template <typename FirstMatcher, typename SecondMatcher> PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher) : first_matcher_( testing::SafeMatcherCast<const FirstType&>(first_matcher)), second_matcher_( testing::SafeMatcherCast<const SecondType&>(second_matcher)) { } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "has a first field that "; first_matcher_.DescribeTo(os); *os << ", and has a second field that "; second_matcher_.DescribeTo(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "has a first field that "; first_matcher_.DescribeNegationTo(os); *os << ", or has a second field that "; second_matcher_.DescribeNegationTo(os); } // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second' // matches second_matcher. virtual bool MatchAndExplain(PairType a_pair, MatchResultListener* listener) const { if (!listener->IsInterested()) { // If the listener is not interested, we don't need to construct the // explanation. return first_matcher_.Matches(a_pair.first) && second_matcher_.Matches(a_pair.second); } StringMatchResultListener first_inner_listener; if (!first_matcher_.MatchAndExplain(a_pair.first, &first_inner_listener)) { *listener << "whose first field does not match"; PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); return false; } StringMatchResultListener second_inner_listener; if (!second_matcher_.MatchAndExplain(a_pair.second, &second_inner_listener)) { *listener << "whose second field does not match"; PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); return false; } ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(), listener); return true; } private: void ExplainSuccess(const std::string& first_explanation, const std::string& second_explanation, MatchResultListener* listener) const { *listener << "whose both fields match"; if (first_explanation != "") { *listener << ", where the first field is a value " << first_explanation; } if (second_explanation != "") { *listener << ", "; if (first_explanation != "") { *listener << "and "; } else { *listener << "where "; } *listener << "the second field is a value " << second_explanation; } } const Matcher<const FirstType&> first_matcher_; const Matcher<const SecondType&> second_matcher_; GTEST_DISALLOW_ASSIGN_(PairMatcherImpl); }; // Implements polymorphic Pair(first_matcher, second_matcher). template <typename FirstMatcher, typename SecondMatcher> class PairMatcher { public: PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher) : first_matcher_(first_matcher), second_matcher_(second_matcher) {} template <typename PairType> operator Matcher<PairType> () const { return MakeMatcher( new PairMatcherImpl<PairType>( first_matcher_, second_matcher_)); } private: const FirstMatcher first_matcher_; const SecondMatcher second_matcher_; GTEST_DISALLOW_ASSIGN_(PairMatcher); }; // Implements ElementsAre() and ElementsAreArray(). template <typename Container> class ElementsAreMatcherImpl : public MatcherInterface<Container> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef typename StlContainer::value_type Element; // Constructs the matcher from a sequence of element values or // element matchers. template <typename InputIter> ElementsAreMatcherImpl(InputIter first, InputIter last) { while (first != last) { matchers_.push_back(MatcherCast<const Element&>(*first++)); } } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { if (count() == 0) { *os << "is empty"; } else if (count() == 1) { *os << "has 1 element that "; matchers_[0].DescribeTo(os); } else { *os << "has " << Elements(count()) << " where\n"; for (size_t i = 0; i != count(); ++i) { *os << "element #" << i << " "; matchers_[i].DescribeTo(os); if (i + 1 < count()) { *os << ",\n"; } } } } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { if (count() == 0) { *os << "isn't empty"; return; } *os << "doesn't have " << Elements(count()) << ", or\n"; for (size_t i = 0; i != count(); ++i) { *os << "element #" << i << " "; matchers_[i].DescribeNegationTo(os); if (i + 1 < count()) { *os << ", or\n"; } } } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { // To work with stream-like "containers", we must only walk // through the elements in one pass. const bool listener_interested = listener->IsInterested(); // explanations[i] is the explanation of the element at index i. ::std::vector<std::string> explanations(count()); StlContainerReference stl_container = View::ConstReference(container); typename StlContainer::const_iterator it = stl_container.begin(); size_t exam_pos = 0; bool mismatch_found = false; // Have we found a mismatched element yet? // Go through the elements and matchers in pairs, until we reach // the end of either the elements or the matchers, or until we find a // mismatch. for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) { bool match; // Does the current element match the current matcher? if (listener_interested) { StringMatchResultListener s; match = matchers_[exam_pos].MatchAndExplain(*it, &s); explanations[exam_pos] = s.str(); } else { match = matchers_[exam_pos].Matches(*it); } if (!match) { mismatch_found = true; break; } } // If mismatch_found is true, 'exam_pos' is the index of the mismatch. // Find how many elements the actual container has. We avoid // calling size() s.t. this code works for stream-like "containers" // that don't define size(). size_t actual_count = exam_pos; for (; it != stl_container.end(); ++it) { ++actual_count; } if (actual_count != count()) { // The element count doesn't match. If the container is empty, // there's no need to explain anything as Google Mock already // prints the empty container. Otherwise we just need to show // how many elements there actually are. if (listener_interested && (actual_count != 0)) { *listener << "which has " << Elements(actual_count); } return false; } if (mismatch_found) { // The element count matches, but the exam_pos-th element doesn't match. if (listener_interested) { *listener << "whose element #" << exam_pos << " doesn't match"; PrintIfNotEmpty(explanations[exam_pos], listener->stream()); } return false; } // Every element matches its expectation. We need to explain why // (the obvious ones can be skipped). if (listener_interested) { bool reason_printed = false; for (size_t i = 0; i != count(); ++i) { const std::string& s = explanations[i]; if (!s.empty()) { if (reason_printed) { *listener << ",\nand "; } *listener << "whose element #" << i << " matches, " << s; reason_printed = true; } } } return true; } private: static Message Elements(size_t count) { return Message() << count << (count == 1 ? " element" : " elements"); } size_t count() const { return matchers_.size(); } ::std::vector<Matcher<const Element&> > matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl); }; // Connectivity matrix of (elements X matchers), in element-major order. // Initially, there are no edges. // Use NextGraph() to iterate over all possible edge configurations. // Use Randomize() to generate a random edge configuration. class GTEST_API_ MatchMatrix { public: MatchMatrix(size_t num_elements, size_t num_matchers) : num_elements_(num_elements), num_matchers_(num_matchers), matched_(num_elements_* num_matchers_, 0) { } size_t LhsSize() const { return num_elements_; } size_t RhsSize() const { return num_matchers_; } bool HasEdge(size_t ilhs, size_t irhs) const { return matched_[SpaceIndex(ilhs, irhs)] == 1; } void SetEdge(size_t ilhs, size_t irhs, bool b) { matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; } // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number, // adds 1 to that number; returns false if incrementing the graph left it // empty. bool NextGraph(); void Randomize(); std::string DebugString() const; private: size_t SpaceIndex(size_t ilhs, size_t irhs) const { return ilhs * num_matchers_ + irhs; } size_t num_elements_; size_t num_matchers_; // Each element is a char interpreted as bool. They are stored as a // flattened array in lhs-major order, use 'SpaceIndex()' to translate // a (ilhs, irhs) matrix coordinate into an offset. ::std::vector<char> matched_; }; typedef ::std::pair<size_t, size_t> ElementMatcherPair; typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs; // Returns a maximum bipartite matching for the specified graph 'g'. // The matching is represented as a vector of {element, matcher} pairs. GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g); GTEST_API_ bool FindPairing(const MatchMatrix& matrix, MatchResultListener* listener); // Untyped base class for implementing UnorderedElementsAre. By // putting logic that's not specific to the element type here, we // reduce binary bloat and increase compilation speed. class GTEST_API_ UnorderedElementsAreMatcherImplBase { protected: // A vector of matcher describers, one for each element matcher. // Does not own the describers (and thus can be used only when the // element matchers are alive). typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec; // Describes this UnorderedElementsAre matcher. void DescribeToImpl(::std::ostream* os) const; // Describes the negation of this UnorderedElementsAre matcher. void DescribeNegationToImpl(::std::ostream* os) const; bool VerifyAllElementsAndMatchersAreMatched( const ::std::vector<std::string>& element_printouts, const MatchMatrix& matrix, MatchResultListener* listener) const; MatcherDescriberVec& matcher_describers() { return matcher_describers_; } static Message Elements(size_t n) { return Message() << n << " element" << (n == 1 ? "" : "s"); } private: MatcherDescriberVec matcher_describers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase); }; // Implements unordered ElementsAre and unordered ElementsAreArray. template <typename Container> class UnorderedElementsAreMatcherImpl : public MatcherInterface<Container>, public UnorderedElementsAreMatcherImplBase { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef typename StlContainer::const_iterator StlContainerConstIterator; typedef typename StlContainer::value_type Element; // Constructs the matcher from a sequence of element values or // element matchers. template <typename InputIter> UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) { for (; first != last; ++first) { matchers_.push_back(MatcherCast<const Element&>(*first)); matcher_describers().push_back(matchers_.back().GetDescriber()); } } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); ::std::vector<std::string> element_printouts; MatchMatrix matrix = AnalyzeElements(stl_container.begin(), stl_container.end(), &element_printouts, listener); const size_t actual_count = matrix.LhsSize(); if (actual_count == 0 && matchers_.empty()) { return true; } if (actual_count != matchers_.size()) { // The element count doesn't match. If the container is empty, // there's no need to explain anything as Google Mock already // prints the empty container. Otherwise we just need to show // how many elements there actually are. if (actual_count != 0 && listener->IsInterested()) { *listener << "which has " << Elements(actual_count); } return false; } return VerifyAllElementsAndMatchersAreMatched(element_printouts, matrix, listener) && FindPairing(matrix, listener); } private: typedef ::std::vector<Matcher<const Element&> > MatcherVec; template <typename ElementIter> MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, ::std::vector<std::string>* element_printouts, MatchResultListener* listener) const { element_printouts->clear(); ::std::vector<char> did_match; size_t num_elements = 0; for (; elem_first != elem_last; ++num_elements, ++elem_first) { if (listener->IsInterested()) { element_printouts->push_back(PrintToString(*elem_first)); } for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { did_match.push_back(Matches(matchers_[irhs])(*elem_first)); } } MatchMatrix matrix(num_elements, matchers_.size()); ::std::vector<char>::const_iterator did_match_iter = did_match.begin(); for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) { for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0); } } return matrix; } MatcherVec matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl); }; // Functor for use in TransformTuple. // Performs MatcherCast<Target> on an input argument of any type. template <typename Target> struct CastAndAppendTransform { template <typename Arg> Matcher<Target> operator()(const Arg& a) const { return MatcherCast<Target>(a); } }; // Implements UnorderedElementsAre. template <typename MatcherTuple> class UnorderedElementsAreMatcher { public: explicit UnorderedElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type View; typedef typename View::value_type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>( matchers.begin(), matchers.end())); } private: const MatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher); }; // Implements ElementsAre. template <typename MatcherTuple> class ElementsAreMatcher { public: explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type View; typedef typename View::value_type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new ElementsAreMatcherImpl<Container>( matchers.begin(), matchers.end())); } private: const MatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher); }; // Implements UnorderedElementsAreArray(). template <typename T> class UnorderedElementsAreArrayMatcher { public: UnorderedElementsAreArrayMatcher() {} template <typename Iter> UnorderedElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher( new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(), matchers_.end())); } private: ::std::vector<T> matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher); }; // Implements ElementsAreArray(). template <typename T> class ElementsAreArrayMatcher { public: template <typename Iter> ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new ElementsAreMatcherImpl<Container>( matchers_.begin(), matchers_.end())); } private: const ::std::vector<T> matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher); }; // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm, // second) is a polymorphic matcher that matches a value x iff tm // matches tuple (x, second). Useful for implementing // UnorderedPointwise() in terms of UnorderedElementsAreArray(). // // BoundSecondMatcher is copyable and assignable, as we need to put // instances of this class in a vector when implementing // UnorderedPointwise(). template <typename Tuple2Matcher, typename Second> class BoundSecondMatcher { public: BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) : tuple2_matcher_(tm), second_value_(second) {} template <typename T> operator Matcher<T>() const { return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_)); } // We have to define this for UnorderedPointwise() to compile in // C++98 mode, as it puts BoundSecondMatcher instances in a vector, // which requires the elements to be assignable in C++98. The // compiler cannot generate the operator= for us, as Tuple2Matcher // and Second may not be assignable. // // However, this should never be called, so the implementation just // need to assert. void operator=(const BoundSecondMatcher& /*rhs*/) { GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned."; } private: template <typename T> class Impl : public MatcherInterface<T> { public: typedef ::testing::tuple<T, Second> ArgTuple; Impl(const Tuple2Matcher& tm, const Second& second) : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)), second_value_(second) {} virtual void DescribeTo(::std::ostream* os) const { *os << "and "; UniversalPrint(second_value_, os); *os << " "; mono_tuple2_matcher_.DescribeTo(os); } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_), listener); } private: const Matcher<const ArgTuple&> mono_tuple2_matcher_; const Second second_value_; GTEST_DISALLOW_ASSIGN_(Impl); }; const Tuple2Matcher tuple2_matcher_; const Second second_value_; }; // Given a 2-tuple matcher tm and a value second, // MatcherBindSecond(tm, second) returns a matcher that matches a // value x iff tm matches tuple (x, second). Useful for implementing // UnorderedPointwise() in terms of UnorderedElementsAreArray(). template <typename Tuple2Matcher, typename Second> BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond( const Tuple2Matcher& tm, const Second& second) { return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second); } // Returns the description for a matcher defined using the MATCHER*() // macro where the user-supplied description string is "", if // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. GTEST_API_ std::string FormatMatcherDescription(bool negation, const char* matcher_name, const Strings& param_values); } // namespace internal // ElementsAreArray(first, last) // ElementsAreArray(pointer, count) // ElementsAreArray(array) // ElementsAreArray(container) // ElementsAreArray({ e1, e2, ..., en }) // // The ElementsAreArray() functions are like ElementsAre(...), except // that they are given a homogeneous sequence rather than taking each // element as a function argument. The sequence can be specified as an // array, a pointer and count, a vector, an initializer list, or an // STL iterator range. In each of these cases, the underlying sequence // can be either a sequence of values or a sequence of matchers. // // All forms of ElementsAreArray() make a copy of the input matcher sequence. template <typename Iter> inline internal::ElementsAreArrayMatcher< typename ::std::iterator_traits<Iter>::value_type> ElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits<Iter>::value_type T; return internal::ElementsAreArrayMatcher<T>(first, last); } template <typename T> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const T* pointer, size_t count) { return ElementsAreArray(pointer, pointer + count); } template <typename T, size_t N> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const T (&array)[N]) { return ElementsAreArray(array, N); } template <typename Container> inline internal::ElementsAreArrayMatcher<typename Container::value_type> ElementsAreArray(const Container& container) { return ElementsAreArray(container.begin(), container.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template <typename T> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(::std::initializer_list<T> xs) { return ElementsAreArray(xs.begin(), xs.end()); } #endif // UnorderedElementsAreArray(first, last) // UnorderedElementsAreArray(pointer, count) // UnorderedElementsAreArray(array) // UnorderedElementsAreArray(container) // UnorderedElementsAreArray({ e1, e2, ..., en }) // // The UnorderedElementsAreArray() functions are like // ElementsAreArray(...), but allow matching the elements in any order. template <typename Iter> inline internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits<Iter>::value_type> UnorderedElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits<Iter>::value_type T; return internal::UnorderedElementsAreArrayMatcher<T>(first, last); } template <typename T> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(const T* pointer, size_t count) { return UnorderedElementsAreArray(pointer, pointer + count); } template <typename T, size_t N> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(const T (&array)[N]) { return UnorderedElementsAreArray(array, N); } template <typename Container> inline internal::UnorderedElementsAreArrayMatcher< typename Container::value_type> UnorderedElementsAreArray(const Container& container) { return UnorderedElementsAreArray(container.begin(), container.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template <typename T> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(::std::initializer_list<T> xs) { return UnorderedElementsAreArray(xs.begin(), xs.end()); } #endif // _ is a matcher that matches anything of any type. // // This definition is fine as: // // 1. The C++ standard permits using the name _ in a namespace that // is not the global namespace or ::std. // 2. The AnythingMatcher class has no data member or constructor, // so it's OK to create global variables of this type. // 3. c-style has approved of using _ in this case. const internal::AnythingMatcher _ = {}; // Creates a matcher that matches any value of the given type T. template <typename T> inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); } // Creates a matcher that matches any value of the given type T. template <typename T> inline Matcher<T> An() { return A<T>(); } // Creates a polymorphic matcher that matches anything equal to x. // Note: if the parameter of Eq() were declared as const T&, Eq("foo") // wouldn't compile. template <typename T> inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); } // Constructs a Matcher<T> from a 'value' of type T. The constructed // matcher matches any value that's equal to 'value'. template <typename T> Matcher<T>::Matcher(T value) { *this = Eq(value); } // Creates a monomorphic matcher that matches anything with type Lhs // and equal to rhs. A user may need to use this instead of Eq(...) // in order to resolve an overloading ambiguity. // // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x)) // or Matcher<T>(x), but more readable than the latter. // // We could define similar monomorphic matchers for other comparison // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do // it yet as those are used much less than Eq() in practice. A user // can always write Matcher<T>(Lt(5)) to be explicit about the type, // for example. template <typename Lhs, typename Rhs> inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); } // Creates a polymorphic matcher that matches anything >= x. template <typename Rhs> inline internal::GeMatcher<Rhs> Ge(Rhs x) { return internal::GeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything > x. template <typename Rhs> inline internal::GtMatcher<Rhs> Gt(Rhs x) { return internal::GtMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything <= x. template <typename Rhs> inline internal::LeMatcher<Rhs> Le(Rhs x) { return internal::LeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything < x. template <typename Rhs> inline internal::LtMatcher<Rhs> Lt(Rhs x) { return internal::LtMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything != x. template <typename Rhs> inline internal::NeMatcher<Rhs> Ne(Rhs x) { return internal::NeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches any NULL pointer. inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() { return MakePolymorphicMatcher(internal::IsNullMatcher()); } // Creates a polymorphic matcher that matches any non-NULL pointer. // This is convenient as Not(NULL) doesn't compile (the compiler // thinks that that expression is comparing a pointer with an integer). inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() { return MakePolymorphicMatcher(internal::NotNullMatcher()); } // Creates a polymorphic matcher that matches any argument that // references variable x. template <typename T> inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT return internal::RefMatcher<T&>(x); } // Creates a matcher that matches any double argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) { return internal::FloatingEqMatcher<double>(rhs, false); } // Creates a matcher that matches any double argument approximately // equal to rhs, including NaN values when rhs is NaN. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) { return internal::FloatingEqMatcher<double>(rhs, true); } // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<double> DoubleNear( double rhs, double max_abs_error) { return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error); } // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear( double rhs, double max_abs_error) { return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error); } // Creates a matcher that matches any float argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher<float> FloatEq(float rhs) { return internal::FloatingEqMatcher<float>(rhs, false); } // Creates a matcher that matches any float argument approximately // equal to rhs, including NaN values when rhs is NaN. inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) { return internal::FloatingEqMatcher<float>(rhs, true); } // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<float> FloatNear( float rhs, float max_abs_error) { return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error); } // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear( float rhs, float max_abs_error) { return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error); } // Creates a matcher that matches a pointer (raw or smart) that points // to a value that matches inner_matcher. template <typename InnerMatcher> inline internal::PointeeMatcher<InnerMatcher> Pointee( const InnerMatcher& inner_matcher) { return internal::PointeeMatcher<InnerMatcher>(inner_matcher); } // Creates a matcher that matches a pointer or reference that matches // inner_matcher when dynamic_cast<To> is applied. // The result of dynamic_cast<To> is forwarded to the inner matcher. // If To is a pointer and the cast fails, the inner matcher will receive NULL. // If To is a reference and the cast fails, this matcher returns false // immediately. template <typename To> inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> > WhenDynamicCastTo(const Matcher<To>& inner_matcher) { return MakePolymorphicMatcher( internal::WhenDynamicCastToMatcher<To>(inner_matcher)); } // Creates a matcher that matches an object whose given field matches // 'matcher'. For example, // Field(&Foo::number, Ge(5)) // matches a Foo object x iff x.number >= 5. template <typename Class, typename FieldType, typename FieldMatcher> inline PolymorphicMatcher< internal::FieldMatcher<Class, FieldType> > Field( FieldType Class::*field, const FieldMatcher& matcher) { return MakePolymorphicMatcher( internal::FieldMatcher<Class, FieldType>( field, MatcherCast<const FieldType&>(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Field(&Foo::bar, m) // to compile where bar is an int32 and m is a matcher for int64. } // Creates a matcher that matches an object whose given property // matches 'matcher'. For example, // Property(&Foo::str, StartsWith("hi")) // matches a Foo object x iff x.str() starts with "hi". template <typename Class, typename PropertyType, typename PropertyMatcher> inline PolymorphicMatcher< internal::PropertyMatcher<Class, PropertyType> > Property( PropertyType (Class::*property)() const, const PropertyMatcher& matcher) { return MakePolymorphicMatcher( internal::PropertyMatcher<Class, PropertyType>( property, MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Property(&Foo::bar, m) // to compile where bar() returns an int32 and m is a matcher for int64. } // Creates a matcher that matches an object iff the result of applying // a callable to x matches 'matcher'. // For example, // ResultOf(f, StartsWith("hi")) // matches a Foo object x iff f(x) starts with "hi". // callable parameter can be a function, function pointer, or a functor. // Callable has to satisfy the following conditions: // * It is required to keep no state affecting the results of // the calls on it and make no assumptions about how many calls // will be made. Any state it keeps must be protected from the // concurrent access. // * If it is a function object, it has to define type result_type. // We recommend deriving your functor classes from std::unary_function. template <typename Callable, typename ResultOfMatcher> internal::ResultOfMatcher<Callable> ResultOf( Callable callable, const ResultOfMatcher& matcher) { return internal::ResultOfMatcher<Callable>( callable, MatcherCast<typename internal::CallableTraits<Callable>::ResultType>( matcher)); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // ResultOf(Function, m) // to compile where Function() returns an int32 and m is a matcher for int64. } // String matchers. // Matches a string equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrEq( const std::string& str) { return MakePolymorphicMatcher( internal::StrEqualityMatcher<std::string>(str, true, true)); } // Matches a string not equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrNe( const std::string& str) { return MakePolymorphicMatcher( internal::StrEqualityMatcher<std::string>(str, false, true)); } // Matches a string equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseEq( const std::string& str) { return MakePolymorphicMatcher( internal::StrEqualityMatcher<std::string>(str, true, false)); } // Matches a string not equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<std::string> > StrCaseNe( const std::string& str) { return MakePolymorphicMatcher( internal::StrEqualityMatcher<std::string>(str, false, false)); } // Creates a matcher that matches any string, std::string, or C string // that contains the given substring. inline PolymorphicMatcher<internal::HasSubstrMatcher<std::string> > HasSubstr( const std::string& substring) { return MakePolymorphicMatcher( internal::HasSubstrMatcher<std::string>(substring)); } // Matches a string that starts with 'prefix' (case-sensitive). inline PolymorphicMatcher<internal::StartsWithMatcher<std::string> > StartsWith( const std::string& prefix) { return MakePolymorphicMatcher( internal::StartsWithMatcher<std::string>(prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). inline PolymorphicMatcher<internal::EndsWithMatcher<std::string> > EndsWith( const std::string& suffix) { return MakePolymorphicMatcher(internal::EndsWithMatcher<std::string>(suffix)); } // Matches a string that fully matches regular expression 'regex'. // The matcher takes ownership of 'regex'. inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( const std::string& regex) { return MatchesRegex(new internal::RE(regex)); } // Matches a string that contains regular expression 'regex'. // The matcher takes ownership of 'regex'. inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( const std::string& regex) { return ContainsRegex(new internal::RE(regex)); } #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING // Wide string matchers. // Matches a string equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrEq(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, true, true)); } // Matches a string not equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrNe(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, false, true)); } // Matches a string equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrCaseEq(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, true, false)); } // Matches a string not equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrCaseNe(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, false, false)); } // Creates a matcher that matches any wstring, std::wstring, or C wide string // that contains the given substring. inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> > HasSubstr(const internal::wstring& substring) { return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>( substring)); } // Matches a string that starts with 'prefix' (case-sensitive). inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> > StartsWith(const internal::wstring& prefix) { return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>( prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> > EndsWith(const internal::wstring& suffix) { return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>( suffix)); } #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING // Creates a polymorphic matcher that matches a 2-tuple where the // first field == the second field. inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field >= the second field. inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field > the second field. inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field <= the second field. inline internal::Le2Matcher Le() { return internal::Le2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field < the second field. inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field != the second field. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } // Creates a matcher that matches any value of type T that m doesn't // match. template <typename InnerMatcher> inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) { return internal::NotMatcher<InnerMatcher>(m); } // Returns a matcher that matches anything that satisfies the given // predicate. The predicate can be any unary function or functor // whose return type can be implicitly converted to bool. template <typename Predicate> inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> > Truly(Predicate pred) { return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred)); } // Returns a matcher that matches the container size. The container must // support both size() and size_type which all STL-like containers provide. // Note that the parameter 'size' can be a value of type size_type as well as // matcher. For instance: // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements. // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2. template <typename SizeMatcher> inline internal::SizeIsMatcher<SizeMatcher> SizeIs(const SizeMatcher& size_matcher) { return internal::SizeIsMatcher<SizeMatcher>(size_matcher); } // Returns a matcher that matches the distance between the container's begin() // iterator and its end() iterator, i.e. the size of the container. This matcher // can be used instead of SizeIs with containers such as std::forward_list which // do not implement size(). The container must provide const_iterator (with // valid iterator_traits), begin() and end(). template <typename DistanceMatcher> inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(const DistanceMatcher& distance_matcher) { return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher); } // Returns a matcher that matches an equal container. // This matcher behaves like Eq(), but in the event of mismatch lists the // values that are included in one container but not the other. (Duplicate // values and order differences are not explained.) template <typename Container> inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT GTEST_REMOVE_CONST_(Container)> > ContainerEq(const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes. typedef GTEST_REMOVE_CONST_(Container) RawContainer; return MakePolymorphicMatcher( internal::ContainerEqMatcher<RawContainer>(rhs)); } // Returns a matcher that matches a container that, when sorted using // the given comparator, matches container_matcher. template <typename Comparator, typename ContainerMatcher> inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(const Comparator& comparator, const ContainerMatcher& container_matcher) { return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>( comparator, container_matcher); } // Returns a matcher that matches a container that, when sorted using // the < operator, matches container_matcher. template <typename ContainerMatcher> inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher> WhenSorted(const ContainerMatcher& container_matcher) { return internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>( internal::LessComparator(), container_matcher); } // Matches an STL-style container or a native array that contains the // same number of elements as in rhs, where its i-th element and rhs's // i-th element (as a pair) satisfy the given pair matcher, for all i. // TupleMatcher must be able to be safely cast to Matcher<tuple<const // T1&, const T2&> >, where T1 and T2 are the types of elements in the // LHS container and the RHS container respectively. template <typename TupleMatcher, typename Container> inline internal::PointwiseMatcher<TupleMatcher, GTEST_REMOVE_CONST_(Container)> Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes (e.g. when // rhs is a const int[]).. typedef GTEST_REMOVE_CONST_(Container) RawContainer; return internal::PointwiseMatcher<TupleMatcher, RawContainer>( tuple_matcher, rhs); } #if GTEST_HAS_STD_INITIALIZER_LIST_ // Supports the Pointwise(m, {a, b, c}) syntax. template <typename TupleMatcher, typename T> inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise( const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) { return Pointwise(tuple_matcher, std::vector<T>(rhs)); } #endif // GTEST_HAS_STD_INITIALIZER_LIST_ // UnorderedPointwise(pair_matcher, rhs) matches an STL-style // container or a native array that contains the same number of // elements as in rhs, where in some permutation of the container, its // i-th element and rhs's i-th element (as a pair) satisfy the given // pair matcher, for all i. Tuple2Matcher must be able to be safely // cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are // the types of elements in the LHS container and the RHS container // respectively. // // This is like Pointwise(pair_matcher, rhs), except that the element // order doesn't matter. template <typename Tuple2Matcher, typename RhsContainer> inline internal::UnorderedElementsAreArrayMatcher< typename internal::BoundSecondMatcher< Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_( RhsContainer)>::type::value_type> > UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, const RhsContainer& rhs_container) { // This following line is for working around a bug in MSVC 8.0, // which causes RhsContainer to be a const type sometimes (e.g. when // rhs_container is a const int[]). typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer; // RhsView allows the same code to handle RhsContainer being a // STL-style container and it being a native C-style array. typedef typename internal::StlContainerView<RawRhsContainer> RhsView; typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type Second; const RhsStlContainer& rhs_stl_container = RhsView::ConstReference(rhs_container); // Create a matcher for each element in rhs_container. ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers; for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin(); it != rhs_stl_container.end(); ++it) { matchers.push_back( internal::MatcherBindSecond(tuple2_matcher, *it)); } // Delegate the work to UnorderedElementsAreArray(). return UnorderedElementsAreArray(matchers); } #if GTEST_HAS_STD_INITIALIZER_LIST_ // Supports the UnorderedPointwise(m, {a, b, c}) syntax. template <typename Tuple2Matcher, typename T> inline internal::UnorderedElementsAreArrayMatcher< typename internal::BoundSecondMatcher<Tuple2Matcher, T> > UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, std::initializer_list<T> rhs) { return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs)); } #endif // GTEST_HAS_STD_INITIALIZER_LIST_ // Matches an STL-style container or a native array that contains at // least one element matching the given value or matcher. // // Examples: // ::std::set<int> page_ids; // page_ids.insert(3); // page_ids.insert(1); // EXPECT_THAT(page_ids, Contains(1)); // EXPECT_THAT(page_ids, Contains(Gt(2))); // EXPECT_THAT(page_ids, Not(Contains(4))); // // ::std::map<int, size_t> page_lengths; // page_lengths[1] = 100; // EXPECT_THAT(page_lengths, // Contains(::std::pair<const int, size_t>(1, 100))); // // const char* user_ids[] = { "joe", "mike", "tom" }; // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom")))); template <typename M> inline internal::ContainsMatcher<M> Contains(M matcher) { return internal::ContainsMatcher<M>(matcher); } // Matches an STL-style container or a native array that contains only // elements matching the given value or matcher. // // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only // the messages are different. // // Examples: // ::std::set<int> page_ids; // // Each(m) matches an empty container, regardless of what m is. // EXPECT_THAT(page_ids, Each(Eq(1))); // EXPECT_THAT(page_ids, Each(Eq(77))); // // page_ids.insert(3); // EXPECT_THAT(page_ids, Each(Gt(0))); // EXPECT_THAT(page_ids, Not(Each(Gt(4)))); // page_ids.insert(1); // EXPECT_THAT(page_ids, Not(Each(Lt(2)))); // // ::std::map<int, size_t> page_lengths; // page_lengths[1] = 100; // page_lengths[2] = 200; // page_lengths[3] = 300; // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100)))); // EXPECT_THAT(page_lengths, Each(Key(Le(3)))); // // const char* user_ids[] = { "joe", "mike", "tom" }; // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom"))))); template <typename M> inline internal::EachMatcher<M> Each(M matcher) { return internal::EachMatcher<M>(matcher); } // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an // std::map that contains at least one element whose key is >= 5. template <typename M> inline internal::KeyMatcher<M> Key(M inner_matcher) { return internal::KeyMatcher<M>(inner_matcher); } // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field // matches first_matcher and whose 'second' field matches second_matcher. For // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used // to match a std::map<int, string> that contains exactly one element whose key // is >= 5 and whose value equals "foo". template <typename FirstMatcher, typename SecondMatcher> inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) { return internal::PairMatcher<FirstMatcher, SecondMatcher>( first_matcher, second_matcher); } // Returns a predicate that is satisfied by anything that matches the // given matcher. template <typename M> inline internal::MatcherAsPredicate<M> Matches(M matcher) { return internal::MatcherAsPredicate<M>(matcher); } // Returns true iff the value matches the matcher. template <typename T, typename M> inline bool Value(const T& value, M matcher) { return testing::Matches(matcher)(value); } // Matches the value against the given matcher and explains the match // result to listener. template <typename T, typename M> inline bool ExplainMatchResult( M matcher, const T& value, MatchResultListener* listener) { return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener); } #if GTEST_LANG_CXX11 // Define variadic matcher versions. They are overloaded in // gmock-generated-matchers.h for the cases supported by pre C++11 compilers. template <typename... Args> inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) { return internal::AllOfMatcher<Args...>(matchers...); } template <typename... Args> inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) { return internal::AnyOfMatcher<Args...>(matchers...); } #endif // GTEST_LANG_CXX11 // AllArgs(m) is a synonym of m. This is useful in // // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq())); // // which is easier to read than // // EXPECT_CALL(foo, Bar(_, _)).With(Eq()); template <typename InnerMatcher> inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } // These macros allow using matchers to check values in Google Test // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) // succeed iff the value matches the matcher. If the assertion fails, // the value and the description of the matcher will be printed. #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\ ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) } // namespace testing // Include any custom callback matchers added by the local installation. // We must include this header at the end to make sure it can use the // declarations from this file. #include "gmock/internal/custom/gmock-matchers.h" #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ diff --git a/googlemock/src/gmock-matchers.cc b/googlemock/src/gmock-matchers.cc index e0de25cb..6e40e5e8 100644 --- a/googlemock/src/gmock-matchers.cc +++ b/googlemock/src/gmock-matchers.cc @@ -1,497 +1,497 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements Matcher<const string&>, Matcher<string>, and // utilities for defining matchers. #include "gmock/gmock-matchers.h" #include "gmock/gmock-generated-matchers.h" #include <string.h> #include <sstream> #include <string> namespace testing { // Constructs a matcher that matches a const string& whose value is // equal to s. Matcher<const internal::string&>::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a const string& whose value is // equal to s. Matcher<const internal::string&>::Matcher(const char* s) { *this = Eq(internal::string(s)); } // Constructs a matcher that matches a string whose value is equal to s. Matcher<internal::string>::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a string whose value is equal to s. Matcher<internal::string>::Matcher(const char* s) { *this = Eq(internal::string(s)); } #if GTEST_HAS_STRING_PIECE_ // Constructs a matcher that matches a const StringPiece& whose value is // equal to s. Matcher<const StringPiece&>::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a const StringPiece& whose value is // equal to s. Matcher<const StringPiece&>::Matcher(const char* s) { *this = Eq(internal::string(s)); } // Constructs a matcher that matches a const StringPiece& whose value is // equal to s. Matcher<const StringPiece&>::Matcher(StringPiece s) { *this = Eq(s.ToString()); } // Constructs a matcher that matches a StringPiece whose value is equal to s. Matcher<StringPiece>::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a StringPiece whose value is equal to s. Matcher<StringPiece>::Matcher(const char* s) { *this = Eq(internal::string(s)); } // Constructs a matcher that matches a StringPiece whose value is equal to s. Matcher<StringPiece>::Matcher(StringPiece s) { *this = Eq(s.ToString()); } #endif // GTEST_HAS_STRING_PIECE_ namespace internal { // Joins a vector of strings as if they are fields of a tuple; returns // the joined string. GTEST_API_ string JoinAsTuple(const Strings& fields) { switch (fields.size()) { case 0: return ""; case 1: return fields[0]; default: string result = "(" + fields[0]; for (size_t i = 1; i < fields.size(); i++) { result += ", "; result += fields[i]; } result += ")"; return result; } } // Returns the description for a matcher defined using the MATCHER*() // macro where the user-supplied description string is "", if // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. GTEST_API_ string FormatMatcherDescription(bool negation, const char* matcher_name, const Strings& param_values) { string result = ConvertIdentifierNameToWords(matcher_name); if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values); return negation ? "not (" + result + ")" : result; } // FindMaxBipartiteMatching and its helper class. // // Uses the well-known Ford-Fulkerson max flow method to find a maximum // bipartite matching. Flow is considered to be from left to right. // There is an implicit source node that is connected to all of the left // nodes, and an implicit sink node that is connected to all of the // right nodes. All edges have unit capacity. // // Neither the flow graph nor the residual flow graph are represented // explicitly. Instead, they are implied by the information in 'graph' and // a vector<int> called 'left_' whose elements are initialized to the // value kUnused. This represents the initial state of the algorithm, // where the flow graph is empty, and the residual flow graph has the // following edges: // - An edge from source to each left_ node // - An edge from each right_ node to sink // - An edge from each left_ node to each right_ node, if the // corresponding edge exists in 'graph'. // // When the TryAugment() method adds a flow, it sets left_[l] = r for some // nodes l and r. This induces the following changes: // - The edges (source, l), (l, r), and (r, sink) are added to the // flow graph. // - The same three edges are removed from the residual flow graph. // - The reverse edges (l, source), (r, l), and (sink, r) are added // to the residual flow graph, which is a directional graph // representing unused flow capacity. // // When the method augments a flow (moving left_[l] from some r1 to some // other r2), this can be thought of as "undoing" the above steps with // respect to r1 and "redoing" them with respect to r2. // // It bears repeating that the flow graph and residual flow graph are // never represented explicitly, but can be derived by looking at the // information in 'graph' and in left_. // // As an optimization, there is a second vector<int> called right_ which // does not provide any new information. Instead, it enables more // efficient queries about edges entering or leaving the right-side nodes // of the flow or residual flow graphs. The following invariants are // maintained: // // left[l] == kUnused or right[left[l]] == l // right[r] == kUnused or left[right[r]] == r // // . [ source ] . // . ||| . // . ||| . // . ||\--> left[0]=1 ---\ right[0]=-1 ----\ . // . || | | . // . |\---> left[1]=-1 \--> right[1]=0 ---\| . // . | || . // . \----> left[2]=2 ------> right[2]=2 --\|| . // . ||| . // . elements matchers vvv . // . [ sink ] . // // See Also: // [1] Cormen, et al (2001). "Section 26.2: The Ford-Fulkerson method". // "Introduction to Algorithms (Second ed.)", pp. 651-664. // [2] "Ford-Fulkerson algorithm", Wikipedia, // 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm' class MaxBipartiteMatchState { public: explicit MaxBipartiteMatchState(const MatchMatrix& graph) : graph_(&graph), left_(graph_->LhsSize(), kUnused), right_(graph_->RhsSize(), kUnused) { } // Returns the edges of a maximal match, each in the form {left, right}. ElementMatcherPairs Compute() { // 'seen' is used for path finding { 0: unseen, 1: seen }. ::std::vector<char> seen; // Searches the residual flow graph for a path from each left node to // the sink in the residual flow graph, and if one is found, add flow // to the graph. It's okay to search through the left nodes once. The // edge from the implicit source node to each previously-visited left // node will have flow if that left node has any path to the sink // whatsoever. Subsequent augmentations can only add flow to the // network, and cannot take away that previous flow unit from the source. // Since the source-to-left edge can only carry one flow unit (or, // each element can be matched to only one matcher), there is no need // to visit the left nodes more than once looking for augmented paths. // The flow is known to be possible or impossible by looking at the // node once. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { // Reset the path-marking vector and try to find a path from // source to sink starting at the left_[ilhs] node. GTEST_CHECK_(left_[ilhs] == kUnused) << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs]; // 'seen' initialized to 'graph_->RhsSize()' copies of 0. seen.assign(graph_->RhsSize(), 0); TryAugment(ilhs, &seen); } ElementMatcherPairs result; for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) { size_t irhs = left_[ilhs]; if (irhs == kUnused) continue; result.push_back(ElementMatcherPair(ilhs, irhs)); } return result; } private: static const size_t kUnused = static_cast<size_t>(-1); // Perform a depth-first search from left node ilhs to the sink. If a // path is found, flow is added to the network by linking the left and // right vector elements corresponding each segment of the path. // Returns true if a path to sink was found, which means that a unit of // flow was added to the network. The 'seen' vector elements correspond // to right nodes and are marked to eliminate cycles from the search. // // Left nodes will only be explored at most once because they // are accessible from at most one right node in the residual flow // graph. // // Note that left_[ilhs] is the only element of left_ that TryAugment will // potentially transition from kUnused to another value. Any other // left_ element holding kUnused before TryAugment will be holding it // when TryAugment returns. // bool TryAugment(size_t ilhs, ::std::vector<char>* seen) { for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { if ((*seen)[irhs]) continue; if (!graph_->HasEdge(ilhs, irhs)) continue; // There's an available edge from ilhs to irhs. (*seen)[irhs] = 1; // Next a search is performed to determine whether // this edge is a dead end or leads to the sink. // // right_[irhs] == kUnused means that there is residual flow from // right node irhs to the sink, so we can use that to finish this // flow path and return success. // // Otherwise there is residual flow to some ilhs. We push flow // along that path and call ourselves recursively to see if this // ultimately leads to sink. if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) { // Add flow from left_[ilhs] to right_[irhs]. left_[ilhs] = irhs; right_[irhs] = ilhs; return true; } } return false; } const MatchMatrix* graph_; // not owned // Each element of the left_ vector represents a left hand side node // (i.e. an element) and each element of right_ is a right hand side // node (i.e. a matcher). The values in the left_ vector indicate - // outflow from that node to a node on the the right_ side. The values + // outflow from that node to a node on the right_ side. The values // in the right_ indicate inflow, and specify which left_ node is // feeding that right_ node, if any. For example, left_[3] == 1 means // there's a flow from element #3 to matcher #1. Such a flow would also // be redundantly represented in the right_ vector as right_[1] == 3. // Elements of left_ and right_ are either kUnused or mutually // referent. Mutually referent means that left_[right_[i]] = i and // right_[left_[i]] = i. ::std::vector<size_t> left_; ::std::vector<size_t> right_; GTEST_DISALLOW_ASSIGN_(MaxBipartiteMatchState); }; const size_t MaxBipartiteMatchState::kUnused; GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) { return MaxBipartiteMatchState(g).Compute(); } static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, ::std::ostream* stream) { typedef ElementMatcherPairs::const_iterator Iter; ::std::ostream& os = *stream; os << "{"; const char *sep = ""; for (Iter it = pairs.begin(); it != pairs.end(); ++it) { os << sep << "\n (" << "element #" << it->first << ", " << "matcher #" << it->second << ")"; sep = ","; } os << "\n}"; } // Tries to find a pairing, and explains the result. GTEST_API_ bool FindPairing(const MatchMatrix& matrix, MatchResultListener* listener) { ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix); size_t max_flow = matches.size(); bool result = (max_flow == matrix.RhsSize()); if (!result) { if (listener->IsInterested()) { *listener << "where no permutation of the elements can " "satisfy all matchers, and the closest match is " << max_flow << " of " << matrix.RhsSize() << " matchers with the pairings:\n"; LogElementMatcherPairVec(matches, listener->stream()); } return false; } if (matches.size() > 1) { if (listener->IsInterested()) { const char *sep = "where:\n"; for (size_t mi = 0; mi < matches.size(); ++mi) { *listener << sep << " - element #" << matches[mi].first << " is matched by matcher #" << matches[mi].second; sep = ",\n"; } } } return true; } bool MatchMatrix::NextGraph() { for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) { for (size_t irhs = 0; irhs < RhsSize(); ++irhs) { char& b = matched_[SpaceIndex(ilhs, irhs)]; if (!b) { b = 1; return true; } b = 0; } } return false; } void MatchMatrix::Randomize() { for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) { for (size_t irhs = 0; irhs < RhsSize(); ++irhs) { char& b = matched_[SpaceIndex(ilhs, irhs)]; b = static_cast<char>(rand() & 1); // NOLINT } } } std::string MatchMatrix::DebugString() const { ::std::stringstream ss; const char *sep = ""; for (size_t i = 0; i < LhsSize(); ++i) { ss << sep; for (size_t j = 0; j < RhsSize(); ++j) { ss << HasEdge(i, j); } sep = ";"; } return ss.str(); } void UnorderedElementsAreMatcherImplBase::DescribeToImpl( ::std::ostream* os) const { if (matcher_describers_.empty()) { *os << "is empty"; return; } if (matcher_describers_.size() == 1) { *os << "has " << Elements(1) << " and that element "; matcher_describers_[0]->DescribeTo(os); return; } *os << "has " << Elements(matcher_describers_.size()) << " and there exists some permutation of elements such that:\n"; const char* sep = ""; for (size_t i = 0; i != matcher_describers_.size(); ++i) { *os << sep << " - element #" << i << " "; matcher_describers_[i]->DescribeTo(os); sep = ", and\n"; } } void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( ::std::ostream* os) const { if (matcher_describers_.empty()) { *os << "isn't empty"; return; } if (matcher_describers_.size() == 1) { *os << "doesn't have " << Elements(1) << ", or has " << Elements(1) << " that "; matcher_describers_[0]->DescribeNegationTo(os); return; } *os << "doesn't have " << Elements(matcher_describers_.size()) << ", or there exists no permutation of elements such that:\n"; const char* sep = ""; for (size_t i = 0; i != matcher_describers_.size(); ++i) { *os << sep << " - element #" << i << " "; matcher_describers_[i]->DescribeTo(os); sep = ", and\n"; } } // Checks that all matchers match at least one element, and that all // elements match at least one matcher. This enables faster matching // and better error reporting. // Returns false, writing an explanation to 'listener', if and only // if the success criteria are not met. bool UnorderedElementsAreMatcherImplBase:: VerifyAllElementsAndMatchersAreMatched( const ::std::vector<std::string>& element_printouts, const MatchMatrix& matrix, MatchResultListener* listener) const { bool result = true; ::std::vector<char> element_matched(matrix.LhsSize(), 0); ::std::vector<char> matcher_matched(matrix.RhsSize(), 0); for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) { for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) { char matched = matrix.HasEdge(ilhs, irhs); element_matched[ilhs] |= matched; matcher_matched[irhs] |= matched; } } { const char* sep = "where the following matchers don't match any elements:\n"; for (size_t mi = 0; mi < matcher_matched.size(); ++mi) { if (matcher_matched[mi]) continue; result = false; if (listener->IsInterested()) { *listener << sep << "matcher #" << mi << ": "; matcher_describers_[mi]->DescribeTo(listener->stream()); sep = ",\n"; } } } { const char* sep = "where the following elements don't match any matchers:\n"; const char* outer_sep = ""; if (!result) { outer_sep = "\nand "; } for (size_t ei = 0; ei < element_matched.size(); ++ei) { if (element_matched[ei]) continue; result = false; if (listener->IsInterested()) { *listener << outer_sep << sep << "element #" << ei << ": " << element_printouts[ei]; sep = ",\n"; outer_sep = ""; } } } return result; } } // namespace internal } // namespace testing diff --git a/googlemock/src/gmock-spec-builders.cc b/googlemock/src/gmock-spec-builders.cc index 2fa1ee4b..f761f97e 100644 --- a/googlemock/src/gmock-spec-builders.cc +++ b/googlemock/src/gmock-spec-builders.cc @@ -1,822 +1,822 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements the spec builder syntax (ON_CALL and // EXPECT_CALL). #include "gmock/gmock-spec-builders.h" #include <stdlib.h> #include <iostream> // NOLINT #include <map> #include <set> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC # include <unistd.h> // NOLINT #endif namespace testing { namespace internal { // Protects the mock object registry (in class Mock), all function // mockers, and all expectations. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const std::string& message) { ::std::ostringstream s; s << file << ":" << line << ": " << message << ::std::endl; Log(severity, s.str(), 0); } // Constructs an ExpectationBase object. ExpectationBase::ExpectationBase(const char* a_file, int a_line, const std::string& a_source_text) : file_(a_file), line_(a_line), source_text_(a_source_text), cardinality_specified_(false), cardinality_(Exactly(1)), call_count_(0), retired_(false), extra_matcher_specified_(false), repeated_action_specified_(false), retires_on_saturation_(false), last_clause_(kNone), action_count_checked_(false) {} // Destructs an ExpectationBase object. ExpectationBase::~ExpectationBase() {} // Explicitly specifies the cardinality of this expectation. Used by // the subclasses to implement the .Times() clause. void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { cardinality_specified_ = true; cardinality_ = a_cardinality; } // Retires all pre-requisites of this expectation. void ExpectationBase::RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { if (is_retired()) { // We can take this short-cut as we never retire an expectation // until we have retired all its pre-requisites. return; } for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); ++it) { ExpectationBase* const prerequisite = it->expectation_base().get(); if (!prerequisite->is_retired()) { prerequisite->RetireAllPreRequisites(); prerequisite->Retire(); } } } // Returns true iff all pre-requisites of this expectation have been // satisfied. bool ExpectationBase::AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); ++it) { if (!(it->expectation_base()->IsSatisfied()) || !(it->expectation_base()->AllPrerequisitesAreSatisfied())) return false; } return true; } // Adds unsatisfied pre-requisites of this expectation to 'result'. void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); ++it) { if (it->expectation_base()->IsSatisfied()) { // If *it is satisfied and has a call count of 0, some of its // pre-requisites may not be satisfied yet. if (it->expectation_base()->call_count_ == 0) { it->expectation_base()->FindUnsatisfiedPrerequisites(result); } } else { // Now that we know *it is unsatisfied, we are not so interested // in whether its pre-requisites are satisfied. Therefore we // don't recursively call FindUnsatisfiedPrerequisites() here. *result += *it; } } } // Describes how many times a function call matching this // expectation has occurred. void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // Describes how many times the function is expected to be called. *os << " Expected: to be "; cardinality().DescribeTo(os); *os << "\n Actual: "; Cardinality::DescribeActualCallCountTo(call_count(), os); // Describes the state of the expectation (e.g. is it satisfied? // is it active?). *os << " - " << (IsOverSaturated() ? "over-saturated" : IsSaturated() ? "saturated" : IsSatisfied() ? "satisfied" : "unsatisfied") << " and " << (is_retired() ? "retired" : "active"); } // Checks the action count (i.e. the number of WillOnce() and // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. void ExpectationBase::CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_) { bool should_check = false; { MutexLock l(&mutex_); if (!action_count_checked_) { action_count_checked_ = true; should_check = true; } } if (should_check) { if (!cardinality_specified_) { // The cardinality was inferred - no need to check the action // count against it. return; } // The cardinality was explicitly specified. const int action_count = static_cast<int>(untyped_actions_.size()); const int upper_bound = cardinality().ConservativeUpperBound(); const int lower_bound = cardinality().ConservativeLowerBound(); bool too_many; // True if there are too many actions, or false // if there are too few. if (action_count > upper_bound || (action_count == upper_bound && repeated_action_specified_)) { too_many = true; } else if (0 < action_count && action_count < lower_bound && !repeated_action_specified_) { too_many = false; } else { return; } ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Too " << (too_many ? "many" : "few") << " actions specified in " << source_text() << "...\n" << "Expected to be "; cardinality().DescribeTo(&ss); ss << ", but has " << (too_many ? "" : "only ") << action_count << " WillOnce()" << (action_count == 1 ? "" : "s"); if (repeated_action_specified_) { ss << " and a WillRepeatedly()"; } ss << "."; Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace". } } // Implements the .Times() clause. void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) { if (last_clause_ == kTimes) { ExpectSpecProperty(false, ".Times() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty(last_clause_ < kTimes, ".Times() cannot appear after " ".InSequence(), .WillOnce(), .WillRepeatedly(), " "or .RetiresOnSaturation()."); } last_clause_ = kTimes; SpecifyCardinality(a_cardinality); } // Points to the implicit sequence introduced by a living InSequence // object (if any) in the current thread or NULL. GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { // Include a stack trace only if --gmock_verbose=info is specified. const int stack_frames_to_skip = GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1; switch (reaction) { case kAllow: Log(kInfo, msg, stack_frames_to_skip); break; case kWarn: Log(kWarning, msg + "\nNOTE: You can safely ignore the above warning unless this " "call should not happen. Do not suppress it by blindly adding " "an EXPECT_CALL() if you don't mean to enforce the call. " "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" "knowing-when-to-expect for details.\n", stack_frames_to_skip); break; default: // FAIL Expect(false, NULL, -1, msg); } } UntypedFunctionMockerBase::UntypedFunctionMockerBase() : mock_obj_(NULL), name_("") {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} // Sets the mock object this mock method belongs to, and registers // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { { MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; } Mock::Register(mock_obj, this); } // Sets the mock object this mock method belongs to, and sets the name // of the mock function. Will be called upon each invocation of this // mock function. void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { // We protect name_ under g_gmock_mutex in case this mock function // is called from two threads concurrently. MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; name_ = name; } // Returns the name of the function being mocked. Must be called // after RegisterOwner() or SetOwnerAndName() has been called. const void* UntypedFunctionMockerBase::MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const void* mock_obj; { // We protect mock_obj_ under g_gmock_mutex in case this mock // function is called from two threads concurrently. MutexLock l(&g_gmock_mutex); Assert(mock_obj_ != NULL, __FILE__, __LINE__, "MockObject() must not be called before RegisterOwner() or " "SetOwnerAndName() has been called."); mock_obj = mock_obj_; } return mock_obj; } // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. const char* UntypedFunctionMockerBase::Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const char* name; { // We protect name_ under g_gmock_mutex in case this mock // function is called from two threads concurrently. MutexLock l(&g_gmock_mutex); Assert(name_ != NULL, __FILE__, __LINE__, "Name() must not be called before SetOwnerAndName() has " "been called."); name = name_; } return name; } // Calculates the result of invoking this mock function with the given // arguments, prints it, and returns it. The caller is responsible // for deleting the result. UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { if (untyped_expectations_.size() == 0) { // No expectation is set on this mock method - we have an // uninteresting call. // We must get Google Mock's reaction on uninteresting calls // made on this mock object BEFORE performing the action, // because the action may DELETE the mock object and make the // following expression meaningless. const CallReaction reaction = Mock::GetReactionOnUninterestingCalls(MockObject()); // True iff we need to print this call's arguments and return // value. This definition must be kept in sync with // the behavior of ReportUninterestingCall(). const bool need_to_report_uninteresting_call = // If the user allows this uninteresting call, we print it // only when he wants informational messages. reaction == kAllow ? LogIsVisible(kInfo) : // If the user wants this to be a warning, we print it only // when he wants to see warnings. reaction == kWarn ? LogIsVisible(kWarning) : // Otherwise, the user wants this to be an error, and we // should always print detailed information in the error. true; if (!need_to_report_uninteresting_call) { // Perform the action without printing the call information. - return this->UntypedPerformDefaultAction(untyped_args, ""); + return this->UntypedPerformDefaultAction(untyped_args, "Function call: " + std::string(Name())); } // Warns about the uninteresting call. ::std::stringstream ss; this->UntypedDescribeUninterestingCall(untyped_args, &ss); // Calculates the function result. UntypedActionResultHolderBase* const result = this->UntypedPerformDefaultAction(untyped_args, ss.str()); // Prints the function result. if (result != NULL) result->PrintAsActionResult(&ss); ReportUninterestingCall(reaction, ss.str()); return result; } bool is_excessive = false; ::std::stringstream ss; ::std::stringstream why; ::std::stringstream loc; const void* untyped_action = NULL; // The UntypedFindMatchingExpectation() function acquires and // releases g_gmock_mutex. const ExpectationBase* const untyped_expectation = this->UntypedFindMatchingExpectation( untyped_args, &untyped_action, &is_excessive, &ss, &why); const bool found = untyped_expectation != NULL; // True iff we need to print the call's arguments and return value. // This definition must be kept in sync with the uses of Expect() // and Log() in this function. const bool need_to_report_call = !found || is_excessive || LogIsVisible(kInfo); if (!need_to_report_call) { // Perform the action without printing the call information. return untyped_action == NULL ? this->UntypedPerformDefaultAction(untyped_args, "") : this->UntypedPerformAction(untyped_action, untyped_args); } ss << " Function call: " << Name(); this->UntypedPrintArgs(untyped_args, &ss); // In case the action deletes a piece of the expectation, we // generate the message beforehand. if (found && !is_excessive) { untyped_expectation->DescribeLocationTo(&loc); } UntypedActionResultHolderBase* const result = untyped_action == NULL ? this->UntypedPerformDefaultAction(untyped_args, ss.str()) : this->UntypedPerformAction(untyped_action, untyped_args); if (result != NULL) result->PrintAsActionResult(&ss); ss << "\n" << why.str(); if (!found) { // No expectation matches this call - reports a failure. Expect(false, NULL, -1, ss.str()); } else if (is_excessive) { // We had an upper-bound violation and the failure message is in ss. Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } else { // We had an expected call and the matching expectation is // described in ss. Log(kInfo, loc.str() + ss.str(), 2); } return result; } // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { if (it->get() == exp) { return Expectation(*it); } } Assert(false, __FILE__, __LINE__, "Cannot find expectation."); return Expectation(); // The above statement is just to make the code compile, and will // never be executed. } // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); bool expectations_met = true; for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); ++it) { ExpectationBase* const untyped_expectation = it->get(); if (untyped_expectation->IsOverSaturated()) { // There was an upper-bound violation. Since the error was // already reported when it occurred, there is no need to do // anything here. expectations_met = false; } else if (!untyped_expectation->IsSatisfied()) { expectations_met = false; ::std::stringstream ss; ss << "Actual function call count doesn't match " << untyped_expectation->source_text() << "...\n"; // No need to show the source file location of the expectation // in the description, as the Expect() call that follows already // takes care of it. untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->DescribeCallCountTo(&ss); Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } } // Deleting our expectations may trigger other mock objects to be deleted, for // example if an action contains a reference counted smart pointer to that // mock object, and that is the last reference. So if we delete our // expectations within the context of the global mutex we may deadlock when // this method is called again. Instead, make a copy of the set of // expectations to delete, clear our set within the mutex, and then clear the // copied set outside of it. UntypedExpectations expectations_to_delete; untyped_expectations_.swap(expectations_to_delete); g_gmock_mutex.Unlock(); expectations_to_delete.clear(); g_gmock_mutex.Lock(); return expectations_met; } } // namespace internal // Class Mock. namespace { typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; // The current state of a mock object. Such information is needed for // detecting leaked mock objects and explicitly verifying a mock's // expectations. struct MockObjectState { MockObjectState() : first_used_file(NULL), first_used_line(-1), leakable(false) {} // Where in the source file an ON_CALL or EXPECT_CALL is first // invoked on this mock object. const char* first_used_file; int first_used_line; ::std::string first_used_test_case; ::std::string first_used_test; bool leakable; // true iff it's OK to leak the object. FunctionMockers function_mockers; // All registered methods of the object. }; // A global registry holding the state of all mock objects that are // alive. A mock object is added to this registry the first time // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It // is removed from the registry in the mock object's destructor. class MockObjectRegistry { public: // Maps a mock object (identified by its address) to its state. typedef std::map<const void*, MockObjectState> StateMap; // This destructor will be called when a program exits, after all // tests in it have been run. By then, there should be no mock // object alive. Therefore we report any living object as test // failure, unless the user explicitly asked us to ignore it. ~MockObjectRegistry() { // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is // a macro. if (!GMOCK_FLAG(catch_leaked_mocks)) return; int leaked_count = 0; for (StateMap::const_iterator it = states_.begin(); it != states_.end(); ++it) { if (it->second.leakable) // The user said it's fine to leak this object. continue; // TODO(wan@google.com): Print the type of the leaked object. // This can help the user identify the leaked object. std::cout << "\n"; const MockObjectState& state = it->second; std::cout << internal::FormatFileLocation(state.first_used_file, state.first_used_line); std::cout << " ERROR: this mock object"; if (state.first_used_test != "") { std::cout << " (used in test " << state.first_used_test_case << "." << state.first_used_test << ")"; } std::cout << " should be deleted but never is. Its address is @" << it->first << "."; leaked_count++; } if (leaked_count > 0) { std::cout << "\nERROR: " << leaked_count << " leaked mock " << (leaked_count == 1 ? "object" : "objects") << " found at program exit.\n"; std::cout.flush(); ::std::cerr.flush(); // RUN_ALL_TESTS() has already returned when this destructor is // called. Therefore we cannot use the normal Google Test // failure reporting mechanism. _exit(1); // We cannot call exit() as it is not reentrant and // may already have been called. } } StateMap& states() { return states_; } private: StateMap states_; }; // Protected by g_gmock_mutex. MockObjectRegistry g_mock_object_registry; // Maps a mock object to the reaction Google Mock should have when an // uninteresting method is called. Protected by g_gmock_mutex. std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction; // Sets the reaction Google Mock should have when an uninteresting // method of the given mock object is called. void SetReactionOnUninterestingCalls(const void* mock_obj, internal::CallReaction reaction) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_uninteresting_call_reaction[mock_obj] = reaction; } } // namespace // Tells Google Mock to allow uninteresting calls on the given mock // object. void Mock::AllowUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); } // Tells Google Mock to warn the user about uninteresting calls on the // given mock object. void Mock::WarnUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); } // Tells Google Mock to fail uninteresting calls on the given mock // object. void Mock::FailUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kFail); } // Tells Google Mock the given mock object is being destroyed and its // entry in the call-reaction table should be removed. void Mock::UnregisterCallReaction(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_uninteresting_call_reaction.erase(mock_obj); } // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. internal::CallReaction Mock::GetReactionOnUninterestingCalls( const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? internal::kDefault : g_uninteresting_call_reaction[mock_obj]; } // Tells Google Mock to ignore mock_obj when checking for leaked mock // objects. void Mock::AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].leakable = true; } // Verifies and clears all expectations on the given mock object. If // the expectations aren't satisfied, generates one or more Google // Test non-fatal failures and returns false. bool Mock::VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return VerifyAndClearExpectationsLocked(mock_obj); } // Verifies all expectations on the given mock object and clears its // default actions and expectations. Returns true iff the // verification was successful. bool Mock::VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); ClearDefaultActionsLocked(mock_obj); return VerifyAndClearExpectationsLocked(mock_obj); } // Verifies and clears all expectations on the given mock object. If // the expectations aren't satisfied, generates one or more Google // Test non-fatal failures and returns false. bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { // No EXPECT_CALL() was set on the given mock object. return true; } // Verifies and clears the expectations on each mock method in the // given mock object. bool expectations_met = true; FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { if (!(*it)->VerifyAndClearExpectationsLocked()) { expectations_met = false; } } // We don't clear the content of mockers, as they may still be // needed by ClearDefaultActionsLocked(). return expectations_met; } // Registers a mock object and a mock method it owns. void Mock::Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); } // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); MockObjectState& state = g_mock_object_registry.states()[mock_obj]; if (state.first_used_file == NULL) { state.first_used_file = file; state.first_used_line = line; const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != NULL) { // TODO(wan@google.com): record the test case name when the // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or // TearDownTestCase(). state.first_used_test_case = test_info->test_case_name(); state.first_used_test = test_info->name(); } } } // Unregisters a mock method; removes the owning mock object from the // registry when the last mock method associated with it has been // unregistered. This is called only in the destructor of // FunctionMockerBase. void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); for (MockObjectRegistry::StateMap::iterator it = g_mock_object_registry.states().begin(); it != g_mock_object_registry.states().end(); ++it) { FunctionMockers& mockers = it->second.function_mockers; if (mockers.erase(mocker) > 0) { // mocker was in mockers and has been just removed. if (mockers.empty()) { g_mock_object_registry.states().erase(it); } return; } } } // Clears all ON_CALL()s set on the given mock object. void Mock::ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { // No ON_CALL() was set on the given mock object. return; } // Clears the default actions for each mock method in the given mock // object. FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { (*it)->ClearDefaultActionsLocked(); } // We don't clear the content of mockers, as they may still be // needed by VerifyAndClearExpectationsLocked(). } Expectation::Expectation() {} Expectation::Expectation( const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base) : expectation_base_(an_expectation_base) {} Expectation::~Expectation() {} // Adds an expectation to a sequence. void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { if (last_expectation_->expectation_base() != NULL) { expectation.expectation_base()->immediate_prerequisites_ += *last_expectation_; } *last_expectation_ = expectation; } } // Creates the implicit sequence if there isn't one. InSequence::InSequence() { if (internal::g_gmock_implicit_sequence.get() == NULL) { internal::g_gmock_implicit_sequence.set(new Sequence); sequence_created_ = true; } else { sequence_created_ = false; } } // Deletes the implicit sequence if it was created by the constructor // of this object. InSequence::~InSequence() { if (sequence_created_) { delete internal::g_gmock_implicit_sequence.get(); internal::g_gmock_implicit_sequence.set(NULL); } } } // namespace testing diff --git a/googlemock/test/BUILD.bazel b/googlemock/test/BUILD.bazel new file mode 100644 index 00000000..6e67f187 --- /dev/null +++ b/googlemock/test/BUILD.bazel @@ -0,0 +1,52 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: misterg@google.com (Gennadiy Civil) +# +# Bazel Build for Google C++ Testing Framework(Google Test)-googlemock + +""" gmock own tests """ + +cc_test( + name = "gmock_all_test", + size = "small", + srcs = glob( + include = [ + "gmock-*.cc", + ], + ), + linkopts = select({ + "//:win": [], + "//conditions:default": [ + "-pthread", + ], + }), + deps = ["//:gtest"], +) diff --git a/googlemock/test/gmock-generated-actions_test.cc b/googlemock/test/gmock-generated-actions_test.cc index 58d45728..80bcb31c 100644 --- a/googlemock/test/gmock-generated-actions_test.cc +++ b/googlemock/test/gmock-generated-actions_test.cc @@ -1,1228 +1,1228 @@ // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file tests the built-in actions generated by a script. #include "gmock/gmock-generated-actions.h" #include <functional> #include <sstream> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace testing { namespace gmock_generated_actions_test { using ::std::plus; using ::std::string; using testing::get; using testing::make_tuple; using testing::tuple; using testing::tuple_element; using testing::_; using testing::Action; using testing::ActionInterface; using testing::ByRef; using testing::DoAll; using testing::Invoke; using testing::Return; using testing::ReturnNew; using testing::SetArgPointee; using testing::StaticAssertTypeEq; using testing::Unused; using testing::WithArgs; // For suppressing compiler warnings on conversion possibly losing precision. inline short Short(short n) { return n; } // NOLINT inline char Char(char ch) { return ch; } // Sample functions and functors for testing various actions. int Nullary() { return 1; } class NullaryFunctor { public: int operator()() { return 2; } }; bool g_done = false; bool Unary(int x) { return x < 0; } const char* Plus1(const char* s) { return s + 1; } bool ByConstRef(const std::string& s) { return s == "Hi"; } const double g_double = 0; bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; } std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT struct UnaryFunctor { int operator()(bool x) { return x ? 1 : -1; } }; const char* Binary(const char* input, short n) { return input + n; } // NOLINT void VoidBinary(int, char) { g_done = true; } int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT void VoidTernary(int, char, bool) { g_done = true; } int SumOf4(int a, int b, int c, int d) { return a + b + c + d; } std::string Concat4(const char* s1, const char* s2, const char* s3, const char* s4) { return std::string(s1) + s2 + s3 + s4; } int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; } struct SumOf5Functor { int operator()(int a, int b, int c, int d, int e) { return a + b + c + d + e; } }; std::string Concat5(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5) { return std::string(s1) + s2 + s3 + s4 + s5; } int SumOf6(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } struct SumOf6Functor { int operator()(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } }; std::string Concat6(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6) { return std::string(s1) + s2 + s3 + s4 + s5 + s6; } std::string Concat7(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7; } std::string Concat8(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8; } std::string Concat9(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9; } std::string Concat10(const char* s1, const char* s2, const char* s3, const char* s4, const char* s5, const char* s6, const char* s7, const char* s8, const char* s9, const char* s10) { return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10; } // A helper that turns the type of a C-string literal from const // char[N] to const char*. inline const char* CharPtr(const char* s) { return s; } // Tests InvokeArgument<N>(...). // Tests using InvokeArgument with a nullary function. TEST(InvokeArgumentTest, Function0) { Action<int(int, int(*)())> a = InvokeArgument<1>(); // NOLINT EXPECT_EQ(1, a.Perform(make_tuple(2, &Nullary))); } // Tests using InvokeArgument with a unary function. TEST(InvokeArgumentTest, Functor1) { Action<int(UnaryFunctor)> a = InvokeArgument<0>(true); // NOLINT EXPECT_EQ(1, a.Perform(make_tuple(UnaryFunctor()))); } // Tests using InvokeArgument with a 5-ary function. TEST(InvokeArgumentTest, Function5) { Action<int(int(*)(int, int, int, int, int))> a = // NOLINT InvokeArgument<0>(10000, 2000, 300, 40, 5); EXPECT_EQ(12345, a.Perform(make_tuple(&SumOf5))); } // Tests using InvokeArgument with a 5-ary functor. TEST(InvokeArgumentTest, Functor5) { Action<int(SumOf5Functor)> a = // NOLINT InvokeArgument<0>(10000, 2000, 300, 40, 5); EXPECT_EQ(12345, a.Perform(make_tuple(SumOf5Functor()))); } // Tests using InvokeArgument with a 6-ary function. TEST(InvokeArgumentTest, Function6) { Action<int(int(*)(int, int, int, int, int, int))> a = // NOLINT InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); EXPECT_EQ(123456, a.Perform(make_tuple(&SumOf6))); } // Tests using InvokeArgument with a 6-ary functor. TEST(InvokeArgumentTest, Functor6) { Action<int(SumOf6Functor)> a = // NOLINT InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6); EXPECT_EQ(123456, a.Perform(make_tuple(SumOf6Functor()))); } // Tests using InvokeArgument with a 7-ary function. TEST(InvokeArgumentTest, Function7) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7"); EXPECT_EQ("1234567", a.Perform(make_tuple(&Concat7))); } // Tests using InvokeArgument with a 8-ary function. TEST(InvokeArgumentTest, Function8) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8"); EXPECT_EQ("12345678", a.Perform(make_tuple(&Concat8))); } // Tests using InvokeArgument with a 9-ary function. TEST(InvokeArgumentTest, Function9) { Action<std::string(std::string(*)(const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9"); EXPECT_EQ("123456789", a.Perform(make_tuple(&Concat9))); } // Tests using InvokeArgument with a 10-ary function. TEST(InvokeArgumentTest, Function10) { Action<std::string(std::string(*)( const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*, const char*))> a = InvokeArgument<0>("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); EXPECT_EQ("1234567890", a.Perform(make_tuple(&Concat10))); } // Tests using InvokeArgument with a function that takes a pointer argument. TEST(InvokeArgumentTest, ByPointerFunction) { Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT InvokeArgument<0>(static_cast<const char*>("Hi"), Short(1)); EXPECT_STREQ("i", a.Perform(make_tuple(&Binary))); } // Tests using InvokeArgument with a function that takes a const char* // by passing it a C-string literal. TEST(InvokeArgumentTest, FunctionWithCStringLiteral) { Action<const char*(const char*(*)(const char* input, short n))> a = // NOLINT InvokeArgument<0>("Hi", Short(1)); EXPECT_STREQ("i", a.Perform(make_tuple(&Binary))); } // Tests using InvokeArgument with a function that takes a const reference. TEST(InvokeArgumentTest, ByConstReferenceFunction) { Action<bool(bool (*function)(const std::string& s))> a = // NOLINT InvokeArgument<0>(std::string("Hi")); // When action 'a' is constructed, it makes a copy of the temporary // string object passed to it, so it's OK to use 'a' later, when the // temporary object has already died. EXPECT_TRUE(a.Perform(make_tuple(&ByConstRef))); } // Tests using InvokeArgument with ByRef() and a function that takes a // const reference. TEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) { Action<bool(bool(*)(const double& x))> a = // NOLINT InvokeArgument<0>(ByRef(g_double)); // The above line calls ByRef() on a const value. EXPECT_TRUE(a.Perform(make_tuple(&ReferencesGlobalDouble))); double x = 0; a = InvokeArgument<0>(ByRef(x)); // This calls ByRef() on a non-const. EXPECT_FALSE(a.Perform(make_tuple(&ReferencesGlobalDouble))); } // Tests using WithArgs and with an action that takes 1 argument. TEST(WithArgsTest, OneArg) { Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT EXPECT_TRUE(a.Perform(make_tuple(1.5, -1))); EXPECT_FALSE(a.Perform(make_tuple(1.5, 1))); } // Tests using WithArgs with an action that takes 2 arguments. TEST(WithArgsTest, TwoArgs) { Action<const char*(const char* s, double x, short n)> a = WithArgs<0, 2>(Invoke(Binary)); const char s[] = "Hello"; EXPECT_EQ(s + 2, a.Perform(make_tuple(CharPtr(s), 0.5, Short(2)))); } // Tests using WithArgs with an action that takes 3 arguments. TEST(WithArgsTest, ThreeArgs) { Action<int(int, double, char, short)> a = // NOLINT WithArgs<0, 2, 3>(Invoke(Ternary)); EXPECT_EQ(123, a.Perform(make_tuple(100, 6.5, Char(20), Short(3)))); } // Tests using WithArgs with an action that takes 4 arguments. TEST(WithArgsTest, FourArgs) { Action<std::string(const char*, const char*, double, const char*, const char*)> a = WithArgs<4, 3, 1, 0>(Invoke(Concat4)); EXPECT_EQ("4310", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), 2.5, CharPtr("3"), CharPtr("4")))); } // Tests using WithArgs with an action that takes 5 arguments. TEST(WithArgsTest, FiveArgs) { Action<std::string(const char*, const char*, const char*, const char*, const char*)> a = WithArgs<4, 3, 2, 1, 0>(Invoke(Concat5)); EXPECT_EQ("43210", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), CharPtr("3"), CharPtr("4")))); } // Tests using WithArgs with an action that takes 6 arguments. TEST(WithArgsTest, SixArgs) { Action<std::string(const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 2, 1, 0>(Invoke(Concat6)); EXPECT_EQ("012210", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2")))); } // Tests using WithArgs with an action that takes 7 arguments. TEST(WithArgsTest, SevenArgs) { Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 2, 1, 0>(Invoke(Concat7)); EXPECT_EQ("0123210", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that takes 8 arguments. TEST(WithArgsTest, EightArgs) { Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 0, 1, 2, 3>(Invoke(Concat8)); EXPECT_EQ("01230123", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that takes 9 arguments. TEST(WithArgsTest, NineArgs) { Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 1, 2, 3, 2, 3>(Invoke(Concat9)); EXPECT_EQ("012312323", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that takes 10 arguments. TEST(WithArgsTest, TenArgs) { Action<std::string(const char*, const char*, const char*, const char*)> a = WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(Concat10)); EXPECT_EQ("0123210123", a.Perform(make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"), CharPtr("3")))); } // Tests using WithArgs with an action that is not Invoke(). class SubstractAction : public ActionInterface<int(int, int)> { // NOLINT public: virtual int Perform(const tuple<int, int>& args) { return get<0>(args) - get<1>(args); } }; TEST(WithArgsTest, NonInvokeAction) { Action<int(const string&, int, int)> a = // NOLINT WithArgs<2, 1>(MakeAction(new SubstractAction)); string s("hello"); EXPECT_EQ(8, a.Perform(tuple<const string&, int, int>(s, 2, 10))); } // Tests using WithArgs to pass all original arguments in the original order. TEST(WithArgsTest, Identity) { Action<int(int x, char y, short z)> a = // NOLINT WithArgs<0, 1, 2>(Invoke(Ternary)); EXPECT_EQ(123, a.Perform(make_tuple(100, Char(20), Short(3)))); } // Tests using WithArgs with repeated arguments. TEST(WithArgsTest, RepeatedArguments) { Action<int(bool, int m, int n)> a = // NOLINT WithArgs<1, 1, 1, 1>(Invoke(SumOf4)); EXPECT_EQ(4, a.Perform(make_tuple(false, 1, 10))); } // Tests using WithArgs with reversed argument order. TEST(WithArgsTest, ReversedArgumentOrder) { Action<const char*(short n, const char* input)> a = // NOLINT WithArgs<1, 0>(Invoke(Binary)); const char s[] = "Hello"; EXPECT_EQ(s + 2, a.Perform(make_tuple(Short(2), CharPtr(s)))); } // Tests using WithArgs with compatible, but not identical, argument types. TEST(WithArgsTest, ArgsOfCompatibleTypes) { Action<long(short x, char y, double z, char c)> a = // NOLINT WithArgs<0, 1, 3>(Invoke(Ternary)); EXPECT_EQ(123, a.Perform(make_tuple(Short(100), Char(20), 5.6, Char(3)))); } // Tests using WithArgs with an action that returns void. TEST(WithArgsTest, VoidAction) { Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary)); g_done = false; a.Perform(make_tuple(1.5, 'a', 3)); EXPECT_TRUE(g_done); } // Tests DoAll(a1, a2). TEST(DoAllTest, TwoActions) { int n = 0; Action<int(int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT Return(2)); EXPECT_EQ(2, a.Perform(make_tuple(&n))); EXPECT_EQ(1, n); } // Tests DoAll(a1, a2, a3). TEST(DoAllTest, ThreeActions) { int m = 0, n = 0; Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1), // NOLINT SetArgPointee<1>(2), Return(3)); EXPECT_EQ(3, a.Perform(make_tuple(&m, &n))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); } // Tests DoAll(a1, a2, a3, a4). TEST(DoAllTest, FourActions) { int m = 0, n = 0; char ch = '\0'; Action<int(int*, int*, char*)> a = // NOLINT DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), Return(3)); EXPECT_EQ(3, a.Perform(make_tuple(&m, &n, &ch))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', ch); } // Tests DoAll(a1, a2, a3, a4, a5). TEST(DoAllTest, FiveActions) { int m = 0, n = 0; char a = '\0', b = '\0'; Action<int(int*, int*, char*, char*)> action = // NOLINT DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); } // Tests DoAll(a1, a2, ..., a6). TEST(DoAllTest, SixActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0'; Action<int(int*, int*, char*, char*, char*)> action = // NOLINT DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); } // Tests DoAll(a1, a2, ..., a7). TEST(DoAllTest, SevenActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0'; Action<int(int*, int*, char*, char*, char*, char*)> action = // NOLINT DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); } // Tests DoAll(a1, a2, ..., a8). TEST(DoAllTest, EightActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0'; Action<int(int*, int*, char*, char*, char*, char*, // NOLINT char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); } // Tests DoAll(a1, a2, ..., a9). TEST(DoAllTest, NineActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0'; Action<int(int*, int*, char*, char*, char*, char*, // NOLINT char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); EXPECT_EQ('f', f); } // Tests DoAll(a1, a2, ..., a10). TEST(DoAllTest, TenActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0'; char e = '\0', f = '\0', g = '\0'; Action<int(int*, int*, char*, char*, char*, char*, // NOLINT char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); EXPECT_EQ('f', f); EXPECT_EQ('g', g); } // The ACTION*() macros trigger warning C4100 (unreferenced formal // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in // the macro definition, as the warnings are generated when the macro // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) #endif // Tests the ACTION*() macro family. // Tests that ACTION() can define an action that doesn't reference the // mock function arguments. ACTION(Return5) { return 5; } TEST(ActionMacroTest, WorksWhenNotReferencingArguments) { Action<double()> a1 = Return5(); EXPECT_DOUBLE_EQ(5, a1.Perform(make_tuple())); Action<int(double, bool)> a2 = Return5(); EXPECT_EQ(5, a2.Perform(make_tuple(1, true))); } // Tests that ACTION() can define an action that returns void. ACTION(IncrementArg1) { (*arg1)++; } TEST(ActionMacroTest, WorksWhenReturningVoid) { Action<void(int, int*)> a1 = IncrementArg1(); int n = 0; a1.Perform(make_tuple(5, &n)); EXPECT_EQ(1, n); } // Tests that the body of ACTION() can reference the type of the // argument. ACTION(IncrementArg2) { StaticAssertTypeEq<int*, arg2_type>(); arg2_type temp = arg2; (*temp)++; } TEST(ActionMacroTest, CanReferenceArgumentType) { Action<void(int, bool, int*)> a1 = IncrementArg2(); int n = 0; a1.Perform(make_tuple(5, false, &n)); EXPECT_EQ(1, n); } // Tests that the body of ACTION() can reference the argument tuple // via args_type and args. ACTION(Sum2) { StaticAssertTypeEq<tuple<int, char, int*>, args_type>(); args_type args_copy = args; return get<0>(args_copy) + get<1>(args_copy); } TEST(ActionMacroTest, CanReferenceArgumentTuple) { Action<int(int, char, int*)> a1 = Sum2(); int dummy = 0; EXPECT_EQ(11, a1.Perform(make_tuple(5, Char(6), &dummy))); } // Tests that the body of ACTION() can reference the mock function // type. int Dummy(bool flag) { return flag? 1 : 0; } ACTION(InvokeDummy) { StaticAssertTypeEq<int(bool), function_type>(); function_type* fp = &Dummy; return (*fp)(true); } TEST(ActionMacroTest, CanReferenceMockFunctionType) { Action<int(bool)> a1 = InvokeDummy(); EXPECT_EQ(1, a1.Perform(make_tuple(true))); EXPECT_EQ(1, a1.Perform(make_tuple(false))); } // Tests that the body of ACTION() can reference the mock function's // return type. ACTION(InvokeDummy2) { StaticAssertTypeEq<int, return_type>(); return_type result = Dummy(true); return result; } TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) { Action<int(bool)> a1 = InvokeDummy2(); EXPECT_EQ(1, a1.Perform(make_tuple(true))); EXPECT_EQ(1, a1.Perform(make_tuple(false))); } // Tests that ACTION() works for arguments passed by const reference. ACTION(ReturnAddrOfConstBoolReferenceArg) { StaticAssertTypeEq<const bool&, arg1_type>(); return &arg1; } TEST(ActionMacroTest, WorksForConstReferenceArg) { Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg(); const bool b = false; EXPECT_EQ(&b, a.Perform(tuple<int, const bool&>(0, b))); } // Tests that ACTION() works for arguments passed by non-const reference. ACTION(ReturnAddrOfIntReferenceArg) { StaticAssertTypeEq<int&, arg0_type>(); return &arg0; } TEST(ActionMacroTest, WorksForNonConstReferenceArg) { Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg(); int n = 0; EXPECT_EQ(&n, a.Perform(tuple<int&, bool, int>(n, true, 1))); } // Tests that ACTION() can be used in a namespace. namespace action_test { ACTION(Sum) { return arg0 + arg1; } } // namespace action_test TEST(ActionMacroTest, WorksInNamespace) { Action<int(int, int)> a1 = action_test::Sum(); EXPECT_EQ(3, a1.Perform(make_tuple(1, 2))); } // Tests that the same ACTION definition works for mock functions with // different argument numbers. ACTION(PlusTwo) { return arg0 + 2; } TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) { Action<int(int)> a1 = PlusTwo(); EXPECT_EQ(4, a1.Perform(make_tuple(2))); Action<double(float, void*)> a2 = PlusTwo(); int dummy; EXPECT_DOUBLE_EQ(6, a2.Perform(make_tuple(4.0f, &dummy))); } // Tests that ACTION_P can define a parameterized action. ACTION_P(Plus, n) { return arg0 + n; } TEST(ActionPMacroTest, DefinesParameterizedAction) { Action<int(int m, bool t)> a1 = Plus(9); EXPECT_EQ(10, a1.Perform(make_tuple(1, true))); } // Tests that the body of ACTION_P can reference the argument types // and the parameter type. ACTION_P(TypedPlus, n) { arg0_type t1 = arg0; n_type t2 = n; return t1 + t2; } TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) { Action<int(char m, bool t)> a1 = TypedPlus(9); EXPECT_EQ(10, a1.Perform(make_tuple(Char(1), true))); } // Tests that a parameterized action can be used in any mock function // whose type is compatible. TEST(ActionPMacroTest, WorksInCompatibleMockFunction) { Action<std::string(const std::string& s)> a1 = Plus("tail"); const std::string re = "re"; EXPECT_EQ("retail", a1.Perform(tuple<const std::string&>(re))); } // Tests that we can use ACTION*() to define actions overloaded on the // number of parameters. ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; } ACTION_P(OverloadedAction, default_value) { return arg0 ? arg1 : default_value; } ACTION_P2(OverloadedAction, true_value, false_value) { return arg0 ? true_value : false_value; } TEST(ActionMacroTest, CanDefineOverloadedActions) { typedef Action<const char*(bool, const char*)> MyAction; const MyAction a1 = OverloadedAction(); EXPECT_STREQ("hello", a1.Perform(make_tuple(false, CharPtr("world")))); EXPECT_STREQ("world", a1.Perform(make_tuple(true, CharPtr("world")))); const MyAction a2 = OverloadedAction("hi"); EXPECT_STREQ("hi", a2.Perform(make_tuple(false, CharPtr("world")))); EXPECT_STREQ("world", a2.Perform(make_tuple(true, CharPtr("world")))); const MyAction a3 = OverloadedAction("hi", "you"); EXPECT_STREQ("hi", a3.Perform(make_tuple(true, CharPtr("world")))); EXPECT_STREQ("you", a3.Perform(make_tuple(false, CharPtr("world")))); } // Tests ACTION_Pn where n >= 3. ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; } TEST(ActionPnMacroTest, WorksFor3Parameters) { Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4); EXPECT_DOUBLE_EQ(3123.4, a1.Perform(make_tuple(3000, true))); Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">"); const std::string re = "re"; EXPECT_EQ("retail->", a2.Perform(tuple<const std::string&>(re))); } ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; } TEST(ActionPnMacroTest, WorksFor4Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4); EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(make_tuple(10))); } ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; } TEST(ActionPnMacroTest, WorksFor5Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(make_tuple(10))); } ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5; } TEST(ActionPnMacroTest, WorksFor6Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(make_tuple(10))); } ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6; } TEST(ActionPnMacroTest, WorksFor7Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(make_tuple(10))); } ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7; } TEST(ActionPnMacroTest, WorksFor8Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, a1.Perform(make_tuple(10))); } ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8; } TEST(ActionPnMacroTest, WorksFor9Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, a1.Perform(make_tuple(10))); } ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) { arg0_type t0 = arg0; last_param_type t9 = last_param; return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9; } TEST(ActionPnMacroTest, WorksFor10Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, a1.Perform(make_tuple(10))); } // Tests that the action body can promote the parameter types. ACTION_P2(PadArgument, prefix, suffix) { // The following lines promote the two parameters to desired types. std::string prefix_str(prefix); char suffix_char = static_cast<char>(suffix); return prefix_str + arg0 + suffix_char; } TEST(ActionPnMacroTest, SimpleTypePromotion) { Action<std::string(const char*)> no_promo = PadArgument(std::string("foo"), 'r'); Action<std::string(const char*)> promo = PadArgument("foo", static_cast<int>('r')); EXPECT_EQ("foobar", no_promo.Perform(make_tuple(CharPtr("ba")))); EXPECT_EQ("foobar", promo.Perform(make_tuple(CharPtr("ba")))); } // Tests that we can partially restrict parameter types using a // straight-forward pattern. // Defines a generic action that doesn't restrict the types of its // parameters. ACTION_P3(ConcatImpl, a, b, c) { std::stringstream ss; ss << a << b << c; return ss.str(); } // Next, we try to restrict that either the first parameter is a // string, or the second parameter is an int. // Defines a partially specialized wrapper that restricts the first // parameter to std::string. template <typename T1, typename T2> // ConcatImplActionP3 is the class template ACTION_P3 uses to // implement ConcatImpl. We shouldn't change the name as this // pattern requires the user to use it directly. ConcatImplActionP3<std::string, T1, T2> Concat(const std::string& a, T1 b, T2 c) { GTEST_INTENTIONAL_CONST_COND_PUSH_() if (true) { GTEST_INTENTIONAL_CONST_COND_POP_() // This branch verifies that ConcatImpl() can be invoked without // explicit template arguments. return ConcatImpl(a, b, c); } else { // This branch verifies that ConcatImpl() can also be invoked with // explicit template arguments. It doesn't really need to be // executed as this is a compile-time verification. return ConcatImpl<std::string, T1, T2>(a, b, c); } } // Defines another partially specialized wrapper that restricts the // second parameter to int. template <typename T1, typename T2> ConcatImplActionP3<T1, int, T2> Concat(T1 a, int b, T2 c) { return ConcatImpl(a, b, c); } TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) { Action<const std::string()> a1 = Concat("Hello", "1", 2); EXPECT_EQ("Hello12", a1.Perform(make_tuple())); a1 = Concat(1, 2, 3); EXPECT_EQ("123", a1.Perform(make_tuple())); } // Verifies the type of an ACTION*. ACTION(DoFoo) {} ACTION_P(DoFoo, p) {} ACTION_P2(DoFoo, p0, p1) {} TEST(ActionPnMacroTest, TypesAreCorrect) { // DoFoo() must be assignable to a DoFooAction variable. DoFooAction a0 = DoFoo(); // DoFoo(1) must be assignable to a DoFooActionP variable. DoFooActionP<int> a1 = DoFoo(1); // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk // variable, and so on. DoFooActionP2<int, char> a2 = DoFoo(1, '2'); PlusActionP3<int, int, char> a3 = Plus(1, 2, '3'); PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4'); PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5'); PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6'); PlusActionP7<int, int, int, int, int, int, char> a7 = Plus(1, 2, 3, 4, 5, 6, '7'); PlusActionP8<int, int, int, int, int, int, int, char> a8 = Plus(1, 2, 3, 4, 5, 6, 7, '8'); PlusActionP9<int, int, int, int, int, int, int, int, char> a9 = Plus(1, 2, 3, 4, 5, 6, 7, 8, '9'); PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0'); // Avoid "unused variable" warnings. (void)a0; (void)a1; (void)a2; (void)a3; (void)a4; (void)a5; (void)a6; (void)a7; (void)a8; (void)a9; (void)a10; } // Tests that an ACTION_P*() action can be explicitly instantiated // with reference-typed parameters. ACTION_P(Plus1, x) { return x; } ACTION_P2(Plus2, x, y) { return x + y; } ACTION_P3(Plus3, x, y, z) { return x + y + z; } ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9; } TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) { int x = 1, y = 2, z = 3; const tuple<> empty = make_tuple(); Action<int()> a = Plus1<int&>(x); EXPECT_EQ(1, a.Perform(empty)); a = Plus2<const int&, int&>(x, y); EXPECT_EQ(3, a.Perform(empty)); a = Plus3<int&, const int&, int&>(x, y, z); EXPECT_EQ(6, a.Perform(empty)); int n[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&, int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9]); EXPECT_EQ(55, a.Perform(empty)); } class NullaryConstructorClass { public: NullaryConstructorClass() : value_(123) {} int value_; }; // Tests using ReturnNew() with a nullary constructor. TEST(ReturnNewTest, NoArgs) { Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>(); NullaryConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(123, c->value_); delete c; } class UnaryConstructorClass { public: explicit UnaryConstructorClass(int value) : value_(value) {} int value_; }; // Tests using ReturnNew() with a unary constructor. TEST(ReturnNewTest, Unary) { Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); UnaryConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { Action<UnaryConstructorClass*(bool, int)> a = ReturnNew<UnaryConstructorClass>(4000); UnaryConstructorClass* c = a.Perform(make_tuple(false, 5)); EXPECT_EQ(4000, c->value_); delete c; } TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) { Action<const UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); const UnaryConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } class TenArgConstructorClass { public: TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10) : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) { } int value_; }; // Tests using ReturnNew() with a 10-argument constructor. TEST(ReturnNewTest, ConstructorThatTakes10Arguments) { Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90, 0); TenArgConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(1234567890, c->value_); delete c; } // Tests that ACTION_TEMPLATE works when there is no value parameter. ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_0_VALUE_PARAMS()) { return new T; } TEST(ActionTemplateTest, WorksWithoutValueParam) { const Action<int*()> a = CreateNew<int>(); int* p = a.Perform(make_tuple()); delete p; } // Tests that ACTION_TEMPLATE works when there are value parameters. ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_1_VALUE_PARAMS(a0)) { return new T(a0); } TEST(ActionTemplateTest, WorksWithValueParams) { const Action<int*()> a = CreateNew<int>(42); int* p = a.Perform(make_tuple()); EXPECT_EQ(42, *p); delete p; } // Tests that ACTION_TEMPLATE works for integral template parameters. ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { delete get<k>(args); } // Resets a bool variable in the destructor. class BoolResetter { public: explicit BoolResetter(bool* value) : value_(value) {} ~BoolResetter() { *value_ = false; } private: bool* value_; }; TEST(ActionTemplateTest, WorksForIntegralTemplateParams) { const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>(); int n = 0; bool b = true; BoolResetter* resetter = new BoolResetter(&b); a.Perform(make_tuple(&n, resetter)); EXPECT_FALSE(b); // Verifies that resetter is deleted. } -// Tests that ACTION_TEMPLATES works for template template parameters. +// Tests that ACTION_TEMPLATE works for a template with template parameters. ACTION_TEMPLATE(ReturnSmartPointer, HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class, Pointer), AND_1_VALUE_PARAMS(pointee)) { return Pointer<pointee_type>(new pointee_type(pointee)); } TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) { using ::testing::internal::linked_ptr; const Action<linked_ptr<int>()> a = ReturnSmartPointer<linked_ptr>(42); linked_ptr<int> p = a.Perform(make_tuple()); EXPECT_EQ(42, *p); } // Tests that ACTION_TEMPLATE works for 10 template parameters. template <typename T1, typename T2, typename T3, int k4, bool k5, unsigned int k6, typename T7, typename T8, typename T9> struct GiantTemplate { public: explicit GiantTemplate(int a_value) : value(a_value) {} int value; }; ACTION_TEMPLATE(ReturnGiant, HAS_10_TEMPLATE_PARAMS( typename, T1, typename, T2, typename, T3, int, k4, bool, k5, unsigned int, k6, class, T7, class, T8, class, T9, template <typename T> class, T10), AND_1_VALUE_PARAMS(value)) { return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value); } TEST(ActionTemplateTest, WorksFor10TemplateParameters) { using ::testing::internal::linked_ptr; typedef GiantTemplate<linked_ptr<int>, bool, double, 5, true, 6, char, unsigned, int> Giant; const Action<Giant()> a = ReturnGiant< int, bool, double, 5, true, 6, char, unsigned, int, linked_ptr>(42); Giant giant = a.Perform(make_tuple()); EXPECT_EQ(42, giant.value); } // Tests that ACTION_TEMPLATE works for 10 value parameters. ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) { return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10; } TEST(ActionTemplateTest, WorksFor10ValueParameters) { const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(55, a.Perform(make_tuple())); } // Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded // on the number of value parameters. ACTION(ReturnSum) { return 0; } ACTION_P(ReturnSum, x) { return x; } ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_2_VALUE_PARAMS(v1, v2)) { return static_cast<Number>(v1) + v2; } ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_3_VALUE_PARAMS(v1, v2, v3)) { return static_cast<Number>(v1) + v2 + v3; } ACTION_TEMPLATE(ReturnSum, HAS_2_TEMPLATE_PARAMS(typename, Number, int, k), AND_4_VALUE_PARAMS(v1, v2, v3, v4)) { return static_cast<Number>(v1) + v2 + v3 + v4 + k; } TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) { const Action<int()> a0 = ReturnSum(); const Action<int()> a1 = ReturnSum(1); const Action<int()> a2 = ReturnSum<int>(1, 2); const Action<int()> a3 = ReturnSum<int>(1, 2, 3); const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5); EXPECT_EQ(0, a0.Perform(make_tuple())); EXPECT_EQ(1, a1.Perform(make_tuple())); EXPECT_EQ(3, a2.Perform(make_tuple())); EXPECT_EQ(6, a3.Perform(make_tuple())); EXPECT_EQ(12345, a4.Perform(make_tuple())); } #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace gmock_generated_actions_test } // namespace testing diff --git a/googlemock/test/gmock-nice-strict_test.cc b/googlemock/test/gmock-nice-strict_test.cc index 5d6ccc4f..0eac6439 100644 --- a/googlemock/test/gmock-nice-strict_test.cc +++ b/googlemock/test/gmock-nice-strict_test.cc @@ -1,423 +1,446 @@ // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) #include "gmock/gmock-generated-nice-strict.h" #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" // This must not be defined inside the ::testing namespace, or it will // clash with ::testing::Mock. class Mock { public: Mock() {} MOCK_METHOD0(DoThis, void()); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mock); }; namespace testing { namespace gmock_nice_strict_test { using testing::GMOCK_FLAG(verbose); using testing::HasSubstr; using testing::NaggyMock; using testing::NiceMock; using testing::StrictMock; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif +// Class without default constructor. +class NotDefaultConstructible { + public: + explicit NotDefaultConstructible(int) {} +}; + // Defines some mock classes needed by the tests. class Foo { public: virtual ~Foo() {} virtual void DoThis() = 0; virtual int DoThat(bool flag) = 0; }; class MockFoo : public Foo { public: MockFoo() {} void Delete() { delete this; } MOCK_METHOD0(DoThis, void()); MOCK_METHOD1(DoThat, int(bool flag)); + MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible()); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFoo); }; class MockBar { public: explicit MockBar(const std::string& s) : str_(s) {} MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6, const std::string& a7, const std::string& a8, bool a9, bool a10) { str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) + static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') + (a10 ? 'T' : 'F'); } virtual ~MockBar() {} const std::string& str() const { return str_; } MOCK_METHOD0(This, int()); MOCK_METHOD2(That, std::string(int, bool)); private: std::string str_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MockBar); }; #if GTEST_HAS_STREAM_REDIRECTION // Tests that a raw mock generates warnings for uninteresting calls. TEST(RawMockTest, WarningForUninterestingCall) { const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; MockFoo raw_foo; CaptureStdout(); raw_foo.DoThis(); raw_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG(verbose) = saved_flag; } // Tests that a raw mock generates warnings for uninteresting calls // that delete the mock object. TEST(RawMockTest, WarningForUninterestingCallAfterDeath) { const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; MockFoo* const raw_foo = new MockFoo; ON_CALL(*raw_foo, DoThis()) .WillByDefault(Invoke(raw_foo, &MockFoo::Delete)); CaptureStdout(); raw_foo->DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG(verbose) = saved_flag; } // Tests that a raw mock generates informational logs for // uninteresting calls. TEST(RawMockTest, InfoForUninterestingCall) { MockFoo raw_foo; const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); raw_foo.DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG(verbose) = saved_flag; } // Tests that a nice mock generates no warning for uninteresting calls. TEST(NiceMockTest, NoWarningForUninterestingCall) { NiceMock<MockFoo> nice_foo; CaptureStdout(); nice_foo.DoThis(); nice_foo.DoThat(true); EXPECT_EQ("", GetCapturedStdout()); } // Tests that a nice mock generates no warning for uninteresting calls // that delete the mock object. TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { NiceMock<MockFoo>* const nice_foo = new NiceMock<MockFoo>; ON_CALL(*nice_foo, DoThis()) .WillByDefault(Invoke(nice_foo, &MockFoo::Delete)); CaptureStdout(); nice_foo->DoThis(); EXPECT_EQ("", GetCapturedStdout()); } // Tests that a nice mock generates informational logs for // uninteresting calls. TEST(NiceMockTest, InfoForUninterestingCall) { NiceMock<MockFoo> nice_foo; const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); nice_foo.DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG(verbose) = saved_flag; } #endif // GTEST_HAS_STREAM_REDIRECTION // Tests that a nice mock allows expected calls. TEST(NiceMockTest, AllowsExpectedCall) { NiceMock<MockFoo> nice_foo; EXPECT_CALL(nice_foo, DoThis()); nice_foo.DoThis(); } +// Tests that an unexpected call on a nice mock which returns a not-default-constructible +// type throws an exception and the exception contains the method's name. +TEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) { + NiceMock<MockFoo> nice_foo; +#if GTEST_HAS_EXCEPTIONS + try { + nice_foo.ReturnNonDefaultConstructible(); + FAIL(); + } catch (const std::runtime_error& ex) { + EXPECT_THAT(ex.what(), HasSubstr("ReturnNonDefaultConstructible")); + } +#else + EXPECT_DEATH_IF_SUPPORTED({ nice_foo.ReturnNonDefaultConstructible(); }, ""); +#endif +} + // Tests that an unexpected call on a nice mock fails. TEST(NiceMockTest, UnexpectedCallFails) { NiceMock<MockFoo> nice_foo; EXPECT_CALL(nice_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(nice_foo.DoThis(), "called more times than expected"); } // Tests that NiceMock works with a mock class that has a non-default // constructor. TEST(NiceMockTest, NonDefaultConstructor) { NiceMock<MockBar> nice_bar("hi"); EXPECT_EQ("hi", nice_bar.str()); nice_bar.This(); nice_bar.That(5, true); } // Tests that NiceMock works with a mock class that has a 10-ary // non-default constructor. TEST(NiceMockTest, NonDefaultConstructor10) { NiceMock<MockBar> nice_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, false); EXPECT_EQ("abcdefghTF", nice_bar.str()); nice_bar.This(); nice_bar.That(5, true); } #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NiceMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an // MSVC 8.0 bug that caused the symbol Mock used in the definition of // NiceMock to be looked up in the wrong context, and this test // ensures that our fix works. // // We have to skip this test on Symbian and Windows Mobile, as it // causes the program to crash there, for reasons unclear to us yet. TEST(NiceMockTest, AcceptsClassNamedMock) { NiceMock< ::Mock> nice; EXPECT_CALL(nice, DoThis()); nice.DoThis(); } #endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE #if GTEST_HAS_STREAM_REDIRECTION // Tests that a naggy mock generates warnings for uninteresting calls. TEST(NaggyMockTest, WarningForUninterestingCall) { const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; NaggyMock<MockFoo> naggy_foo; CaptureStdout(); naggy_foo.DoThis(); naggy_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG(verbose) = saved_flag; } // Tests that a naggy mock generates a warning for an uninteresting call // that deletes the mock object. TEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) { const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "warning"; NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>; ON_CALL(*naggy_foo, DoThis()) .WillByDefault(Invoke(naggy_foo, &MockFoo::Delete)); CaptureStdout(); naggy_foo->DoThis(); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); GMOCK_FLAG(verbose) = saved_flag; } #endif // GTEST_HAS_STREAM_REDIRECTION // Tests that a naggy mock allows expected calls. TEST(NaggyMockTest, AllowsExpectedCall) { NaggyMock<MockFoo> naggy_foo; EXPECT_CALL(naggy_foo, DoThis()); naggy_foo.DoThis(); } // Tests that an unexpected call on a naggy mock fails. TEST(NaggyMockTest, UnexpectedCallFails) { NaggyMock<MockFoo> naggy_foo; EXPECT_CALL(naggy_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(naggy_foo.DoThis(), "called more times than expected"); } // Tests that NaggyMock works with a mock class that has a non-default // constructor. TEST(NaggyMockTest, NonDefaultConstructor) { NaggyMock<MockBar> naggy_bar("hi"); EXPECT_EQ("hi", naggy_bar.str()); naggy_bar.This(); naggy_bar.That(5, true); } // Tests that NaggyMock works with a mock class that has a 10-ary // non-default constructor. TEST(NaggyMockTest, NonDefaultConstructor10) { NaggyMock<MockBar> naggy_bar('0', '1', "2", "3", '4', '5', "6", "7", true, false); EXPECT_EQ("01234567TF", naggy_bar.str()); naggy_bar.This(); naggy_bar.That(5, true); } #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that NaggyMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an // MSVC 8.0 bug that caused the symbol Mock used in the definition of // NaggyMock to be looked up in the wrong context, and this test // ensures that our fix works. // // We have to skip this test on Symbian and Windows Mobile, as it // causes the program to crash there, for reasons unclear to us yet. TEST(NaggyMockTest, AcceptsClassNamedMock) { NaggyMock< ::Mock> naggy; EXPECT_CALL(naggy, DoThis()); naggy.DoThis(); } #endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that a strict mock allows expected calls. TEST(StrictMockTest, AllowsExpectedCall) { StrictMock<MockFoo> strict_foo; EXPECT_CALL(strict_foo, DoThis()); strict_foo.DoThis(); } // Tests that an unexpected call on a strict mock fails. TEST(StrictMockTest, UnexpectedCallFails) { StrictMock<MockFoo> strict_foo; EXPECT_CALL(strict_foo, DoThis()).Times(0); EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(), "called more times than expected"); } // Tests that an uninteresting call on a strict mock fails. TEST(StrictMockTest, UninterestingCallFails) { StrictMock<MockFoo> strict_foo; EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(), "Uninteresting mock function call"); } // Tests that an uninteresting call on a strict mock fails, even if // the call deletes the mock object. TEST(StrictMockTest, UninterestingCallFailsAfterDeath) { StrictMock<MockFoo>* const strict_foo = new StrictMock<MockFoo>; ON_CALL(*strict_foo, DoThis()) .WillByDefault(Invoke(strict_foo, &MockFoo::Delete)); EXPECT_NONFATAL_FAILURE(strict_foo->DoThis(), "Uninteresting mock function call"); } // Tests that StrictMock works with a mock class that has a // non-default constructor. TEST(StrictMockTest, NonDefaultConstructor) { StrictMock<MockBar> strict_bar("hi"); EXPECT_EQ("hi", strict_bar.str()); EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), "Uninteresting mock function call"); } // Tests that StrictMock works with a mock class that has a 10-ary // non-default constructor. TEST(StrictMockTest, NonDefaultConstructor10) { StrictMock<MockBar> strict_bar('a', 'b', "c", "d", 'e', 'f', "g", "h", true, false); EXPECT_EQ("abcdefghTF", strict_bar.str()); EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true), "Uninteresting mock function call"); } #if !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE // Tests that StrictMock<Mock> compiles where Mock is a user-defined // class (as opposed to ::testing::Mock). We had to work around an // MSVC 8.0 bug that caused the symbol Mock used in the definition of // StrictMock to be looked up in the wrong context, and this test // ensures that our fix works. // // We have to skip this test on Symbian and Windows Mobile, as it // causes the program to crash there, for reasons unclear to us yet. TEST(StrictMockTest, AcceptsClassNamedMock) { StrictMock< ::Mock> strict; EXPECT_CALL(strict, DoThis()); strict.DoThis(); } #endif // !GTEST_OS_SYMBIAN && !GTEST_OS_WINDOWS_MOBILE } // namespace gmock_nice_strict_test } // namespace testing diff --git a/googletest/CMakeLists.txt b/googletest/CMakeLists.txt index 36d0a9ec..59343ed2 100644 --- a/googletest/CMakeLists.txt +++ b/googletest/CMakeLists.txt @@ -1,286 +1,311 @@ ######################################################################## # CMake build script for Google Test. # # To run the tests for Google Test itself on Linux, use 'make test' or # ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to # make it prominent in the GUI. option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) # When other libraries are using a shared version of runtime libraries, # Google Test also has to use one. option( gtest_force_shared_crt "Use shared (DLL) run-time lib even when Google Test is built as static lib." OFF) option(gtest_build_tests "Build all of gtest's own tests." OFF) option(gtest_build_samples "Build gtest's sample programs." OFF) option(gtest_disable_pthreads "Disable uses of pthreads in gtest." OFF) option( gtest_hide_internal_symbols "Build gtest with internal symbols hidden in shared libraries." OFF) # Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). include(cmake/hermetic_build.cmake OPTIONAL) if (COMMAND pre_project_set_up_hermetic_build) pre_project_set_up_hermetic_build() endif() ######################################################################## # # Project-wide settings # Name of the project. # # CMake files in this project can refer to the root source directory # as ${gtest_SOURCE_DIR} and to the root binary directory as # ${gtest_BINARY_DIR}. # Language "C" is required for find_package(Threads). -project(gtest CXX C) +if (CMAKE_VERSION VERSION_LESS 3.0) + project(gtest CXX C) +else() + cmake_policy(SET CMP0048 NEW) + project(gtest VERSION 1.9.0 LANGUAGES CXX C) +endif() cmake_minimum_required(VERSION 2.6.4) +if (POLICY CMP0063) # Visibility + cmake_policy(SET CMP0063 NEW) +endif (POLICY CMP0063) + if (COMMAND set_up_hermetic_build) set_up_hermetic_build() endif() if (gtest_hide_internal_symbols) set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN 1) endif() # Define helper functions and macros used by Google Test. include(cmake/internal_utils.cmake) config_compiler_and_linker() # Defined in internal_utils.cmake. # Where Google Test's .h files can be found. include_directories( ${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR}) # Where Google Test's libraries can be found. link_directories(${gtest_BINARY_DIR}/src) # Summary of tuple support for Microsoft Visual Studio: # Compiler version(MS) version(cmake) Support # ---------- ----------- -------------- ----------------------------- # <= VS 2010 <= 10 <= 1600 Use Google Tests's own tuple. # VS 2012 11 1700 std::tr1::tuple + _VARIADIC_MAX=10 # VS 2013 12 1800 std::tr1::tuple if (MSVC AND MSVC_VERSION EQUAL 1700) add_definitions(/D _VARIADIC_MAX=10) endif() ######################################################################## # # Defines the gtest & gtest_main libraries. User tests should link # with one of them. # Google Test libraries. We build them using more strict warnings than what # are used for other targets, to ensure that gtest can be compiled by a user # aggressive about warnings. cxx_library(gtest "${cxx_strict}" src/gtest-all.cc) cxx_library(gtest_main "${cxx_strict}" src/gtest_main.cc) target_link_libraries(gtest_main gtest) # If the CMake version supports it, attach header directory information # to the targets for when we are part of a parent build (ie being pulled # in via add_subdirectory() rather than being a standalone build). if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") target_include_directories(gtest INTERFACE "${gtest_SOURCE_DIR}/include") target_include_directories(gtest_main INTERFACE "${gtest_SOURCE_DIR}/include") endif() ######################################################################## # # Install rules -install(TARGETS gtest gtest_main - DESTINATION lib) -install(DIRECTORY ${gtest_SOURCE_DIR}/include/gtest - DESTINATION include) +if(INSTALL_GTEST) + install(TARGETS gtest gtest_main + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + install(DIRECTORY ${gtest_SOURCE_DIR}/include/gtest + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + + # configure and install pkgconfig files + configure_file( + cmake/gtest.pc.in + "${CMAKE_BINARY_DIR}/gtest.pc" + @ONLY) + configure_file( + cmake/gtest_main.pc.in + "${CMAKE_BINARY_DIR}/gtest_main.pc" + @ONLY) + install(FILES "${CMAKE_BINARY_DIR}/gtest.pc" "${CMAKE_BINARY_DIR}/gtest_main.pc" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") +endif() ######################################################################## # # Samples on how to link user tests with gtest or gtest_main. # # They are not built by default. To build them, set the # gtest_build_samples option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_samples=ON flag when running cmake. if (gtest_build_samples) cxx_executable(sample1_unittest samples gtest_main samples/sample1.cc) cxx_executable(sample2_unittest samples gtest_main samples/sample2.cc) cxx_executable(sample3_unittest samples gtest_main) cxx_executable(sample4_unittest samples gtest_main samples/sample4.cc) cxx_executable(sample5_unittest samples gtest_main samples/sample1.cc) cxx_executable(sample6_unittest samples gtest_main) cxx_executable(sample7_unittest samples gtest_main) cxx_executable(sample8_unittest samples gtest_main) cxx_executable(sample9_unittest samples gtest) cxx_executable(sample10_unittest samples gtest) endif() ######################################################################## # # Google Test's own tests. # # You can skip this section if you aren't interested in testing # Google Test itself. # # The tests are not built by default. To build them, set the # gtest_build_tests option to ON. You can do it by running ccmake # or specifying the -Dgtest_build_tests=ON flag when running cmake. if (gtest_build_tests) # This must be set in the root directory for the tests to be run by # 'make test' or ctest. enable_testing() ############################################################ # C++ tests built with standard compiler flags. cxx_test(gtest-death-test_test gtest_main) cxx_test(gtest_environment_test gtest) cxx_test(gtest-filepath_test gtest_main) cxx_test(gtest-linked_ptr_test gtest_main) cxx_test(gtest-listener_test gtest_main) cxx_test(gtest_main_unittest gtest_main) cxx_test(gtest-message_test gtest_main) cxx_test(gtest_no_test_unittest gtest) cxx_test(gtest-options_test gtest_main) cxx_test(gtest-param-test_test gtest test/gtest-param-test2_test.cc) cxx_test(gtest-port_test gtest_main) cxx_test(gtest_pred_impl_unittest gtest_main) cxx_test(gtest_premature_exit_test gtest test/gtest_premature_exit_test.cc) cxx_test(gtest-printers_test gtest_main) cxx_test(gtest_prod_test gtest_main test/production.cc) cxx_test(gtest_repeat_test gtest) cxx_test(gtest_sole_header_test gtest_main) cxx_test(gtest_stress_test gtest) cxx_test(gtest-test-part_test gtest_main) cxx_test(gtest_throw_on_failure_ex_test gtest) cxx_test(gtest-typed-test_test gtest_main test/gtest-typed-test2_test.cc) cxx_test(gtest_unittest gtest_main) cxx_test(gtest-unittest-api_test gtest) ############################################################ # C++ tests built with non-standard compiler flags. # MSVC 7.1 does not support STL with exceptions disabled. if (NOT MSVC OR MSVC_VERSION GREATER 1310) cxx_library(gtest_no_exception "${cxx_no_exception}" src/gtest-all.cc) cxx_library(gtest_main_no_exception "${cxx_no_exception}" src/gtest-all.cc src/gtest_main.cc) endif() cxx_library(gtest_main_no_rtti "${cxx_no_rtti}" src/gtest-all.cc src/gtest_main.cc) cxx_test_with_flags(gtest-death-test_ex_nocatch_test "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0" gtest test/gtest-death-test_ex_test.cc) cxx_test_with_flags(gtest-death-test_ex_catch_test "${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1" gtest test/gtest-death-test_ex_test.cc) cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}" gtest_main_no_rtti test/gtest_unittest.cc) cxx_shared_library(gtest_dll "${cxx_default}" src/gtest-all.cc src/gtest_main.cc) cxx_executable_with_flags(gtest_dll_test_ "${cxx_default}" gtest_dll test/gtest_all_test.cc) set_target_properties(gtest_dll_test_ PROPERTIES COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") if (NOT MSVC OR MSVC_VERSION LESS 1600) # 1600 is Visual Studio 2010. # Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that # conflict with our own definitions. Therefore using our own tuple does not # work on those compilers. cxx_library(gtest_main_use_own_tuple "${cxx_use_own_tuple}" src/gtest-all.cc src/gtest_main.cc) cxx_test_with_flags(gtest-tuple_test "${cxx_use_own_tuple}" gtest_main_use_own_tuple test/gtest-tuple_test.cc) cxx_test_with_flags(gtest_use_own_tuple_test "${cxx_use_own_tuple}" gtest_main_use_own_tuple test/gtest-param-test_test.cc test/gtest-param-test2_test.cc) endif() ############################################################ # Python tests. cxx_executable(gtest_break_on_failure_unittest_ test gtest) py_test(gtest_break_on_failure_unittest) # Visual Studio .NET 2003 does not support STL with exceptions disabled. if (NOT MSVC OR MSVC_VERSION GREATER 1310) # 1310 is Visual Studio .NET 2003 cxx_executable_with_flags( gtest_catch_exceptions_no_ex_test_ "${cxx_no_exception}" gtest_main_no_exception test/gtest_catch_exceptions_test_.cc) endif() cxx_executable_with_flags( gtest_catch_exceptions_ex_test_ "${cxx_exception}" gtest_main test/gtest_catch_exceptions_test_.cc) py_test(gtest_catch_exceptions_test) cxx_executable(gtest_color_test_ test gtest) py_test(gtest_color_test) cxx_executable(gtest_env_var_test_ test gtest) py_test(gtest_env_var_test) cxx_executable(gtest_filter_unittest_ test gtest) py_test(gtest_filter_unittest) cxx_executable(gtest_help_test_ test gtest_main) py_test(gtest_help_test) cxx_executable(gtest_list_tests_unittest_ test gtest) py_test(gtest_list_tests_unittest) cxx_executable(gtest_output_test_ test gtest) py_test(gtest_output_test) cxx_executable(gtest_shuffle_test_ test gtest) py_test(gtest_shuffle_test) # MSVC 7.1 does not support STL with exceptions disabled. if (NOT MSVC OR MSVC_VERSION GREATER 1310) cxx_executable(gtest_throw_on_failure_test_ test gtest_no_exception) set_target_properties(gtest_throw_on_failure_test_ PROPERTIES COMPILE_FLAGS "${cxx_no_exception}") py_test(gtest_throw_on_failure_test) endif() cxx_executable(gtest_uninitialized_test_ test gtest) py_test(gtest_uninitialized_test) cxx_executable(gtest_xml_outfile1_test_ test gtest_main) cxx_executable(gtest_xml_outfile2_test_ test gtest_main) py_test(gtest_xml_outfiles_test) cxx_executable(gtest_xml_output_unittest_ test gtest) py_test(gtest_xml_output_unittest) endif() diff --git a/googletest/Makefile.am b/googletest/Makefile.am index 29797e4e..dbc004de 100644 --- a/googletest/Makefile.am +++ b/googletest/Makefile.am @@ -1,310 +1,310 @@ # Automake file ACLOCAL_AMFLAGS = -I m4 # Nonstandard package files for distribution EXTRA_DIST = \ CHANGES \ CONTRIBUTORS \ LICENSE \ include/gtest/gtest-param-test.h.pump \ include/gtest/internal/gtest-param-util-generated.h.pump \ include/gtest/internal/gtest-tuple.h.pump \ include/gtest/internal/gtest-type-util.h.pump \ make/Makefile \ scripts/fuse_gtest_files.py \ scripts/gen_gtest_pred_impl.py \ scripts/pump.py \ scripts/test/Makefile # gtest source files that we don't compile directly. They are # #included by gtest-all.cc. GTEST_SRC = \ src/gtest-death-test.cc \ src/gtest-filepath.cc \ src/gtest-internal-inl.h \ src/gtest-port.cc \ src/gtest-printers.cc \ src/gtest-test-part.cc \ src/gtest-typed-test.cc \ src/gtest.cc EXTRA_DIST += $(GTEST_SRC) # Sample files that we don't compile. EXTRA_DIST += \ samples/prime_tables.h \ samples/sample2_unittest.cc \ samples/sample3_unittest.cc \ samples/sample4_unittest.cc \ samples/sample5_unittest.cc \ samples/sample6_unittest.cc \ samples/sample7_unittest.cc \ samples/sample8_unittest.cc \ samples/sample9_unittest.cc # C++ test files that we don't compile directly. EXTRA_DIST += \ test/gtest-death-test_ex_test.cc \ test/gtest-death-test_test.cc \ test/gtest-filepath_test.cc \ test/gtest-linked_ptr_test.cc \ test/gtest-listener_test.cc \ test/gtest-message_test.cc \ test/gtest-options_test.cc \ test/gtest-param-test2_test.cc \ test/gtest-param-test2_test.cc \ test/gtest-param-test_test.cc \ test/gtest-param-test_test.cc \ test/gtest-param-test_test.h \ test/gtest-port_test.cc \ test/gtest_premature_exit_test.cc \ test/gtest-printers_test.cc \ test/gtest-test-part_test.cc \ test/gtest-tuple_test.cc \ test/gtest-typed-test2_test.cc \ test/gtest-typed-test_test.cc \ test/gtest-typed-test_test.h \ test/gtest-unittest-api_test.cc \ test/gtest_break_on_failure_unittest_.cc \ test/gtest_catch_exceptions_test_.cc \ test/gtest_color_test_.cc \ test/gtest_env_var_test_.cc \ test/gtest_environment_test.cc \ test/gtest_filter_unittest_.cc \ test/gtest_help_test_.cc \ test/gtest_list_tests_unittest_.cc \ test/gtest_main_unittest.cc \ test/gtest_no_test_unittest.cc \ test/gtest_output_test_.cc \ test/gtest_pred_impl_unittest.cc \ test/gtest_prod_test.cc \ test/gtest_repeat_test.cc \ test/gtest_shuffle_test_.cc \ test/gtest_sole_header_test.cc \ test/gtest_stress_test.cc \ test/gtest_throw_on_failure_ex_test.cc \ test/gtest_throw_on_failure_test_.cc \ test/gtest_uninitialized_test_.cc \ test/gtest_unittest.cc \ test/gtest_unittest.cc \ test/gtest_xml_outfile1_test_.cc \ test/gtest_xml_outfile2_test_.cc \ test/gtest_xml_output_unittest_.cc \ test/production.cc \ test/production.h # Python tests that we don't run. EXTRA_DIST += \ test/gtest_break_on_failure_unittest.py \ test/gtest_catch_exceptions_test.py \ test/gtest_color_test.py \ test/gtest_env_var_test.py \ test/gtest_filter_unittest.py \ test/gtest_help_test.py \ test/gtest_list_tests_unittest.py \ test/gtest_output_test.py \ test/gtest_output_test_golden_lin.txt \ test/gtest_shuffle_test.py \ test/gtest_test_utils.py \ test/gtest_throw_on_failure_test.py \ test/gtest_uninitialized_test.py \ test/gtest_xml_outfiles_test.py \ test/gtest_xml_output_unittest.py \ test/gtest_xml_test_utils.py # CMake script EXTRA_DIST += \ CMakeLists.txt \ cmake/internal_utils.cmake # MSVC project files EXTRA_DIST += \ msvc/gtest-md.sln \ msvc/gtest-md.vcproj \ msvc/gtest.sln \ msvc/gtest.vcproj \ msvc/gtest_main-md.vcproj \ msvc/gtest_main.vcproj \ msvc/gtest_prod_test-md.vcproj \ msvc/gtest_prod_test.vcproj \ msvc/gtest_unittest-md.vcproj \ msvc/gtest_unittest.vcproj # xcode project files EXTRA_DIST += \ xcode/Config/DebugProject.xcconfig \ xcode/Config/FrameworkTarget.xcconfig \ xcode/Config/General.xcconfig \ xcode/Config/ReleaseProject.xcconfig \ xcode/Config/StaticLibraryTarget.xcconfig \ xcode/Config/TestTarget.xcconfig \ xcode/Resources/Info.plist \ xcode/Scripts/runtests.sh \ xcode/Scripts/versiongenerate.py \ xcode/gtest.xcodeproj/project.pbxproj # xcode sample files EXTRA_DIST += \ xcode/Samples/FrameworkSample/Info.plist \ xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj \ xcode/Samples/FrameworkSample/runtests.sh \ xcode/Samples/FrameworkSample/widget.cc \ xcode/Samples/FrameworkSample/widget.h \ xcode/Samples/FrameworkSample/widget_test.cc # C++Builder project files EXTRA_DIST += \ codegear/gtest.cbproj \ codegear/gtest.groupproj \ codegear/gtest_all.cc \ codegear/gtest_link.cc \ codegear/gtest_main.cbproj \ codegear/gtest_unittest.cbproj # Distribute and install M4 macro m4datadir = $(datadir)/aclocal m4data_DATA = m4/gtest.m4 EXTRA_DIST += $(m4data_DATA) # We define the global AM_CPPFLAGS as everything we compile includes from these # directories. AM_CPPFLAGS = -I$(srcdir) -I$(srcdir)/include # Modifies compiler and linker flags for pthreads compatibility. if HAVE_PTHREADS AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1 AM_LIBS = @PTHREAD_LIBS@ else AM_CXXFLAGS = -DGTEST_HAS_PTHREAD=0 endif # Build rules for libraries. lib_LTLIBRARIES = lib/libgtest.la lib/libgtest_main.la lib_libgtest_la_SOURCES = src/gtest-all.cc pkginclude_HEADERS = \ include/gtest/gtest-death-test.h \ include/gtest/gtest-message.h \ include/gtest/gtest-param-test.h \ include/gtest/gtest-printers.h \ include/gtest/gtest-spi.h \ include/gtest/gtest-test-part.h \ include/gtest/gtest-typed-test.h \ include/gtest/gtest.h \ include/gtest/gtest_pred_impl.h \ include/gtest/gtest_prod.h pkginclude_internaldir = $(pkgincludedir)/internal pkginclude_internal_HEADERS = \ include/gtest/internal/gtest-death-test-internal.h \ include/gtest/internal/gtest-filepath.h \ include/gtest/internal/gtest-internal.h \ include/gtest/internal/gtest-linked_ptr.h \ include/gtest/internal/gtest-param-util-generated.h \ include/gtest/internal/gtest-param-util.h \ include/gtest/internal/gtest-port.h \ include/gtest/internal/gtest-port-arch.h \ include/gtest/internal/gtest-string.h \ include/gtest/internal/gtest-tuple.h \ include/gtest/internal/gtest-type-util.h \ include/gtest/internal/custom/gtest.h \ include/gtest/internal/custom/gtest-port.h \ include/gtest/internal/custom/gtest-printers.h lib_libgtest_main_la_SOURCES = src/gtest_main.cc lib_libgtest_main_la_LIBADD = lib/libgtest.la -# Bulid rules for samples and tests. Automake's naming for some of +# Build rules for samples and tests. Automake's naming for some of # these variables isn't terribly obvious, so this is a brief # reference: # # TESTS -- Programs run automatically by "make check" # check_PROGRAMS -- Programs built by "make check" but not necessarily run noinst_LTLIBRARIES = samples/libsamples.la samples_libsamples_la_SOURCES = \ samples/sample1.cc \ samples/sample1.h \ samples/sample2.cc \ samples/sample2.h \ samples/sample3-inl.h \ samples/sample4.cc \ samples/sample4.h TESTS= TESTS_ENVIRONMENT = GTEST_SOURCE_DIR="$(srcdir)/test" \ GTEST_BUILD_DIR="$(top_builddir)/test" check_PROGRAMS= # A simple sample on using gtest. TESTS += samples/sample1_unittest check_PROGRAMS += samples/sample1_unittest samples_sample1_unittest_SOURCES = samples/sample1_unittest.cc samples_sample1_unittest_LDADD = lib/libgtest_main.la \ lib/libgtest.la \ samples/libsamples.la # Another sample. It also verifies that libgtest works. TESTS += samples/sample10_unittest check_PROGRAMS += samples/sample10_unittest samples_sample10_unittest_SOURCES = samples/sample10_unittest.cc samples_sample10_unittest_LDADD = lib/libgtest.la # This tests most constructs of gtest and verifies that libgtest_main # and libgtest work. TESTS += test/gtest_all_test check_PROGRAMS += test/gtest_all_test test_gtest_all_test_SOURCES = test/gtest_all_test.cc test_gtest_all_test_LDADD = lib/libgtest_main.la \ lib/libgtest.la # Tests that fused gtest files compile and work. FUSED_GTEST_SRC = \ fused-src/gtest/gtest-all.cc \ fused-src/gtest/gtest.h \ fused-src/gtest/gtest_main.cc if HAVE_PYTHON TESTS += test/fused_gtest_test check_PROGRAMS += test/fused_gtest_test test_fused_gtest_test_SOURCES = $(FUSED_GTEST_SRC) \ samples/sample1.cc samples/sample1_unittest.cc test_fused_gtest_test_CPPFLAGS = -I"$(srcdir)/fused-src" # Build rules for putting fused Google Test files into the distribution # package. The user can also create those files by manually running # scripts/fuse_gtest_files.py. $(test_fused_gtest_test_SOURCES): fused-gtest fused-gtest: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \ $(GTEST_SRC) src/gtest-all.cc src/gtest_main.cc \ scripts/fuse_gtest_files.py mkdir -p "$(srcdir)/fused-src" chmod -R u+w "$(srcdir)/fused-src" rm -f "$(srcdir)/fused-src/gtest/gtest-all.cc" rm -f "$(srcdir)/fused-src/gtest/gtest.h" "$(srcdir)/scripts/fuse_gtest_files.py" "$(srcdir)/fused-src" cp -f "$(srcdir)/src/gtest_main.cc" "$(srcdir)/fused-src/gtest/" maintainer-clean-local: rm -rf "$(srcdir)/fused-src" endif # Death tests may produce core dumps in the build directory. In case # this happens, clean them to keep distcleancheck happy. CLEANFILES = core # Disables 'make install' as installing a compiled version of Google # Test can lead to undefined behavior due to violation of the # One-Definition Rule. install-exec-local: echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system." false install-data-local: echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Test into your build system." false diff --git a/googletest/cmake/gtest.pc.in b/googletest/cmake/gtest.pc.in new file mode 100644 index 00000000..e7967ad5 --- /dev/null +++ b/googletest/cmake/gtest.pc.in @@ -0,0 +1,9 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gtest +Description: GoogleTest (without main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Libs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/googletest/cmake/gtest_main.pc.in b/googletest/cmake/gtest_main.pc.in new file mode 100644 index 00000000..fe25d9c7 --- /dev/null +++ b/googletest/cmake/gtest_main.pc.in @@ -0,0 +1,10 @@ +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: gtest_main +Description: GoogleTest (with main() function) +Version: @PROJECT_VERSION@ +URL: https://github.com/google/googletest +Requires: gtest +Libs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@ +Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/googletest/cmake/internal_utils.cmake b/googletest/cmake/internal_utils.cmake index 8878dc1a..f0f54d02 100644 --- a/googletest/cmake/internal_utils.cmake +++ b/googletest/cmake/internal_utils.cmake @@ -1,256 +1,258 @@ # Defines functions and macros useful for building Google Test and # Google Mock. # # Note: # # - This file will be run twice when building Google Mock (once via # Google Test's CMakeLists.txt, and once via Google Mock's). # Therefore it shouldn't have any side effects other than defining # the functions and macros. # # - The functions/macros defined in this file may depend on Google # Test and Google Mock's option() definitions, and thus must be # called *after* the options have been defined. # Tweaks CMake's default compiler/linker settings to suit Google Test's needs. # # This must be a macro(), as inside a function string() can only # update variables in the function scope. 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. foreach (flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt) # When Google Test is built as a shared library, it should also use # shared runtime libraries. Otherwise, it may end up with multiple # copies of runtime library data in different modules, resulting in # hard-to-find crashes. When it is built as a static library, it is # preferable to use CRT as static libraries, as we don't have to rely # on CRT DLLs being available. CMake always defaults to using shared # CRT libraries, so we override that default here. string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}") endif() # We prefer more strict warning checking for building Google Test. # Replaces /W3 with /W4 in defaults. string(REPLACE "/W3" "/W4" ${flag_var} "${${flag_var}}") endforeach() endif() endmacro() # Defines the compiler/linker flags used to build Google Test and # Google Mock. You can tweak these definitions to suit your need. A # variable's value is empty before it's explicitly assigned to. macro(config_compiler_and_linker) # Note: pthreads on MinGW is not supported, even if available # instead, we use windows threading primitives if (NOT gtest_disable_pthreads AND NOT MINGW) # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. + set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads) endif() fix_default_compiler_settings_() if (MSVC) # Newlines inside flags variables break CMake's NMake generator. # TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds. set(cxx_base_flags "-GS -W4 -WX -wd4251 -wd4275 -nologo -J -Zi") if (MSVC_VERSION LESS 1400) # 1400 is Visual Studio 2005 # Suppress spurious warnings MSVC 7.1 sometimes issues. # Forcing value to bool. set(cxx_base_flags "${cxx_base_flags} -wd4800") # Copy constructor and assignment operator could not be generated. set(cxx_base_flags "${cxx_base_flags} -wd4511 -wd4512") # Compatibility warnings not applicable to Google Test. # Resolved overload was found by argument-dependent lookup. set(cxx_base_flags "${cxx_base_flags} -wd4675") endif() if (MSVC_VERSION LESS 1500) # 1500 is Visual Studio 2008 # Conditional expression is constant. # When compiling with /W4, we get several instances of C4127 # (Conditional expression is constant). In our code, we disable that # warning on a case-by-case basis. However, on Visual Studio 2005, # the warning fires on std::list. Therefore on that compiler and earlier, # we disable the warning project-wide. set(cxx_base_flags "${cxx_base_flags} -wd4127") endif() if (NOT (MSVC_VERSION LESS 1700)) # 1700 is Visual Studio 2012. # Suppress "unreachable code" warning on VS 2012 and later. # http://stackoverflow.com/questions/3232669 explains the issue. set(cxx_base_flags "${cxx_base_flags} -wd4702") endif() if (NOT (MSVC_VERSION GREATER 1900)) # 1900 is Visual Studio 2015 # BigObj required for tests. set(cxx_base_flags "${cxx_base_flags} -bigobj") endif() set(cxx_base_flags "${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32") set(cxx_base_flags "${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN") set(cxx_exception_flags "-EHsc -D_HAS_EXCEPTIONS=1") set(cxx_no_exception_flags "-D_HAS_EXCEPTIONS=0") set(cxx_no_rtti_flags "-GR-") elseif (CMAKE_COMPILER_IS_GNUCXX) set(cxx_base_flags "-Wall -Wshadow") set(cxx_exception_flags "-fexceptions") set(cxx_no_exception_flags "-fno-exceptions") # Until version 4.3.2, GCC doesn't define a macro to indicate # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-fno-rtti -DGTEST_HAS_RTTI=0") set(cxx_strict_flags "-Wextra -Wno-unused-parameter -Wno-missing-field-initializers") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "SunPro") set(cxx_exception_flags "-features=except") # Sun Pro doesn't provide macros to indicate whether exceptions and # RTTI are enabled, so we define GTEST_HAS_* explicitly. set(cxx_no_exception_flags "-features=no%except -DGTEST_HAS_EXCEPTIONS=0") set(cxx_no_rtti_flags "-features=no%rtti -DGTEST_HAS_RTTI=0") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "VisualAge" OR CMAKE_CXX_COMPILER_ID STREQUAL "XL") # CMake 2.8 changes Visual Age's compiler ID to "XL". set(cxx_exception_flags "-qeh") set(cxx_no_exception_flags "-qnoeh") # Until version 9.0, Visual Age doesn't define a macro to indicate # whether RTTI is enabled. Therefore we define GTEST_HAS_RTTI # explicitly. set(cxx_no_rtti_flags "-qnortti -DGTEST_HAS_RTTI=0") elseif (CMAKE_CXX_COMPILER_ID STREQUAL "HP") set(cxx_base_flags "-AA -mt") set(cxx_exception_flags "-DGTEST_HAS_EXCEPTIONS=1") set(cxx_no_exception_flags "+noeh -DGTEST_HAS_EXCEPTIONS=0") # RTTI can not be disabled in HP aCC compiler. set(cxx_no_rtti_flags "") endif() if (CMAKE_USE_PTHREADS_INIT) # The pthreads library is available and allowed. - set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=1") + set(GTEST_HAS_PTHREAD_MACRO "-DGTEST_HAS_PTHREAD=1") else() - set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=0") + set(GTEST_HAS_PTHREAD_MACRO "-DGTEST_HAS_PTHREAD=0") endif() + set(cxx_base_flags "${cxx_base_flags} ${GTEST_HAS_PTHREAD_MACRO}") # For building gtest's own tests and samples. set(cxx_exception "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_exception_flags}") set(cxx_no_exception "${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_no_exception_flags}") set(cxx_default "${cxx_exception}") set(cxx_no_rtti "${cxx_default} ${cxx_no_rtti_flags}") set(cxx_use_own_tuple "${cxx_default} -DGTEST_USE_OWN_TR1_TUPLE=1") # For building the gtest libraries. set(cxx_strict "${cxx_default} ${cxx_strict_flags}") endmacro() # Defines the gtest & gtest_main libraries. User tests should link # with one of them. function(cxx_library_with_type name type cxx_flags) # type can be either STATIC or SHARED to denote a static or shared library. # ARGN refers to additional arguments after 'cxx_flags'. add_library(${name} ${type} ${ARGN}) set_target_properties(${name} PROPERTIES COMPILE_FLAGS "${cxx_flags}") if (BUILD_SHARED_LIBS OR type STREQUAL "SHARED") set_target_properties(${name} PROPERTIES COMPILE_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1") endif() if (CMAKE_USE_PTHREADS_INIT) target_link_libraries(${name} ${CMAKE_THREAD_LIBS_INIT}) endif() endfunction() ######################################################################## # # Helper functions for creating build targets. function(cxx_shared_library name cxx_flags) cxx_library_with_type(${name} SHARED "${cxx_flags}" ${ARGN}) endfunction() function(cxx_library name cxx_flags) cxx_library_with_type(${name} "" "${cxx_flags}" ${ARGN}) endfunction() # cxx_executable_with_flags(name cxx_flags libs srcs...) # # creates a named C++ executable that depends on the given libraries and # is built from the given source files with the given compiler flags. function(cxx_executable_with_flags name cxx_flags libs) add_executable(${name} ${ARGN}) if (cxx_flags) set_target_properties(${name} PROPERTIES COMPILE_FLAGS "${cxx_flags}") endif() if (BUILD_SHARED_LIBS) set_target_properties(${name} PROPERTIES COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") endif() # To support mixing linking in static and dynamic libraries, link each # library in with an extra call to target_link_libraries. foreach (lib "${libs}") target_link_libraries(${name} ${lib}) endforeach() endfunction() # cxx_executable(name dir lib srcs...) # # creates a named target that depends on the given libs and is built # from the given source files. dir/name.cc is implicitly included in # the source file list. function(cxx_executable name dir libs) cxx_executable_with_flags( ${name} "${cxx_default}" "${libs}" "${dir}/${name}.cc" ${ARGN}) endfunction() # Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE. find_package(PythonInterp) # cxx_test_with_flags(name cxx_flags libs srcs...) # # creates a named C++ test that depends on the given libs and is built # from the given source files with the given compiler flags. function(cxx_test_with_flags name cxx_flags libs) cxx_executable_with_flags(${name} "${cxx_flags}" "${libs}" ${ARGN}) add_test(${name} ${name}) endfunction() # cxx_test(name libs srcs...) # # creates a named test target that depends on the given libs and is # built from the given source files. Unlike cxx_test_with_flags, # test/name.cc is already implicitly included in the source file list. function(cxx_test name libs) cxx_test_with_flags("${name}" "${cxx_default}" "${libs}" "test/${name}.cc" ${ARGN}) endfunction() # py_test(name) # # creates a Python test with the given name whose main module is in # test/name.py. It does nothing if Python is not installed. function(py_test name) # We are not supporting Python tests on Linux yet as they consider # all Linux environments to be google3 and try to use google3 features. if (PYTHONINTERP_FOUND) # ${CMAKE_BINARY_DIR} is known at configuration time, so we can # directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known # only at ctest runtime (by calling ctest -c <Configuration>), so # we have to escape $ to delay variable substitution here. if (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1) add_test( NAME ${name} COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>) else (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1) add_test( ${name} ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE}) endif (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 3.1) endif() endfunction() diff --git a/googletest/docs/AdvancedGuide.md b/googletest/docs/AdvancedGuide.md index 6c25db86..a454bf45 100644 --- a/googletest/docs/AdvancedGuide.md +++ b/googletest/docs/AdvancedGuide.md @@ -1,2182 +1,2182 @@ 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 the them. +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, -deteremines the test's success or failure. For example, you might want to write +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 <pre> !MutuallyPrime(b, c) is false, where<br> b is 4<br> c is 10<br> </pre> **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 +_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: <pre> Value of: IsEven(Fib(4))<br> Actual: false (*3 is odd*)<br> Expected: true<br> </pre> instead of a more opaque <pre> Value of: IsEven(Fib(4))<br> Actual: false<br> Expected: true<br> </pre> 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 <pre> Value of: IsEven(Fib(6))<br> Actual: true (8 is even)<br> Expected: false<br> </pre> _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 <pre> b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br> </pre> 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<T1, T2>(); ``` 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<T1, T2>()` is effective _only if_ the function is instantiated. For example, given: ``` template <typename T> class Foo { public: void Bar() { ::testing::StaticAssertTypeEq<int, T>(); } }; ``` the code: ``` void Test1() { Foo<bool> foo; } ``` will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never actually instantiated. Instead, you need: ``` void Test2() { Foo<bool> 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 <iostream> 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 <iostream> 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<pair<Bar, int> > 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 of how precisely +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: | `SCOPED_TRACE(`_message_`);` | |:-----------------------------| where _message_ can be anything streamable to `std::ostream`. This macro will cause the current file name, line number, and the given message to be added in every failure message. 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! } ``` Since we don't use exceptions, it is technically impossible to implement the intended behavior here. To alleviate this, Google Test provides two solutions. You could use either the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the `HasFatalFailure()` function. They are described in the following two subsections. ### 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: ``` ... <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" /> ... ``` _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<T>` (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<T>`, which itself is derived from both `::testing::Test` and `::testing::WithParamInterface<T>`. `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<const char*> { // You can implement all the usual fixture class members here. // To access the test parameter, call GetParam() from class // TestWithParam<T>. }; // 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<const char*> { ... }; ``` 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<T> 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 `<tr1/tuple>` 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 <i>abstract tests</i>. 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, he 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 <typename T> class FooTest : public ::testing::Test { public: ... typedef std::list<T> 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<char, int, unsigned int> 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` for a complete example. +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 <typename T> 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<char, int, unsigned int> 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 + * 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 +`"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 `TestCaseSetUp()`, `TestCaseTearDown()` (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 <b>event listener API</b> 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 <i>each pure virtual method<br> can be overridden to handle a test event</i> (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.) ### 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: ``` <testsuites name="AllTests" ...> <testsuite name="test_case_name" ...> <testcase name="test_name" ...> <failure message="..."/> <failure message="..."/> <failure message="..."/> </testcase> </testsuite> </testsuites> ``` * The root `<testsuites>` element corresponds to the entire test program. * `<testsuite>` elements correspond to Google Test test cases. * `<testcase>` 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: ``` <?xml version="1.0" encoding="UTF-8"?> <testsuites tests="3" failures="1" errors="0" time="35" name="AllTests"> <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15"> <testcase name="Addition" status="run" time="7" classname=""> <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type=""/> <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type=""/> </testcase> <testcase name="Subtraction" status="run" time="5" classname=""> </testcase> </testsuite> <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5"> <testcase name="NonContradiction" status="run" time="5" classname=""> </testcase> </testsuite> </testsuites> ``` Things to note: * The `tests` attribute of a `<testsuites>` or `<testsuite>` 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 `<failure>` 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. ## 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/DevGuide.md b/googletest/docs/DevGuide.md index 06467a32..4333a8e0 100644 --- a/googletest/docs/DevGuide.md +++ b/googletest/docs/DevGuide.md @@ -1,126 +1,126 @@ If you are interested in understanding the internals of Google Test, building from source, or contributing ideas or modifications to the project, then this document is for you. # Introduction # First, let's give you some background of the project. ## Licensing ## All Google Test source and pre-built packages are provided under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php). ## The Google Test Community ## The Google Test community exists primarily through the [discussion group](http://groups.google.com/group/googletestframework) and the GitHub repository. You are definitely encouraged to contribute to the discussion and you can also help us to keep the effectiveness of the group high by following and promoting the guidelines listed here. ### Please Be Friendly ### Showing courtesy and respect to others is a vital part of the Google culture, and we strongly encourage everyone participating in Google Test development to join us in accepting nothing less. Of course, being courteous is not the same as failing to constructively disagree with each other, but it does mean that we should be respectful of each other when enumerating the 42 technical reasons that a particular proposal may not be the best choice. There's never a reason to be antagonistic or dismissive toward anyone who is sincerely trying to contribute to a discussion. Sure, C++ testing is serious business and all that, but it's also a lot of fun. Let's keep it that way. Let's strive to be one of the friendliest communities in all of open source. As always, discuss Google Test in the official GoogleTest discussion group. You don't have to actually submit code in order to sign up. Your participation itself is a valuable contribution. # Working with the Code # If you want to get your hands dirty with the code inside Google Test, this is the section for you. ## Compiling from Source ## Once you check out the code, you can find instructions on how to compile it in the [README](../README.md) file. ## Testing ## A testing framework is of no good if itself is not thoroughly tested. Tests should be written for any new code, and changes should be verified to not break existing tests before they are submitted for review. To perform the tests, follow the instructions in [README](../README.md) and verify that there are no failures. # Contributing Code # We are excited that Google Test is now open source, and hope to get great patches from the community. Before you fire up your favorite IDE and begin hammering away at that new feature, though, please take the time to read this section and understand the process. While it seems rigorous, we want to keep a high standard of quality in the code base. ## Contributor License Agreements ## You must sign a Contributor License Agreement (CLA) before we can accept any code. The CLA protects you and us. * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). * If you work for a company that wants to allow you to contribute your work to Google Test, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. ## Coding Style ## To keep the source consistent, readable, diffable and easy to merge, -we use a fairly rigid coding style, as defined by the [google-styleguide](http://code.google.com/p/google-styleguide/) project. All patches will be expected -to conform to the style outlined [here](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml). +we use a fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project. All patches will be expected +to conform to the style outlined [here](https://google.github.io/styleguide/cppguide.html). ## Updating Generated Code ## Some of Google Test's source files are generated by the Pump tool (a Python script). If you need to update such files, please modify the source (`foo.h.pump`) and re-generate the C++ file using Pump. You can read the PumpManual for details. ## Submitting Patches ## Please do submit code. Here's what you need to do: 1. A submission should be a set of changes that addresses one issue in the [issue tracker](https://github.com/google/googletest/issues). Please don't mix more than one logical change per submittal, because it makes the history hard to follow. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please create one. 1. Also, coordinate with team members that are listed on the issue in question. This ensures that work isn't being duplicated and communicating your plan early also generally leads to better patches. 1. Ensure that your code adheres to the [Google Test source code style](#Coding_Style.md). 1. Ensure that there are unit tests for your code. 1. Sign a Contributor License Agreement. 1. Create a Pull Request in the usual way. ## Google Test Committers ## The current members of the Google Test engineering team are the only committers at present. In the great tradition of eating one's own dogfood, we will be requiring each new Google Test engineering team member to earn the right to become a committer by following the procedures in this document, writing consistently great code, and demonstrating repeatedly that he or she truly gets the zen of Google Test. # Release Process # We follow a typical release process: 1. A release branch named `release-X.Y` is created. 1. Bugs are fixed and features are added in trunk; those individual patches are merged into the release branch until it's stable. 1. An individual point release (the `Z` in `X.Y.Z`) is made by creating a tag from the branch. 1. Repeat steps 2 and 3 throughout one release cycle (as determined by features or time). 1. Go back to step 1 to create another release branch and so on. --- This page is based on the [Making GWT Better](http://code.google.com/webtoolkit/makinggwtbetter.html) guide from the [Google Web Toolkit](http://code.google.com/webtoolkit/) project. Except as otherwise [noted](http://code.google.com/policies.html#restrictions), the content of this page is licensed under the [Creative Commons Attribution 2.5 License](http://creativecommons.org/licenses/by/2.5/). diff --git a/googletest/docs/Documentation.md b/googletest/docs/Documentation.md index 8ca1aac7..1e4c5c54 100644 --- a/googletest/docs/Documentation.md +++ b/googletest/docs/Documentation.md @@ -1,14 +1,16 @@ -This page lists all documentation wiki pages for Google Test **(the SVN trunk version)** --- **if you use a released version of Google Test, please read the -documentation for that specific version instead.** +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](AdvancedGuide.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: * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files. \ No newline at end of file + * [PumpManual](PumpManual.md) -- how we generate some of Google Test's source files. diff --git a/googletest/docs/FAQ.md b/googletest/docs/FAQ.md index 5fd6cb72..36f5f7fb 100644 --- a/googletest/docs/FAQ.md +++ b/googletest/docs/FAQ.md @@ -1,1087 +1,1092 @@ If you cannot find the answer to your question here, and you have read [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? ## 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](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). ## 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 containers two consecutive underscores (i.e. `__`) _anywhere_ in its name. + 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 his tests using the _same_ compiler flags used to compile the installed Google Test libraries; otherwise he 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 `<New...>` 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 overriden 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<bool (*)(int)>*(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 <typename T> bool IsNegative(T x) { return x < 0; } ``` you can use it in a predicate assertion like this: ``` cpp ASSERT_PRED1(IsNegative*<int>*, -5); ``` Things are more interesting if your template has more than one parameters. The following won't compile: ``` cpp ASSERT_PRED2(*GreaterThan<int, int>*, 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<int, int>)*, 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](AdvancedGuide.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](AdvancedGuide.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 the posted his solution to -our mailing list. +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 runing this commad: +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 alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file. +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 foo ``` 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 foo ``` ## 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/Pkgconfig.md b/googletest/docs/Pkgconfig.md new file mode 100644 index 00000000..97612894 --- /dev/null +++ b/googletest/docs/Pkgconfig.md @@ -0,0 +1,146 @@ +## Using GoogleTest from various build systems ## + +GoogleTest comes with pkg-config files that can be used to determine all +necessary flags for compiling and linking to GoogleTest (and GoogleMock). +Pkg-config is a standardised plain-text format containing + + * the includedir (-I) path + * necessary macro (-D) definitions + * further required flags (-pthread) + * the library (-L) path + * the library (-l) to link to + +All current build systems support pkg-config in one way or another. For +all examples here we assume you want to compile the sample +`samples/sample3_unittest.cc`. + + +### CMake ### + +Using `pkg-config` in CMake is fairly easy: + +``` +cmake_minimum_required(VERSION 3.0) + +cmake_policy(SET CMP0048 NEW) +project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX) + +find_package(PkgConfig) +pkg_search_module(GTEST REQUIRED gtest_main) + +add_executable(testapp samples/sample3_unittest.cc) +target_link_libraries(testapp ${GTEST_LDFLAGS}) +target_compile_options(testapp PUBLIC ${GTEST_CFLAGS}) + +include(CTest) +add_test(first_and_only_test testapp) +``` + +It is generally recommended that you use `target_compile_options` + `_CFLAGS` +over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not +just -I flags (GoogleTest might require a macro indicating to internal headers +that all libraries have been compiled with threading enabled. In addition, +GoogleTest might also require `-pthread` in the compiling step, and as such +splitting the pkg-config `Cflags` variable into include dirs and macros for +`target_compile_definitions()` might still miss this). The same recommendation +goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which +happens to discard `-L` flags and `-pthread`. + + +### Autotools ### + +Finding GoogleTest in Autoconf and using it from Automake is also fairly easy: + +In your `configure.ac`: + +``` +AC_PREREQ([2.69]) +AC_INIT([my_gtest_pkgconfig], [0.0.1]) +AC_CONFIG_SRCDIR([samples/sample3_unittest.cc]) +AC_PROG_CXX + +PKG_CHECK_MODULES([GTEST], [gtest_main]) + +AM_INIT_AUTOMAKE([foreign subdir-objects]) +AC_CONFIG_FILES([Makefile]) +AC_OUTPUT +``` + +and in your `Makefile.am`: + +``` +check_PROGRAMS = testapp +TESTS = $(check_PROGRAMS) + +testapp_SOURCES = samples/sample3_unittest.cc +testapp_CXXFLAGS = $(GTEST_CFLAGS) +testapp_LDADD = $(GTEST_LIBS) +``` + + +### Meson ### + +Meson natively uses pkgconfig to query dependencies: + +``` +project('my_gtest_pkgconfig', 'cpp', version : '0.0.1') + +gtest_dep = dependency('gtest_main') + +testapp = executable( + 'testapp', + files(['samples/sample3_unittest.cc']), + dependencies : gtest_dep, + install : false) + +test('first_and_only_test', testapp) +``` + + +### Plain Makefiles ### + +Since `pkg-config` is a small Unix command-line utility, it can be used +in handwritten `Makefile`s too: + +``` +GTEST_CFLAGS = `pkg-config --cflags gtest_main` +GTEST_LIBS = `pkg-config --libs gtest_main` + +.PHONY: tests all + +tests: all + ./testapp + +all: testapp + +testapp: testapp.o + $(CXX) $(CXXFLAGS) $(LDFLAGS) $< -o $@ $(GTEST_LIBS) + +testapp.o: samples/sample3_unittest.cc + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ $(GTEST_CFLAGS) +``` + + +### Help! pkg-config can't find GoogleTest! ### + +Let's say you have a `CMakeLists.txt` along the lines of the one in this +tutorial and you try to run `cmake`. It is very possible that you get a +failure along the lines of: + +``` +-- Checking for one of the modules 'gtest_main' +CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message): + None of the required 'gtest_main' found +``` + +These failures are common if you installed GoogleTest yourself and have not +sourced it from a distro or other package manager. If so, you need to tell +pkg-config where it can find the `.pc` files containing the information. +Say you installed GoogleTest to `/usr/local`, then it might be that the +`.pc` files are installed under `/usr/local/lib64/pkgconfig`. If you set + +``` +export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig +``` + +pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`. diff --git a/googletest/docs/Primer.md b/googletest/docs/Primer.md index 474c1d2a..384d4d6e 100644 --- a/googletest/docs/Primer.md +++ b/googletest/docs/Primer.md @@ -1,502 +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_`, `_str_2`);` | the two C strings have the same content | +| `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(test_case_name, test_name) { ... 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. 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 <typename E> // 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<int> q0_; Queue<int> q1_; Queue<int> 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 text fixture's constructor generates a fatal failure in +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/PumpManual.md b/googletest/docs/PumpManual.md index 8184f153..109c7f2c 100644 --- a/googletest/docs/PumpManual.md +++ b/googletest/docs/PumpManual.md @@ -1,177 +1,177 @@ <b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. # The Problem # Template and macro libraries often need to define many classes, functions, or macros that vary only (or almost only) in the number of arguments they take. It's a lot of repetitive, mechanical, and error-prone work. Variadic templates and variadic macros can alleviate the problem. However, while both are being considered by the C++ committee, neither is in the standard yet or widely supported by compilers. Thus they are often not a good choice, especially when your code needs to be portable. And their capabilities are still limited. As a result, authors of such libraries often have to write scripts to generate their implementation. However, our experience is that it's tedious to write such scripts, which tend to reflect the structure of the generated code poorly and are often hard to read and edit. For example, a small change needed in the generated code may require some non-intuitive, non-trivial changes in the script. This is especially painful when experimenting with the code. # Our Solution # Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta Programming, or Practical Utility for Meta Programming, whichever you prefer) is a simple meta-programming tool for C++. The idea is that a programmer writes a `foo.pump` file which contains C++ code plus meta code that manipulates the C++ code. The meta code can handle iterations over a range, nested iterations, local meta variable definitions, simple arithmetic, and conditional expressions. You can view it as a small Domain-Specific Language. The meta language is designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, for example) and concise, making Pump code intuitive and easy to maintain. ## Highlights ## * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. * The format is human-readable and more concise than XML. * The format works relatively well with Emacs' C++ mode. ## Examples ## The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): ``` $var n = 3 $$ Defines a meta variable n. $range i 0..n $$ Declares the range of meta iterator i (inclusive). $for i [[ $$ Meta loop. // Foo$i does blah for $i-ary predicates. $range j 1..i template <size_t N $for j [[, typename A$j]]> class Foo$i { $if i == 0 [[ blah a; ]] $elif i <= 2 [[ blah b; ]] $else [[ blah c; ]] }; ]] ``` will be translated by the Pump compiler to: ``` // Foo0 does blah for 0-ary predicates. template <size_t N> class Foo0 { blah a; }; // Foo1 does blah for 1-ary predicates. template <size_t N, typename A1> class Foo1 { blah b; }; // Foo2 does blah for 2-ary predicates. template <size_t N, typename A1, typename A2> class Foo2 { blah b; }; // Foo3 does blah for 3-ary predicates. template <size_t N, typename A1, typename A2, typename A3> class Foo3 { blah c; }; ``` In another example, ``` $range i 1..n Func($for i + [[a$i]]); $$ The text between i and [[ is the separator between iterations. ``` will generate one of the following lines (without the comments), depending on the value of `n`: ``` Func(); // If n is 0. Func(a1); // If n is 1. Func(a1 + a2); // If n is 2. Func(a1 + a2 + a3); // If n is 3. // And so on... ``` ## Constructs ## We support the following meta programming constructs: | `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | |:----------------|:-----------------------------------------------------------------------------------------------| | `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later. | | `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | | `$($)` | Generates a single `$` character. | | `$id` | Value of the named constant or iteration variable. | | `$(exp)` | Value of the expression. | | `$if exp [[ code ]] else_branch` | Conditional. | | `[[ code ]]` | Meta lexical block. | | `cpp_code` | Raw C++ code. | | `$$ comment` | Meta comment. | **Note:** To give the user some freedom in formatting the Pump source code, Pump ignores a new-line character if it's right after `$for foo` or next to `[[` or `]]`. Without this rule you'll often be forced to write very long lines to get the desired output. Therefore sometimes you may need to insert an extra new-line in such places for a new-line to show up in your output. ## Grammar ## ``` code ::= atomic_code* atomic_code ::= $var id = exp | $var id = [[ code ]] | $range id exp..exp | $for id sep [[ code ]] | $($) | $id | $(exp) | $if exp [[ code ]] else_branch | [[ code ]] | cpp_code sep ::= cpp_code | empty_string else_branch ::= $else [[ code ]] | $elif exp [[ code ]] else_branch | empty_string exp ::= simple_expression_in_Python_syntax ``` ## Code ## You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still very unpolished and lacks automated tests, although it has been successfully used many times. If you find a chance to use it in your project, please let us know what you think! We also welcome help on improving Pump. ## Real Examples ## -You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. +You can find real-world applications of Pump in [Google Test](https://github.com/google/googletest/tree/master/googletest) and [Google Mock](https://github.com/google/googletest/tree/master/googlemock). The source file `foo.h.pump` generates `foo.h`. ## Tips ## * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. diff --git a/googletest/docs/V1_5_AdvancedGuide.md b/googletest/docs/V1_5_AdvancedGuide.md deleted file mode 100644 index 34e19c26..00000000 --- a/googletest/docs/V1_5_AdvancedGuide.md +++ /dev/null @@ -1,2096 +0,0 @@ - - -Now that you have read [Primer](V1_5_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 the 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();` | -|:-----------|:-----------------| - -`FAIL*` generates a fatal failure while `ADD_FAILURE*` generates a nonfatal -failure. These are useful when control flow, rather than a Boolean expression, -deteremines 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."; -} -``` - -_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 - -<pre> -!MutuallyPrime(b, c) is false, where<br> -b is 4<br> -c is 10<br> -</pre> - -**Notes:** - - 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](V1_5_FAQ.md#the-compiler-complains-about-undefined-references-to-some-static-const-member-variables-but-i-did-define-them-in-the-class-body-whats-wrong) 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: - -<pre> -Value of: !IsEven(Fib(4))<br> -Actual: false (*3 is odd*)<br> -Expected: true<br> -</pre> - -instead of a more opaque - -<pre> -Value of: !IsEven(Fib(4))<br> -Actual: false<br> -Expected: true<br> -</pre> - -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 - -<pre> -Value of: !IsEven(Fib(6))<br> -Actual: true (8 is even)<br> -Expected: false<br> -</pre> - -_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 - -<pre> -b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br> -</pre> - -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](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). - -### Floating-Point Macros ### - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_FLOAT_EQ(`_expected, actual_`);` | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal | -| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | 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<T1, T2>(); -``` -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<T1, T2>()` is effective _only if_ -the function is instantiated. For example, given: -``` -template <typename T> class Foo { - public: - void Bar() { ::testing::StaticAssertTypeEq<int, T>(); } -}; -``` -the code: -``` -void Test1() { Foo<bool> foo; } -``` -will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never -actually instantiated. Instead, you need: -``` -void Test2() { Foo<bool> 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! - -# 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 -in an expected fashion is also a death test. - -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(My*DeathTest*, 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 (`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 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 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 -except that it can not return from the current function. This means -_statement_ should not contain `return` or a macro that might return (e.g. -`ASSERT_TRUE()` ). If _statement_ returns before it crashes, Google Test will -print an error message, and the test will fail. - -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: - -| `SCOPED_TRACE(`_message_`);` | -|:-----------------------------| - -where _message_ can be anything streamable to `std::ostream`. This -macro will cause the current file name, line number, and the given -message to be added in every failure message. 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! -} -``` - -Since we don't use exceptions, it is technically impossible to -implement the intended behavior here. To alleviate this, Google Test -provides two solutions. You could use either the -`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the -`HasFatalFailure()` function. They are described in the following two -subsections. - - - -### 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 C string or a 32-bit -integer. 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: - -``` -... - <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest" - MaximumWidgets="12" - MinimumWidgets="9" /> -... -``` - -_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`, and `classname`). - -_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, TestFooo) { - 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 wan 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 `::testing::TestWithParam<T>`, where `T` -is the type of your parameter values. `TestWithParam<T>` is itself -derived from `::testing::Test`. `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<const char*> { - // You can implement all the usual fixture class members here. - // To access the test parameter, call GetParam() from class - // TestWithParam<T>. -}; -``` - -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<T> 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)`. | -| `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 `<tr1/tuple>` 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 <i>abstract tests</i>. 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, he 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 <typename T> -class FooTest : public ::testing::Test { - public: - ... - typedef std::list<T> 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<char, int, unsigned int> 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` 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 <typename T> -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<char, int, unsigned int> 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 `TestCaseSetUp()`, -`TestCaseTearDown()` (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 <b>event listener API</b> 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#L855) -or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L905). -The former is an (abstract) interface, where <i>each pure virtual method<br> -can be overridden to handle a test event</i> (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#L1007) reflects the state of the entire test program, - * [TestCase](../include/gtest/gtest.h#L689) has information about a test case, which can contain one or more tests, - * [TestInfo](../include/gtest/gtest.h#L599) contains the state of a test, and - * [TestPartResult](../include/gtest/gtest-test-part.h#L42) 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 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(), - 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#L929) -- 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.) - -### 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: - -``` -<testsuites name="AllTests" ...> - <testsuite name="test_case_name" ...> - <testcase name="test_name" ...> - <failure message="..."/> - <failure message="..."/> - <failure message="..."/> - </testcase> - </testsuite> -</testsuites> -``` - - * The root `<testsuites>` element corresponds to the entire test program. - * `<testsuite>` elements correspond to Google Test test cases. - * `<testcase>` 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: - -``` -<?xml version="1.0" encoding="UTF-8"?> -<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests"> - <testsuite name="MathTest" tests="2" failures="1"* errors="0" time="15"> - <testcase name="Addition" status="run" time="7" classname=""> - <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type=""/> - <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type=""/> - </testcase> - <testcase name="Subtraction" status="run" time="5" classname=""> - </testcase> - </testsuite> - <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5"> - <testcase name="NonContradiction" status="run" time="5" classname=""> - </testcase> - </testsuite> -</testsuites> -``` - -Things to note: - - * The `tests` attribute of a `<testsuites>` or `<testsuite>` 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 `<failure>` 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. - -## 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. - -### Suppressing Pop-ups Caused by Exceptions ### - -On Windows, Google Test may be used with exceptions enabled. Even when -exceptions are disabled, an application can still throw structured exceptions -(SEH's). If a test throws an exception, by default Google Test doesn't try to -catch it. Instead, you'll see a pop-up dialog, at which point you can attach -the process to a debugger and easily find out what went wrong. - -However, if you don't want to see the pop-ups (for example, if you run the -tests in a batch job), set the `GTEST_CATCH_EXCEPTIONS` environment variable to -a non- `0` value, or use the `--gtest_catch_exceptions` flag. Google Test now -catches all test-thrown exceptions and logs them as failures. - -_Availability:_ Windows. `GTEST_CATCH_EXCEPTIONS` and -`--gtest_catch_exceptions` have no effect on Google Test's behavior on Linux or -Mac, even if exceptions are enabled. It is possible to add support for catching -exceptions on these platforms, but it is not implemented yet. - -### 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. - -_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 -[scrpts/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 [FAQ](V1_5_FAQ.md). diff --git a/googletest/docs/V1_5_Documentation.md b/googletest/docs/V1_5_Documentation.md deleted file mode 100644 index 46bba2ec..00000000 --- a/googletest/docs/V1_5_Documentation.md +++ /dev/null @@ -1,12 +0,0 @@ -This page lists all official documentation wiki pages for Google Test **1.5.0** -- **if you use a different version of Google Test, make sure to read the documentation for that version instead.** - - * [Primer](V1_5_Primer.md) -- start here if you are new to Google Test. - * [Samples](Samples.md) -- learn from examples. - * [AdvancedGuide](V1_5_AdvancedGuide.md) -- learn more about Google Test. - * [XcodeGuide](V1_5_XcodeGuide.md) -- how to use Google Test in Xcode on Mac. - * [Frequently-Asked Questions](V1_5_FAQ.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Test, read: - - * DevGuide -- read this _before_ writing your first patch. - * [PumpManual](V1_5_PumpManual.md) -- how we generate some of Google Test's source files. \ No newline at end of file diff --git a/googletest/docs/V1_5_FAQ.md b/googletest/docs/V1_5_FAQ.md deleted file mode 100644 index e870aff0..00000000 --- a/googletest/docs/V1_5_FAQ.md +++ /dev/null @@ -1,886 +0,0 @@ - - -If you cannot find the answer to your question here, and you have read -[Primer](V1_5_Primer.md) and [AdvancedGuide](V1_5_AdvancedGuide.md), send it to -googletestframework@googlegroups.com. - -## Why should I use Google Test instead of my favorite C++ testing framework? ## - -First, let's 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 works where many STL types (e.g. `std::string` and `std::vector`) don't compile. It doesn't require exceptions or RTTI. As a result, it runs 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. - * No framework can anticipate all your needs, so Google Test provides `EXPECT_PRED*` to make it easy to extend your assertion vocabulary. For a nicer syntax, you can define your own assertion macros trivially in terms of `EXPECT_PRED*`. - * 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. - -## 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 `<New...>` 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](../../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: -``` -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: - -``` -class FooTest : public ::testing::Test {}; - -TEST_F(FooTest, DoesThis) { ... } -``` -or -``` -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: -``` - 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, -``` - 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: - -``` -// foo.h -class Foo { - ... - static const int kBar = 100; -}; -``` - -You also need to define it _outside_ of the class body in `foo.cc`: - -``` -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: - -``` -// 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 -`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, call `TearDown()`, and then -_immediately_ delete the test fixture object. Therefore, there is no -need to write a `SetUp()` or `TearDown()` function if the constructor -or destructor already does the job. - -You may still want to use `SetUp()/TearDown()` in the following 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 Google Test 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 Google Test 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 overriden 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 - -``` -bool IsPositive(int n) { - return n > 0; -} -bool IsPositive(double x) { - return x > 0; -} -``` - -you will get a compiler error if you write - -``` -EXPECT_PRED1(IsPositive, 5); -``` - -However, this will work: - -``` -EXPECT_PRED1(*static_cast<bool (*)(int)>*(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 - -``` -template <typename T> -bool IsNegative(T x) { - return x < 0; -} -``` - -you can use it in a predicate assertion like this: - -``` -ASSERT_PRED1(IsNegative*<int>*, -5); -``` - -Things are more interesting if your template has more than one parameters. The -following won't compile: - -``` -ASSERT_PRED2(*GreaterThan<int, int>*, 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: - -``` -ASSERT_PRED2(*(GreaterThan<int, int>)*, 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 - -``` -return RUN_ALL_TESTS(); -``` - -they write - -``` -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. - -``` -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 - -``` -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: -``` -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: -``` -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: -``` -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: -``` -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: -``` -// 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: -``` -// 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](V1_5_AdvancedGuide.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: -``` -// 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: - -``` -// 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](V1_5_AdvancedGuide.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: - -``` -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: - -``` -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](V1_5_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 the posted his solution to -our mailing list. Here is his link: -http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html. - -## 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](http://code.google.com/p/googletest/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics), - 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](http://code.google.com/p/googletest/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google 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/V1_5_Primer.md b/googletest/docs/V1_5_Primer.md deleted file mode 100644 index 6960d2ce..00000000 --- a/googletest/docs/V1_5_Primer.md +++ /dev/null @@ -1,497 +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_. - -# 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 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(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ | -|`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_ -. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions -we'll introduce later), you should put the expression you want to test -in the position of _actual_, and put its expected value in _expected_, -as Google Test's failure messages are optimized for this convention. - -Value arguments must be comparable by the assertion's comparison operator or -you'll get a compiler error. Values must also support the `<<` operator for -streaming to an `ostream`. All built-in types support this. - -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. - -## 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(`_expected\_str_`, `_actual\_str_`);` | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);` | 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(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | 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 [AdvancedGuide Advanced -Google Test Guide]. - -# 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(test_case_name, test_name) { - ... 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. Remember that a test case can contain any number of individual -tests. 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](V1_5_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 <typename E> // 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<int> q0_; - Queue<int> q1_; - Queue<int> 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 text 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](V1_5_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](V1_5_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/V1_5_PumpManual.md b/googletest/docs/V1_5_PumpManual.md deleted file mode 100644 index 15710789..00000000 --- a/googletest/docs/V1_5_PumpManual.md +++ /dev/null @@ -1,177 +0,0 @@ - - -<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. - -# The Problem # - -Template and macro libraries often need to define many classes, -functions, or macros that vary only (or almost only) in the number of -arguments they take. It's a lot of repetitive, mechanical, and -error-prone work. - -Variadic templates and variadic macros can alleviate the problem. -However, while both are being considered by the C++ committee, neither -is in the standard yet or widely supported by compilers. Thus they -are often not a good choice, especially when your code needs to be -portable. And their capabilities are still limited. - -As a result, authors of such libraries often have to write scripts to -generate their implementation. However, our experience is that it's -tedious to write such scripts, which tend to reflect the structure of -the generated code poorly and are often hard to read and edit. For -example, a small change needed in the generated code may require some -non-intuitive, non-trivial changes in the script. This is especially -painful when experimenting with the code. - -# Our Solution # - -Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta -Programming, or Practical Utility for Meta Programming, whichever you -prefer) is a simple meta-programming tool for C++. The idea is that a -programmer writes a `foo.pump` file which contains C++ code plus meta -code that manipulates the C++ code. The meta code can handle -iterations over a range, nested iterations, local meta variable -definitions, simple arithmetic, and conditional expressions. You can -view it as a small Domain-Specific Language. The meta language is -designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, -for example) and concise, making Pump code intuitive and easy to -maintain. - -## Highlights ## - - * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. - * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. - * The format is human-readable and more concise than XML. - * The format works relatively well with Emacs' C++ mode. - -## Examples ## - -The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): - -``` -$var n = 3 $$ Defines a meta variable n. -$range i 0..n $$ Declares the range of meta iterator i (inclusive). -$for i [[ - $$ Meta loop. -// Foo$i does blah for $i-ary predicates. -$range j 1..i -template <size_t N $for j [[, typename A$j]]> -class Foo$i { -$if i == 0 [[ - blah a; -]] $elif i <= 2 [[ - blah b; -]] $else [[ - blah c; -]] -}; - -]] -``` - -will be translated by the Pump compiler to: - -``` -// Foo0 does blah for 0-ary predicates. -template <size_t N> -class Foo0 { - blah a; -}; - -// Foo1 does blah for 1-ary predicates. -template <size_t N, typename A1> -class Foo1 { - blah b; -}; - -// Foo2 does blah for 2-ary predicates. -template <size_t N, typename A1, typename A2> -class Foo2 { - blah b; -}; - -// Foo3 does blah for 3-ary predicates. -template <size_t N, typename A1, typename A2, typename A3> -class Foo3 { - blah c; -}; -``` - -In another example, - -``` -$range i 1..n -Func($for i + [[a$i]]); -$$ The text between i and [[ is the separator between iterations. -``` - -will generate one of the following lines (without the comments), depending on the value of `n`: - -``` -Func(); // If n is 0. -Func(a1); // If n is 1. -Func(a1 + a2); // If n is 2. -Func(a1 + a2 + a3); // If n is 3. -// And so on... -``` - -## Constructs ## - -We support the following meta programming constructs: - -| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | -|:----------------|:-----------------------------------------------------------------------------------------------| -| $range id exp..exp | Sets the range of an iteration variable, which can be reused in multiple loops later. | -| $for id sep [[code ](.md)] | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | -| `$($)` | Generates a single `$` character. | -| `$id` | Value of the named constant or iteration variable. | -| `$(exp)` | Value of the expression. | -| `$if exp [[ code ]] else_branch` | Conditional. | -| `[[ code ]]` | Meta lexical block. | -| `cpp_code` | Raw C++ code. | -| `$$ comment` | Meta comment. | - -**Note:** To give the user some freedom in formatting the Pump source -code, Pump ignores a new-line character if it's right after `$for foo` -or next to `[[` or `]]`. Without this rule you'll often be forced to write -very long lines to get the desired output. Therefore sometimes you may -need to insert an extra new-line in such places for a new-line to show -up in your output. - -## Grammar ## - -``` -code ::= atomic_code* -atomic_code ::= $var id = exp - | $var id = [[ code ]] - | $range id exp..exp - | $for id sep [[ code ]] - | $($) - | $id - | $(exp) - | $if exp [[ code ]] else_branch - | [[ code ]] - | cpp_code -sep ::= cpp_code | empty_string -else_branch ::= $else [[ code ]] - | $elif exp [[ code ]] else_branch - | empty_string -exp ::= simple_expression_in_Python_syntax -``` - -## Code ## - -You can find the source code of Pump in [scripts/pump.py](http://code.google.com/p/googletest/source/browse/trunk/scripts/pump.py). It is still -very unpolished and lacks automated tests, although it has been -successfully used many times. If you find a chance to use it in your -project, please let us know what you think! We also welcome help on -improving Pump. - -## Real Examples ## - -You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. - -## Tips ## - - * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. - * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. \ No newline at end of file diff --git a/googletest/docs/V1_5_XcodeGuide.md b/googletest/docs/V1_5_XcodeGuide.md deleted file mode 100644 index bf24bf51..00000000 --- a/googletest/docs/V1_5_XcodeGuide.md +++ /dev/null @@ -1,93 +0,0 @@ - - -This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. - -# Quick Start # - -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. 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" - 1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" - 1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. - 1. Build and Go - -The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. - -# 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: - -``` -svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only -``` - -Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. - -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`). - -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. - -``` -[Computer:svn] user$ svn propget svn:externals trunk -externals/src/googletest http://googletest.googlecode.com/svn/trunk -``` - -# Add the Framework to Your Project # - -The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. - - * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. - * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). - -# Make a Test Target # - -To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. - -Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. - - * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. - * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. - -# Set Up the Executable Run Environment # - -Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. - -If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: - -``` -[Session started at 2008-08-15 06:23:57 -0600.] - dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest - Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest - Reason: image not found -``` - -To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. - -# Build and Go # - -Now, when you click "Build and Go", the test will be executed. Dumping out something like this: - -``` -[Session started at 2008-08-06 06:36:13 -0600.] -[==========] Running 2 tests from 1 test case. -[----------] Global test environment set-up. -[----------] 2 tests from WidgetInitializerTest -[ RUN ] WidgetInitializerTest.TestConstructor -[ OK ] WidgetInitializerTest.TestConstructor -[ RUN ] WidgetInitializerTest.TestConversion -[ OK ] WidgetInitializerTest.TestConversion -[----------] Global test environment tear-down -[==========] 2 tests from 1 test case ran. -[ PASSED ] 2 tests. - -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 diff --git a/googletest/docs/V1_6_AdvancedGuide.md b/googletest/docs/V1_6_AdvancedGuide.md deleted file mode 100644 index 78864b16..00000000 --- a/googletest/docs/V1_6_AdvancedGuide.md +++ /dev/null @@ -1,2178 +0,0 @@ - - -Now that you have read [Primer](V1_6_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 the 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, -deteremines 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."; -} -``` - -_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 - -<pre> -!MutuallyPrime(b, c) is false, where<br> -b is 4<br> -c is 10<br> -</pre> - -**Notes:** - - 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](v1_6_FAQ.md#ithe-compiler-complains-about-undefined-references-to-some-static-const-member-variables-but-i-did-define-them-in-the-class-body-whats-wrong) 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: - -<pre> -Value of: !IsEven(Fib(4))<br> -Actual: false (*3 is odd*)<br> -Expected: true<br> -</pre> - -instead of a more opaque - -<pre> -Value of: !IsEven(Fib(4))<br> -Actual: false<br> -Expected: true<br> -</pre> - -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 - -<pre> -Value of: !IsEven(Fib(6))<br> -Actual: true (8 is even)<br> -Expected: false<br> -</pre> - -_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 - -<pre> -b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br> -</pre> - -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](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). - -### Floating-Point Macros ### - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_FLOAT_EQ(`_expected, actual_`);` | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal | -| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | 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<T1, T2>(); -``` -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<T1, T2>()` is effective _only if_ -the function is instantiated. For example, given: -``` -template <typename T> class Foo { - public: - void Bar() { ::testing::StaticAssertTypeEq<int, T>(); } -}; -``` -the code: -``` -void Test1() { Foo<bool> foo; } -``` -will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never -actually instantiated. Instead, you need: -``` -void Test2() { Foo<bool> 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 <iostream> - -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 <iostream> - -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<pair<Bar, int> > 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(My*DeathTest*, 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 (`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 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 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: - -| `SCOPED_TRACE(`_message_`);` | -|:-----------------------------| - -where _message_ can be anything streamable to `std::ostream`. This -macro will cause the current file name, line number, and the given -message to be added in every failure message. 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! -} -``` - -Since we don't use exceptions, it is technically impossible to -implement the intended behavior here. To alleviate this, Google Test -provides two solutions. You could use either the -`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the -`HasFatalFailure()` function. They are described in the following two -subsections. - -### 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 C string or a 32-bit -integer. 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: - -``` -... - <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest" - MaximumWidgets="12" - MinimumWidgets="9" /> -... -``` - -_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`, and `classname`). - -_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, TestFooo) { - 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<T>` (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<T>`, -which itself is derived from both `::testing::Test` and -`::testing::WithParamInterface<T>`. `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<const char*> { - // You can implement all the usual fixture class members here. - // To access the test parameter, call GetParam() from class - // TestWithParam<T>. -}; - -// 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<const char*> { - ... -}; -``` - -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<T> 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 `<tr1/tuple>` 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 <i>abstract tests</i>. 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, he 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 <typename T> -class FooTest : public ::testing::Test { - public: - ... - typedef std::list<T> 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<char, int, unsigned int> 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` 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 <typename T> -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<char, int, unsigned int> 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 `TestCaseSetUp()`, -`TestCaseTearDown()` (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 <b>event listener API</b> 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#L855) -or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L905). -The former is an (abstract) interface, where <i>each pure virtual method<br> -can be overridden to handle a test event</i> (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#L1007) reflects the state of the entire test program, - * [TestCase](../include/gtest/gtest.h#L689) has information about a test case, which can contain one or more tests, - * [TestInfo](../include/gtest/gtest.h#L599) contains the state of a test, and - * [TestPartResult](../include/gtest/gtest-test-part.h#L42) 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#L929) -- 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.) - -### 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: - -``` -<testsuites name="AllTests" ...> - <testsuite name="test_case_name" ...> - <testcase name="test_name" ...> - <failure message="..."/> - <failure message="..."/> - <failure message="..."/> - </testcase> - </testsuite> -</testsuites> -``` - - * The root `<testsuites>` element corresponds to the entire test program. - * `<testsuite>` elements correspond to Google Test test cases. - * `<testcase>` 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: - -``` -<?xml version="1.0" encoding="UTF-8"?> -<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests"> - <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15"> - <testcase name="Addition" status="run" time="7" classname=""> - <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type=""/> - <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type=""/> - </testcase> - <testcase name="Subtraction" status="run" time="5" classname=""> - </testcase> - </testsuite> - <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5"> - <testcase name="NonContradiction" status="run" time="5" classname=""> - </testcase> - </testsuite> -</testsuites> -``` - -Things to note: - - * The `tests` attribute of a `<testsuites>` or `<testsuite>` 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 `<failure>` 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. - -## 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. - -_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](V1_6_FAQ.md). diff --git a/googletest/docs/V1_6_Documentation.md b/googletest/docs/V1_6_Documentation.md deleted file mode 100644 index ca924660..00000000 --- a/googletest/docs/V1_6_Documentation.md +++ /dev/null @@ -1,14 +0,0 @@ -This page lists all documentation wiki pages for Google Test **1.6** --- **if you use a released version of Google Test, please read the -documentation for that specific version instead.** - - * [Primer](V1_6_Primer.md) -- start here if you are new to Google Test. - * [Samples](V1_6_Samples.md) -- learn from examples. - * [AdvancedGuide](V1_6_AdvancedGuide.md) -- learn more about Google Test. - * [XcodeGuide](V1_6_XcodeGuide.md) -- how to use Google Test in Xcode on Mac. - * [Frequently-Asked Questions](V1_6_FAQ.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Test, read: - - * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [PumpManual](V1_6_PumpManual.md) -- how we generate some of Google Test's source files. \ No newline at end of file diff --git a/googletest/docs/V1_6_FAQ.md b/googletest/docs/V1_6_FAQ.md deleted file mode 100644 index 2b7f7840..00000000 --- a/googletest/docs/V1_6_FAQ.md +++ /dev/null @@ -1,1038 +0,0 @@ - - -If you cannot find the answer to your question here, and you have read -[Primer](V1_6_Primer.md) and [AdvancedGuide](V1_6_AdvancedGuide.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](V1_6_AdvancedGuide.md#Global_Set-Up_and_Tear-Down) and tests parameterized by [values](V1_6_AdvancedGuide.md#value-parameterized-tests) or [types](V1_6_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](V1_6_AdvancedGuide.md#predicate-assertions-for-better-error-messages), - * teach Google Test how to [print your types](V1_6_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](V1_6_AdvancedGuide.md#catching-failures), and - * reflect on the test cases or change the test output format by intercepting the [test events](V1_6_AdvancedGuide.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 containers 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: -``` -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 his tests using the _same_ compiler -flags used to compile the installed Google Test libraries; otherwise -he 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 `<New...>` 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](../../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: -``` -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: - -``` -class FooTest : public ::testing::Test {}; - -TEST_F(FooTest, DoesThis) { ... } -``` -or -``` -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: -``` - 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, -``` - 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: - -``` -// foo.h -class Foo { - ... - static const int kBar = 100; -}; -``` - -You also need to define it _outside_ of the class body in `foo.cc`: - -``` -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: - -``` -// 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, call `TearDown()`, and then -_immediately_ delete the test fixture object. Therefore, there is no -need to write a `SetUp()` or `TearDown()` function if the constructor -or destructor already does the job. - -You may still want to use `SetUp()/TearDown()` in the following 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 Google Test 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 Google Test 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 overriden 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 - -``` -bool IsPositive(int n) { - return n > 0; -} -bool IsPositive(double x) { - return x > 0; -} -``` - -you will get a compiler error if you write - -``` -EXPECT_PRED1(IsPositive, 5); -``` - -However, this will work: - -``` -EXPECT_PRED1(*static_cast<bool (*)(int)>*(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 - -``` -template <typename T> -bool IsNegative(T x) { - return x < 0; -} -``` - -you can use it in a predicate assertion like this: - -``` -ASSERT_PRED1(IsNegative*<int>*, -5); -``` - -Things are more interesting if your template has more than one parameters. The -following won't compile: - -``` -ASSERT_PRED2(*GreaterThan<int, int>*, 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: - -``` -ASSERT_PRED2(*(GreaterThan<int, int>)*, 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 - -``` -return RUN_ALL_TESTS(); -``` - -they write - -``` -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. - -``` -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 - -``` -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: -``` -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: -``` -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: -``` -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: -``` -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: -``` -// 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: -``` -// 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](V1_6_AdvancedGuide.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: -``` -// 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: - -``` -// 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](V1_6_AdvancedGuide.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: - -``` -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: - -``` -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](V1_6_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 the posted his solution to -our mailing list. Here is his link: -http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html. - -## 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 runing this commad: - -`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 -``` - GTEST_TEST(SomeTest, DoesThis) { ... } -``` -instead of -``` - TEST(SomeTest, DoesThis) { ... } -``` -in order to define a test. - -Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/include/gtest/gtest.h). More information can be found in the "Avoiding Macro Name Clashes" section of the README file. - -## 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](http://code.google.com/p/googletest/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics), - 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](http://code.google.com/p/googletest/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google 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/V1_6_Primer.md b/googletest/docs/V1_6_Primer.md deleted file mode 100644 index 8d840ef4..00000000 --- a/googletest/docs/V1_6_Primer.md +++ /dev/null @@ -1,501 +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_. - -# 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(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ | -|`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_ -. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions -we'll introduce later), you should put the expression you want to test -in the position of _actual_, and put its expected value in _expected_, -as Google Test's failure messages are optimized for this convention. - -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. - -## 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(`_expected\_str_`, `_actual\_str_`);` | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);` | 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(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | 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](V1_6_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(test_case_name, test_name) { - ... 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](V1_6_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 <typename E> // 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<int> q0_; - Queue<int> q1_; - Queue<int> 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 text 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](V1_6_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](V1_6_Samples.md), or continue with -[AdvancedGuide](V1_6_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/V1_6_PumpManual.md b/googletest/docs/V1_6_PumpManual.md deleted file mode 100644 index 8184f153..00000000 --- a/googletest/docs/V1_6_PumpManual.md +++ /dev/null @@ -1,177 +0,0 @@ - - -<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. - -# The Problem # - -Template and macro libraries often need to define many classes, -functions, or macros that vary only (or almost only) in the number of -arguments they take. It's a lot of repetitive, mechanical, and -error-prone work. - -Variadic templates and variadic macros can alleviate the problem. -However, while both are being considered by the C++ committee, neither -is in the standard yet or widely supported by compilers. Thus they -are often not a good choice, especially when your code needs to be -portable. And their capabilities are still limited. - -As a result, authors of such libraries often have to write scripts to -generate their implementation. However, our experience is that it's -tedious to write such scripts, which tend to reflect the structure of -the generated code poorly and are often hard to read and edit. For -example, a small change needed in the generated code may require some -non-intuitive, non-trivial changes in the script. This is especially -painful when experimenting with the code. - -# Our Solution # - -Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta -Programming, or Practical Utility for Meta Programming, whichever you -prefer) is a simple meta-programming tool for C++. The idea is that a -programmer writes a `foo.pump` file which contains C++ code plus meta -code that manipulates the C++ code. The meta code can handle -iterations over a range, nested iterations, local meta variable -definitions, simple arithmetic, and conditional expressions. You can -view it as a small Domain-Specific Language. The meta language is -designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, -for example) and concise, making Pump code intuitive and easy to -maintain. - -## Highlights ## - - * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. - * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. - * The format is human-readable and more concise than XML. - * The format works relatively well with Emacs' C++ mode. - -## Examples ## - -The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): - -``` -$var n = 3 $$ Defines a meta variable n. -$range i 0..n $$ Declares the range of meta iterator i (inclusive). -$for i [[ - $$ Meta loop. -// Foo$i does blah for $i-ary predicates. -$range j 1..i -template <size_t N $for j [[, typename A$j]]> -class Foo$i { -$if i == 0 [[ - blah a; -]] $elif i <= 2 [[ - blah b; -]] $else [[ - blah c; -]] -}; - -]] -``` - -will be translated by the Pump compiler to: - -``` -// Foo0 does blah for 0-ary predicates. -template <size_t N> -class Foo0 { - blah a; -}; - -// Foo1 does blah for 1-ary predicates. -template <size_t N, typename A1> -class Foo1 { - blah b; -}; - -// Foo2 does blah for 2-ary predicates. -template <size_t N, typename A1, typename A2> -class Foo2 { - blah b; -}; - -// Foo3 does blah for 3-ary predicates. -template <size_t N, typename A1, typename A2, typename A3> -class Foo3 { - blah c; -}; -``` - -In another example, - -``` -$range i 1..n -Func($for i + [[a$i]]); -$$ The text between i and [[ is the separator between iterations. -``` - -will generate one of the following lines (without the comments), depending on the value of `n`: - -``` -Func(); // If n is 0. -Func(a1); // If n is 1. -Func(a1 + a2); // If n is 2. -Func(a1 + a2 + a3); // If n is 3. -// And so on... -``` - -## Constructs ## - -We support the following meta programming constructs: - -| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | -|:----------------|:-----------------------------------------------------------------------------------------------| -| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later. | -| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | -| `$($)` | Generates a single `$` character. | -| `$id` | Value of the named constant or iteration variable. | -| `$(exp)` | Value of the expression. | -| `$if exp [[ code ]] else_branch` | Conditional. | -| `[[ code ]]` | Meta lexical block. | -| `cpp_code` | Raw C++ code. | -| `$$ comment` | Meta comment. | - -**Note:** To give the user some freedom in formatting the Pump source -code, Pump ignores a new-line character if it's right after `$for foo` -or next to `[[` or `]]`. Without this rule you'll often be forced to write -very long lines to get the desired output. Therefore sometimes you may -need to insert an extra new-line in such places for a new-line to show -up in your output. - -## Grammar ## - -``` -code ::= atomic_code* -atomic_code ::= $var id = exp - | $var id = [[ code ]] - | $range id exp..exp - | $for id sep [[ code ]] - | $($) - | $id - | $(exp) - | $if exp [[ code ]] else_branch - | [[ code ]] - | cpp_code -sep ::= cpp_code | empty_string -else_branch ::= $else [[ code ]] - | $elif exp [[ code ]] else_branch - | empty_string -exp ::= simple_expression_in_Python_syntax -``` - -## Code ## - -You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still -very unpolished and lacks automated tests, although it has been -successfully used many times. If you find a chance to use it in your -project, please let us know what you think! We also welcome help on -improving Pump. - -## Real Examples ## - -You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. - -## Tips ## - - * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. - * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. diff --git a/googletest/docs/V1_6_Samples.md b/googletest/docs/V1_6_Samples.md deleted file mode 100644 index f21d2005..00000000 --- a/googletest/docs/V1_6_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/V1_6_XcodeGuide.md b/googletest/docs/V1_6_XcodeGuide.md deleted file mode 100644 index bf24bf51..00000000 --- a/googletest/docs/V1_6_XcodeGuide.md +++ /dev/null @@ -1,93 +0,0 @@ - - -This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. - -# Quick Start # - -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. 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" - 1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" - 1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. - 1. Build and Go - -The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. - -# 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: - -``` -svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only -``` - -Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. - -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`). - -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. - -``` -[Computer:svn] user$ svn propget svn:externals trunk -externals/src/googletest http://googletest.googlecode.com/svn/trunk -``` - -# Add the Framework to Your Project # - -The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. - - * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. - * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). - -# Make a Test Target # - -To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. - -Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. - - * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. - * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. - -# Set Up the Executable Run Environment # - -Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. - -If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: - -``` -[Session started at 2008-08-15 06:23:57 -0600.] - dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest - Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest - Reason: image not found -``` - -To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. - -# Build and Go # - -Now, when you click "Build and Go", the test will be executed. Dumping out something like this: - -``` -[Session started at 2008-08-06 06:36:13 -0600.] -[==========] Running 2 tests from 1 test case. -[----------] Global test environment set-up. -[----------] 2 tests from WidgetInitializerTest -[ RUN ] WidgetInitializerTest.TestConstructor -[ OK ] WidgetInitializerTest.TestConstructor -[ RUN ] WidgetInitializerTest.TestConversion -[ OK ] WidgetInitializerTest.TestConversion -[----------] Global test environment tear-down -[==========] 2 tests from 1 test case ran. -[ PASSED ] 2 tests. - -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 diff --git a/googletest/docs/V1_7_AdvancedGuide.md b/googletest/docs/V1_7_AdvancedGuide.md deleted file mode 100644 index dd4af8f3..00000000 --- a/googletest/docs/V1_7_AdvancedGuide.md +++ /dev/null @@ -1,2181 +0,0 @@ - - -Now that you have read [Primer](V1_7_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 the 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, -deteremines 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."; -} -``` - -_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 - -<pre> -!MutuallyPrime(b, c) is false, where<br> -b is 4<br> -c is 10<br> -</pre> - -**Notes:** - - 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this](V1_7_FAQ.md#the-compiler-complains-about-undefined-references-to-some-static-const-member-variables-but-i-did-define-them-in-the-class-body-whats-wrong) 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: - -<pre> -Value of: IsEven(Fib(4))<br> -Actual: false (*3 is odd*)<br> -Expected: true<br> -</pre> - -instead of a more opaque - -<pre> -Value of: IsEven(Fib(4))<br> -Actual: false<br> -Expected: true<br> -</pre> - -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 - -<pre> -Value of: IsEven(Fib(6))<br> -Actual: true (8 is even)<br> -Expected: false<br> -</pre> - -_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 - -<pre> -b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br> -</pre> - -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](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). - -### Floating-Point Macros ### - -| **Fatal assertion** | **Nonfatal assertion** | **Verifies** | -|:--------------------|:-----------------------|:-------------| -| `ASSERT_FLOAT_EQ(`_expected, actual_`);` | `EXPECT_FLOAT_EQ(`_expected, actual_`);` | the two `float` values are almost equal | -| `ASSERT_DOUBLE_EQ(`_expected, actual_`);` | `EXPECT_DOUBLE_EQ(`_expected, actual_`);` | 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<T1, T2>(); -``` -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<T1, T2>()` is effective _only if_ -the function is instantiated. For example, given: -``` -template <typename T> class Foo { - public: - void Bar() { ::testing::StaticAssertTypeEq<int, T>(); } -}; -``` -the code: -``` -void Test1() { Foo<bool> foo; } -``` -will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never -actually instantiated. Instead, you need: -``` -void Test2() { Foo<bool> 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 <iostream> - -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 <iostream> - -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<pair<Bar, int> > 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 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: - -| `SCOPED_TRACE(`_message_`);` | -|:-----------------------------| - -where _message_ can be anything streamable to `std::ostream`. This -macro will cause the current file name, line number, and the given -message to be added in every failure message. 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! -} -``` - -Since we don't use exceptions, it is technically impossible to -implement the intended behavior here. To alleviate this, Google Test -provides two solutions. You could use either the -`(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the -`HasFatalFailure()` function. They are described in the following two -subsections. - -### 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: - -``` -... - <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest" - MaximumWidgets="12" - MinimumWidgets="9" /> -... -``` - -_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<T>` (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<T>`, -which itself is derived from both `::testing::Test` and -`::testing::WithParamInterface<T>`. `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<const char*> { - // You can implement all the usual fixture class members here. - // To access the test parameter, call GetParam() from class - // TestWithParam<T>. -}; - -// 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<const char*> { - ... -}; -``` - -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<T> 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 `<tr1/tuple>` 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 <i>abstract tests</i>. 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, he 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 <typename T> -class FooTest : public ::testing::Test { - public: - ... - typedef std::list<T> 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<char, int, unsigned int> 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` 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 <typename T> -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<char, int, unsigned int> 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 `TestCaseSetUp()`, -`TestCaseTearDown()` (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 <b>event listener API</b> 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#L855) -or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L905). -The former is an (abstract) interface, where <i>each pure virtual method<br> -can be overridden to handle a test event</i> (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#L1007) reflects the state of the entire test program, - * [TestCase](../include/gtest/gtest.h#L689) has information about a test case, which can contain one or more tests, - * [TestInfo](../include/gtest/gtest.h#L599) contains the state of a test, and - * [TestPartResult](../include/gtest/gtest-test-part.h#L42) 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#L929) -- 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.) - -### 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 [Jenkins](http://jenkins-ci.org/). Since that format -was originally intended for Java, a little interpretation is required -to make it apply to Google Test tests, as shown here: - -``` -<testsuites name="AllTests" ...> - <testsuite name="test_case_name" ...> - <testcase name="test_name" ...> - <failure message="..."/> - <failure message="..."/> - <failure message="..."/> - </testcase> - </testsuite> -</testsuites> -``` - - * The root `<testsuites>` element corresponds to the entire test program. - * `<testsuite>` elements correspond to Google Test test cases. - * `<testcase>` 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: - -``` -<?xml version="1.0" encoding="UTF-8"?> -<testsuites tests="3" failures="1" errors="0" time="35" name="AllTests"> - <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15"> - <testcase name="Addition" status="run" time="7" classname=""> - <failure message="Value of: add(1, 1)
 Actual: 3
Expected: 2" type=""/> - <failure message="Value of: add(1, -1)
 Actual: 1
Expected: 0" type=""/> - </testcase> - <testcase name="Subtraction" status="run" time="5" classname=""> - </testcase> - </testsuite> - <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5"> - <testcase name="NonContradiction" status="run" time="5" classname=""> - </testcase> - </testsuite> -</testsuites> -``` - -Things to note: - - * The `tests` attribute of a `<testsuites>` or `<testsuite>` 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 `<failure>` 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. - -## 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](V1_7_FAQ.md). diff --git a/googletest/docs/V1_7_Documentation.md b/googletest/docs/V1_7_Documentation.md deleted file mode 100644 index 282697a5..00000000 --- a/googletest/docs/V1_7_Documentation.md +++ /dev/null @@ -1,14 +0,0 @@ -This page lists all documentation wiki pages for Google Test **(the SVN trunk version)** --- **if you use a released version of Google Test, please read the -documentation for that specific version instead.** - - * [Primer](V1_7_Primer.md) -- start here if you are new to Google Test. - * [Samples](V1_7_Samples.md) -- learn from examples. - * [AdvancedGuide](V1_7_AdvancedGuide.md) -- learn more about Google Test. - * [XcodeGuide](V1_7_XcodeGuide.md) -- how to use Google Test in Xcode on Mac. - * [Frequently-Asked Questions](V1_7_FAQ.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Test, read: - - * [DevGuide](DevGuide.md) -- read this _before_ writing your first patch. - * [PumpManual](V1_7_PumpManual.md) -- how we generate some of Google Test's source files. \ No newline at end of file diff --git a/googletest/docs/V1_7_FAQ.md b/googletest/docs/V1_7_FAQ.md deleted file mode 100644 index 3dd914dc..00000000 --- a/googletest/docs/V1_7_FAQ.md +++ /dev/null @@ -1,1082 +0,0 @@ - - -If you cannot find the answer to your question here, and you have read -[Primer](V1_7_Primer.md) and [AdvancedGuide](V1_7_AdvancedGuide.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](V1_7_AdvancedGuide.md#global-set-up-and-tear-down) and tests parameterized by [values](V1_7_AdvancedGuide.md#value-parameterized-tests) or [types](V1_7_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](V1_7_AdvancedGuide.md#predicate-assertions-for-better-error-messages), - * teach Google Test how to [print your types](V1_7_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](V1_7_AdvancedGuide.md#catching-failures), and - * reflect on the test cases or change the test output format by intercepting the [test events](V1_7_AdvancedGuide.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 containers 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: -``` -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 his tests using the _same_ compiler -flags used to compile the installed Google Test libraries; otherwise -he 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 `<New...>` 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](../../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: -``` -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: - -``` -class FooTest : public ::testing::Test {}; - -TEST_F(FooTest, DoesThis) { ... } -``` -or -``` -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: -``` - 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, -``` - 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: - -``` -// foo.h -class Foo { - ... - static const int kBar = 100; -}; -``` - -You also need to define it _outside_ of the class body in `foo.cc`: - -``` -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: - -``` -// 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, call `TearDown()`, and then -_immediately_ delete the test fixture object. Therefore, there is no -need to write a `SetUp()` or `TearDown()` function if the constructor -or destructor already does the job. - -You may still want to use `SetUp()/TearDown()` in the following 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 overriden 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 - -``` -bool IsPositive(int n) { - return n > 0; -} -bool IsPositive(double x) { - return x > 0; -} -``` - -you will get a compiler error if you write - -``` -EXPECT_PRED1(IsPositive, 5); -``` - -However, this will work: - -``` -EXPECT_PRED1(*static_cast<bool (*)(int)>*(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 - -``` -template <typename T> -bool IsNegative(T x) { - return x < 0; -} -``` - -you can use it in a predicate assertion like this: - -``` -ASSERT_PRED1(IsNegative*<int>*, -5); -``` - -Things are more interesting if your template has more than one parameters. The -following won't compile: - -``` -ASSERT_PRED2(*GreaterThan<int, int>*, 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: - -``` -ASSERT_PRED2(*(GreaterThan<int, int>)*, 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 - -``` -return RUN_ALL_TESTS(); -``` - -they write - -``` -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. - -``` -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 - -``` -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: -``` -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: -``` -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: -``` -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: -``` -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: -``` -// 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: -``` -// 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](V1_7_AdvancedGuide.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: -``` -// 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: - -``` -// 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](V1_7_AdvancedGuide.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: - -``` -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: - -``` -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](V1_7_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 the posted his solution to -our mailing list. Here is his link: -http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html. - -## 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 runing this commad: - -`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 -``` - GTEST_TEST(SomeTest, DoesThis) { ... } -``` -instead of -``` - TEST(SomeTest, DoesThis) { ... } -``` -in order to define a test. - -Currently, the following `TEST`, `FAIL`, `SUCCEED`, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros [here](http://www.google.com/codesearch?q=if+!GTEST_DONT_DEFINE_\w%2B+package:http://googletest\.googlecode\.com+file:/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`). - -``` -namespace foo { -TEST(CoolTest, DoSomething) { - SUCCEED(); -} -} // namespace foo - -namespace bar { -TEST(CoolTest, DoSomething) { - SUCCEED(); -} -} // namespace foo -``` - -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. - -``` -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 foo -``` - -## 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. - -## 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](http://code.google.com/p/googletest/w/list), - 1. search the mailing list [archive](http://groups.google.com/group/googletestframework/topics), - 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](http://code.google.com/p/googletest/issues/list) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google 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/V1_7_Primer.md b/googletest/docs/V1_7_Primer.md deleted file mode 100644 index b1827c73..00000000 --- a/googletest/docs/V1_7_Primer.md +++ /dev/null @@ -1,501 +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_. - -# 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(`_expected_`, `_actual_`);`|`EXPECT_EQ(`_expected_`, `_actual_`);`| _expected_ `==` _actual_ | -|`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_ -. In `ASSERT_EQ*` and `EXPECT_EQ*` (and all other equality assertions -we'll introduce later), you should put the expression you want to test -in the position of _actual_, and put its expected value in _expected_, -as Google Test's failure messages are optimized for this convention. - -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. - -## 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(`_expected\_str_`, `_actual\_str_`);` | `EXPECT_STREQ(`_expected\_str_`, `_actual\_str_`);` | 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(`_expected\_str_`, `_actual\_str_`);`| `EXPECT_STRCASEEQ(`_expected\_str_`, `_actual\_str_`);` | 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](V1_7_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(test_case_name, test_name) { - ... 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](V1_7_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 <typename E> // 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<int> q0_; - Queue<int> q1_; - Queue<int> 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 text 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](V1_7_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](V1_7_Samples.md), or continue with -[AdvancedGuide](V1_7_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/V1_7_PumpManual.md b/googletest/docs/V1_7_PumpManual.md deleted file mode 100644 index 8184f153..00000000 --- a/googletest/docs/V1_7_PumpManual.md +++ /dev/null @@ -1,177 +0,0 @@ - - -<b>P</b>ump is <b>U</b>seful for <b>M</b>eta <b>P</b>rogramming. - -# The Problem # - -Template and macro libraries often need to define many classes, -functions, or macros that vary only (or almost only) in the number of -arguments they take. It's a lot of repetitive, mechanical, and -error-prone work. - -Variadic templates and variadic macros can alleviate the problem. -However, while both are being considered by the C++ committee, neither -is in the standard yet or widely supported by compilers. Thus they -are often not a good choice, especially when your code needs to be -portable. And their capabilities are still limited. - -As a result, authors of such libraries often have to write scripts to -generate their implementation. However, our experience is that it's -tedious to write such scripts, which tend to reflect the structure of -the generated code poorly and are often hard to read and edit. For -example, a small change needed in the generated code may require some -non-intuitive, non-trivial changes in the script. This is especially -painful when experimenting with the code. - -# Our Solution # - -Pump (for Pump is Useful for Meta Programming, Pretty Useful for Meta -Programming, or Practical Utility for Meta Programming, whichever you -prefer) is a simple meta-programming tool for C++. The idea is that a -programmer writes a `foo.pump` file which contains C++ code plus meta -code that manipulates the C++ code. The meta code can handle -iterations over a range, nested iterations, local meta variable -definitions, simple arithmetic, and conditional expressions. You can -view it as a small Domain-Specific Language. The meta language is -designed to be non-intrusive (s.t. it won't confuse Emacs' C++ mode, -for example) and concise, making Pump code intuitive and easy to -maintain. - -## Highlights ## - - * The implementation is in a single Python script and thus ultra portable: no build or installation is needed and it works cross platforms. - * Pump tries to be smart with respect to [Google's style guide](http://code.google.com/p/google-styleguide/): it breaks long lines (easy to have when they are generated) at acceptable places to fit within 80 columns and indent the continuation lines correctly. - * The format is human-readable and more concise than XML. - * The format works relatively well with Emacs' C++ mode. - -## Examples ## - -The following Pump code (where meta keywords start with `$`, `[[` and `]]` are meta brackets, and `$$` starts a meta comment that ends with the line): - -``` -$var n = 3 $$ Defines a meta variable n. -$range i 0..n $$ Declares the range of meta iterator i (inclusive). -$for i [[ - $$ Meta loop. -// Foo$i does blah for $i-ary predicates. -$range j 1..i -template <size_t N $for j [[, typename A$j]]> -class Foo$i { -$if i == 0 [[ - blah a; -]] $elif i <= 2 [[ - blah b; -]] $else [[ - blah c; -]] -}; - -]] -``` - -will be translated by the Pump compiler to: - -``` -// Foo0 does blah for 0-ary predicates. -template <size_t N> -class Foo0 { - blah a; -}; - -// Foo1 does blah for 1-ary predicates. -template <size_t N, typename A1> -class Foo1 { - blah b; -}; - -// Foo2 does blah for 2-ary predicates. -template <size_t N, typename A1, typename A2> -class Foo2 { - blah b; -}; - -// Foo3 does blah for 3-ary predicates. -template <size_t N, typename A1, typename A2, typename A3> -class Foo3 { - blah c; -}; -``` - -In another example, - -``` -$range i 1..n -Func($for i + [[a$i]]); -$$ The text between i and [[ is the separator between iterations. -``` - -will generate one of the following lines (without the comments), depending on the value of `n`: - -``` -Func(); // If n is 0. -Func(a1); // If n is 1. -Func(a1 + a2); // If n is 2. -Func(a1 + a2 + a3); // If n is 3. -// And so on... -``` - -## Constructs ## - -We support the following meta programming constructs: - -| `$var id = exp` | Defines a named constant value. `$id` is valid util the end of the current meta lexical block. | -|:----------------|:-----------------------------------------------------------------------------------------------| -| `$range id exp..exp` | Sets the range of an iteration variable, which can be reused in multiple loops later. | -| `$for id sep [[ code ]]` | Iteration. The range of `id` must have been defined earlier. `$id` is valid in `code`. | -| `$($)` | Generates a single `$` character. | -| `$id` | Value of the named constant or iteration variable. | -| `$(exp)` | Value of the expression. | -| `$if exp [[ code ]] else_branch` | Conditional. | -| `[[ code ]]` | Meta lexical block. | -| `cpp_code` | Raw C++ code. | -| `$$ comment` | Meta comment. | - -**Note:** To give the user some freedom in formatting the Pump source -code, Pump ignores a new-line character if it's right after `$for foo` -or next to `[[` or `]]`. Without this rule you'll often be forced to write -very long lines to get the desired output. Therefore sometimes you may -need to insert an extra new-line in such places for a new-line to show -up in your output. - -## Grammar ## - -``` -code ::= atomic_code* -atomic_code ::= $var id = exp - | $var id = [[ code ]] - | $range id exp..exp - | $for id sep [[ code ]] - | $($) - | $id - | $(exp) - | $if exp [[ code ]] else_branch - | [[ code ]] - | cpp_code -sep ::= cpp_code | empty_string -else_branch ::= $else [[ code ]] - | $elif exp [[ code ]] else_branch - | empty_string -exp ::= simple_expression_in_Python_syntax -``` - -## Code ## - -You can find the source code of Pump in [scripts/pump.py](../scripts/pump.py). It is still -very unpolished and lacks automated tests, although it has been -successfully used many times. If you find a chance to use it in your -project, please let us know what you think! We also welcome help on -improving Pump. - -## Real Examples ## - -You can find real-world applications of Pump in [Google Test](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgoogletest\.googlecode\.com) and [Google Mock](http://www.google.com/codesearch?q=file%3A\.pump%24+package%3Ahttp%3A%2F%2Fgooglemock\.googlecode\.com). The source file `foo.h.pump` generates `foo.h`. - -## Tips ## - - * If a meta variable is followed by a letter or digit, you can separate them using `[[]]`, which inserts an empty string. For example `Foo$j[[]]Helper` generate `Foo1Helper` when `j` is 1. - * To avoid extra-long Pump source lines, you can break a line anywhere you want by inserting `[[]]` followed by a new line. Since any new-line character next to `[[` or `]]` is ignored, the generated code won't contain this new line. diff --git a/googletest/docs/V1_7_Samples.md b/googletest/docs/V1_7_Samples.md deleted file mode 100644 index f21d2005..00000000 --- a/googletest/docs/V1_7_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/V1_7_XcodeGuide.md b/googletest/docs/V1_7_XcodeGuide.md deleted file mode 100644 index bf24bf51..00000000 --- a/googletest/docs/V1_7_XcodeGuide.md +++ /dev/null @@ -1,93 +0,0 @@ - - -This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. - -# Quick Start # - -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. 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" - 1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" - 1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. - 1. Build and Go - -The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. - -# 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: - -``` -svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only -``` - -Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. - -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`). - -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. - -``` -[Computer:svn] user$ svn propget svn:externals trunk -externals/src/googletest http://googletest.googlecode.com/svn/trunk -``` - -# Add the Framework to Your Project # - -The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. - - * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. - * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). - -# Make a Test Target # - -To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. - -Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. - - * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. - * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. - -# Set Up the Executable Run Environment # - -Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. - -If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: - -``` -[Session started at 2008-08-15 06:23:57 -0600.] - dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest - Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest - Reason: image not found -``` - -To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. - -# Build and Go # - -Now, when you click "Build and Go", the test will be executed. Dumping out something like this: - -``` -[Session started at 2008-08-06 06:36:13 -0600.] -[==========] Running 2 tests from 1 test case. -[----------] Global test environment set-up. -[----------] 2 tests from WidgetInitializerTest -[ RUN ] WidgetInitializerTest.TestConstructor -[ OK ] WidgetInitializerTest.TestConstructor -[ RUN ] WidgetInitializerTest.TestConversion -[ OK ] WidgetInitializerTest.TestConversion -[----------] Global test environment tear-down -[==========] 2 tests from 1 test case ran. -[ PASSED ] 2 tests. - -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 diff --git a/googletest/docs/XcodeGuide.md b/googletest/docs/XcodeGuide.md index bf24bf51..117265c5 100644 --- a/googletest/docs/XcodeGuide.md +++ b/googletest/docs/XcodeGuide.md @@ -1,93 +1,93 @@ This guide will explain how to use the Google Testing Framework in your Xcode projects on Mac OS X. This tutorial begins by quickly explaining what to do for experienced users. After the quick start, the guide goes provides additional explanation about each step. # Quick Start # 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](http://code.google.com/p/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" - 1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests" + 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". + 1. Add your unit test source code to the "Compile Sources" build phase of "UnitTests". 1. Edit the "UnitTests" executable and add an environment variable named "DYLD\_FRAMEWORK\_PATH" with a value equal to the path to the framework containing the gtest.framework relative to the compiled executable. - 1. Build and Go + 1. Build and Go. The following sections further explain each of the steps listed above in depth, describing in more detail how to complete it including some variations. # 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: ``` svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only ``` Alternatively, if you are working with Subversion in your own code base, you can add Google Test as an external dependency to your own Subversion repository. By following this approach, everyone that checks out your svn repository will also receive a copy of Google Test (a specific version, if you wish) without having to check it out explicitly. This makes the set up of your project simpler and reduces the copied code in the repository. 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`). 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. ``` [Computer:svn] user$ svn propget svn:externals trunk externals/src/googletest http://googletest.googlecode.com/svn/trunk ``` # Add the Framework to Your Project # The next step is to build and add the gtest.framework to your own project. This guide describes two common ways below. * **Option 1** --- The simplest way to add Google Test to your own project, is to open gtest.xcodeproj (found in the xcode/ directory of the Google Test trunk) and build the framework manually. Then, add the built framework into your project using the "Add->Existing Framework..." from the context menu or "Project->Add..." from the main menu. The gtest.framework is relocatable and contains the headers and object code that you'll need to make tests. This method requires rebuilding every time you upgrade Google Test in your project. * **Option 2** --- If you are going to be living off the trunk of Google Test, incorporating its latest features into your unit tests (or are a Google Test developer yourself). You'll want to rebuild the framework every time the source updates. to do this, you'll need to add the gtest.xcodeproj file, not the framework itself, to your own Xcode project. Then, from the build products that are revealed by the project's disclosure triangle, you can find the gtest.framework, which can be added to your targets (discussed below). # Make a Test Target # To start writing tests, make a new "Shell Tool" target. This target template is available under BSD, Cocoa, or Carbon. Add your unit test source code to the "Compile Sources" build phase of the target. Next, you'll want to add gtest.framework in two different ways, depending upon which option you chose above. * **Option 1** --- During compilation, Xcode will need to know that you are linking against the gtest.framework. Add the gtest.framework to the "Link Binary with Libraries" build phase of your test target. This will include the Google Test headers in your header search path, and will tell the linker where to find the library. * **Option 2** --- If your working out of the trunk, you'll also want to add gtest.framework to your "Link Binary with Libraries" build phase of your test target. In addition, you'll want to add the gtest.framework as a dependency to your unit test target. This way, Xcode will make sure that gtest.framework is up to date, every time your build your target. Finally, if you don't share build directories with Google Test, you'll have to copy the gtest.framework into your own build products directory using a "Run Script" build phase. # Set Up the Executable Run Environment # Since the unit test executable is a shell tool, it doesn't have a bundle with a `Contents/Frameworks` directory, in which to place gtest.framework. Instead, the dynamic linker must be told at runtime to search for the framework in another location. This can be accomplished by setting the "DYLD\_FRAMEWORK\_PATH" environment variable in the "Edit Active Executable ..." Arguments tab, under "Variables to be set in the environment:". The path for this value is the path (relative or absolute) of the directory containing the gtest.framework. If you haven't set up the DYLD\_FRAMEWORK\_PATH, correctly, you might get a message like this: ``` [Session started at 2008-08-15 06:23:57 -0600.] dyld: Library not loaded: @loader_path/../Frameworks/gtest.framework/Versions/A/gtest Referenced from: /Users/username/Documents/Sandbox/gtestSample/build/Debug/WidgetFrameworkTest Reason: image not found ``` -To correct this problem, got to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. +To correct this problem, go to to the directory containing the executable named in "Referenced from:" value in the error message above. Then, with the terminal in this location, find the relative path to the directory containing the gtest.framework. That is the value you'll need to set as the DYLD\_FRAMEWORK\_PATH. # Build and Go # Now, when you click "Build and Go", the test will be executed. Dumping out something like this: ``` [Session started at 2008-08-06 06:36:13 -0600.] [==========] Running 2 tests from 1 test case. [----------] Global test environment set-up. [----------] 2 tests from WidgetInitializerTest [ RUN ] WidgetInitializerTest.TestConstructor [ OK ] WidgetInitializerTest.TestConstructor [ RUN ] WidgetInitializerTest.TestConversion [ OK ] WidgetInitializerTest.TestConversion [----------] Global test environment tear-down [==========] 2 tests from 1 test case ran. [ PASSED ] 2 tests. 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 diff --git a/googletest/include/gtest/internal/gtest-port.h b/googletest/include/gtest/internal/gtest-port.h index 7e008c05..c2a9f5f3 100644 --- a/googletest/include/gtest/internal/gtest-port.h +++ b/googletest/include/gtest/internal/gtest-port.h @@ -1,2597 +1,2598 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: wan@google.com (Zhanyong Wan) // // Low-level types and utilities for porting Google Test to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't // end with _ are part of Google Test's public API and can be used by // code outside Google Test. // // This file is fundamental to Google Test. All other Google Test source // files are expected to #include this. Therefore, it cannot #include // any other Google Test header. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ // Environment-describing macros // ----------------------------- // // Google Test can be used in many different environments. Macros in // this section tell Google Test what kind of environment it is being // used in, such that Google Test can provide environment-specific // features and implementations. // // Google Test tries to automatically detect the properties of its // environment, so users usually don't need to worry about these // macros. However, the automatic detection is not perfect. // Sometimes it's necessary for a user to define some of the following // macros in the build script to override Google Test's decisions. // // If the user doesn't define a macro in the list, Google Test will // provide a default definition. After this header is #included, all // macros in this list will be defined to either 1 or 0. // // Notes to maintainers: // - Each macro here is a user-tweakable knob; do not grow the list // lightly. // - Use #if to key off these macros. Don't use #ifdef or "#if // defined(...)", which will not work as these macros are ALWAYS // defined. // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // are enabled. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::string, which is different to std::string). // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::wstring, which is different to std::wstring). // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // expressions are/aren't available. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h> // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't // enabled. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // std::wstring does/doesn't work (Google Test can // be used where std::wstring is unavailable). // GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple // is/isn't available. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // compiler supports Microsoft's "Structured // Exception Handling". // GTEST_HAS_STREAM_REDIRECTION // - Define it to 1/0 to indicate whether the // platform supports I/O stream redirection using // dup() and dup2(). // GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google // Test's own tr1 tuple implementation should be // used. Unused when the user sets // GTEST_HAS_TR1_TUPLE to 0. // GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test // is building in C++11/C++98 mode. // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as // DLL on Windows). // GTEST_CREATE_SHARED_LIBRARY // - Define to 1 when compiling Google Test itself // as a shared library. // Platform-indicating macros // -------------------------- // // Macros indicating the platform on which Google Test is being used // (a macro is defined to 1 if compiled on the given platform; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_FREEBSD - FreeBSD // GTEST_OS_HPUX - HP-UX // GTEST_OS_LINUX - Linux // GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_MAC - Mac OS X // GTEST_OS_IOS - iOS // GTEST_OS_NACL - Google Native Client (NaCl) // GTEST_OS_NETBSD - NetBSD // GTEST_OS_OPENBSD - OpenBSD // GTEST_OS_QNX - QNX // GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_SYMBIAN - Symbian // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MOBILE - Windows Mobile // GTEST_OS_WINDOWS_PHONE - Windows Phone // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the // most stable support. Since core members of the Google Test project // don't have access to other platforms, support for them may be less // stable. If you notice any problems on your platform, please notify // googletestframework@googlegroups.com (patches for fixing them are // even more welcome!). // // It is possible that none of the GTEST_OS_* macros are defined. // Feature-indicating macros // ------------------------- // // Macros indicating which Google Test features are available (a macro // is defined to 1 if the corresponding feature is supported; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // These macros are public so that portable tests can be written. // Such tests typically surround code using a feature with an #if // which controls that code. For example: // // #if GTEST_HAS_DEATH_TEST // EXPECT_DEATH(DoSomethingDeadly()); // #endif // // GTEST_HAS_COMBINE - the Combine() function (for value-parameterized // tests) // GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_PARAM_TEST - value-parameterized tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_IS_THREADSAFE - Google Test is thread-safe. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above two are mutually exclusive. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // Misc public macros // ------------------ // // GTEST_FLAG(flag_name) - references the variable corresponding to // the given Google Test flag. // Internal utilities // ------------------ // // The following macros and utilities are for Google Test's INTERNAL // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. // GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 // is suppressed. // // C++11 feature wrappers: // // testing::internal::move - portability wrapper for std::move. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() // - synchronization primitives. // // Template meta programming: // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. // IteratorTraits - partial implementation of std::iterator_traits, which // is not available in libCstd when compiled with Sun C++. // // Smart pointers: // scoped_ptr - as in TR2. // // Regular expressions: // RE - a simple regular expression class using the POSIX // Extended Regular Expression syntax on UNIX-like // platforms, or a reduced regular exception syntax on // other platforms, including Windows. // // Logging: // GTEST_LOG_() - logs messages at the specified severity level. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. // // Stdout and stderr capturing: // CaptureStdout() - starts capturing stdout. // GetCapturedStdout() - stops capturing stdout and returns the captured // string. // CaptureStderr() - starts capturing stderr. // GetCapturedStderr() - stops capturing stderr and returns the captured // string. // // Integer types: // TypeWithSize - maps an integer to a int type. // Int32, UInt32, Int64, UInt64, TimeInMillis // - integers of known sizes. // BiggestInt - the biggest signed integer type. // // Command-line utilities: // GTEST_DECLARE_*() - declares a flag. // GTEST_DEFINE_*() - defines a flag. // GetInjectableArgvs() - returns the command line as a vector of strings. // // Environment variable utilities: // GetEnv() - gets the value of an environment variable. // BoolFromGTestEnv() - parses a bool environment variable. // Int32FromGTestEnv() - parses an Int32 environment variable. // StringFromGTestEnv() - parses a string environment variable. #include <ctype.h> // for isspace, etc #include <stddef.h> // for ptrdiff_t #include <stdlib.h> #include <stdio.h> #include <string.h> #ifndef _WIN32_WCE # include <sys/types.h> # include <sys/stat.h> #endif // !_WIN32_WCE #if defined __APPLE__ # include <AvailabilityMacros.h> # include <TargetConditionals.h> #endif #include <algorithm> // NOLINT #include <iostream> // NOLINT #include <sstream> // NOLINT #include <string> // NOLINT #include <utility> #include <vector> // NOLINT #include "gtest/internal/gtest-port-arch.h" #include "gtest/internal/custom/gtest-port.h" #if !defined(GTEST_DEV_EMAIL_) # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" # define GTEST_FLAG_PREFIX_ "gtest_" # define GTEST_FLAG_PREFIX_DASH_ "gtest-" # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" # define GTEST_NAME_ "Google Test" # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. # define GTEST_GCC_VER_ \ (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. // // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() #if _MSC_VER >= 1500 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ __pragma(warning(push)) \ __pragma(warning(disable: warnings)) # define GTEST_DISABLE_MSC_WARNINGS_POP_() \ __pragma(warning(pop)) #else // Older versions of MSVC don't have __pragma. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) # define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif #ifndef GTEST_LANG_CXX11 // gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when // -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a // value for __cplusplus, and recent versions of clang, gcc, and // probably other compilers set that too in C++11 mode. # if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L // Compiling in at least C++11 mode. # define GTEST_LANG_CXX11 1 # else # define GTEST_LANG_CXX11 0 # endif #endif // Distinct from C++11 language support, some environments don't provide // proper C++11 library support. Notably, it's possible to build in // C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++ // with no C++11 support. // // libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__ // 20110325, but maintenance releases in the 4.4 and 4.5 series followed // this date, so check for those versions by their date stamps. // https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning #if GTEST_LANG_CXX11 && \ (!defined(__GLIBCXX__) || ( \ __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ /* Blacklist of patch releases of older branches: */ \ __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ # define GTEST_STDLIB_CXX11 1 #endif // Only use C++11 library features if the library provides them. #if GTEST_STDLIB_CXX11 # define GTEST_HAS_STD_BEGIN_AND_END_ 1 # define GTEST_HAS_STD_FORWARD_LIST_ 1 # define GTEST_HAS_STD_FUNCTION_ 1 # define GTEST_HAS_STD_INITIALIZER_LIST_ 1 # define GTEST_HAS_STD_MOVE_ 1 # define GTEST_HAS_STD_SHARED_PTR_ 1 # define GTEST_HAS_STD_TYPE_TRAITS_ 1 # define GTEST_HAS_STD_UNIQUE_PTR_ 1 #endif // C++11 specifies that <tuple> provides std::tuple. // Some platforms still might not have it, however. #if GTEST_LANG_CXX11 # define GTEST_HAS_STD_TUPLE_ 1 # if defined(__clang__) // Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include # if defined(__has_include) && !__has_include(<tuple>) # undef GTEST_HAS_STD_TUPLE_ # endif # elif defined(_MSC_VER) // Inspired by boost/config/stdlib/dinkumware.hpp # if defined(_CPPLIB_VER) && _CPPLIB_VER < 520 # undef GTEST_HAS_STD_TUPLE_ # endif # 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 # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) # undef GTEST_HAS_STD_TUPLE_ # endif # endif #endif // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. #if GTEST_OS_WINDOWS # if !GTEST_OS_WINDOWS_MOBILE # include <direct.h> # include <io.h> # endif // In order to avoid having to include <windows.h>, use forward declaration #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) // MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two // separate (equivalent) structs, instead of using typedef typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION; #else // Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. // This assumption is verified by // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #endif #else // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. # include <unistd.h> # include <strings.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. # include <android/api-level.h> // NOLINT #endif // Defines this to true iff Google Test can use POSIX regular expressions. #ifndef GTEST_HAS_POSIX_RE # if GTEST_OS_LINUX_ANDROID // On Android, <regex.h> is only available starting with Gingerbread. # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) # else # define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) # endif #endif #if GTEST_USES_PCRE // The appropriate headers have already been included. #elif GTEST_HAS_POSIX_RE // On some platforms, <regex.h> needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already // included <stdlib.h>, which is guaranteed to define size_t through // <stddef.h>. # include <regex.h> // NOLINT # define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS // <regex.h> is not available on Windows. Use our own simple regex // implementation instead. # define GTEST_USES_SIMPLE_RE 1 #else // <regex.h> may not be available on this platform. Use our own // simple regex implementation instead. # define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_USES_PCRE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. # ifndef _HAS_EXCEPTIONS # define _HAS_EXCEPTIONS 1 # endif // _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS # elif defined(__clang__) // clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, // but iff cleanups are enabled after that. In Obj-C++ files, there can be // cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions // are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ // exceptions starting at clang r206352, but which checked for cleanups prior to // that. To reliably check for C++ exception availability with clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) # elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. # define GTEST_HAS_EXCEPTIONS 1 # else // For other compilers, we assume exceptions are disabled to be // conservative. # define GTEST_HAS_EXCEPTIONS 0 # endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #if !defined(GTEST_HAS_STD_STRING) // Even though we don't use this macro any longer, we keep it in case // some clients still depend on it. # define GTEST_HAS_STD_STRING 1 #elif !GTEST_HAS_STD_STRING // The user told us that ::std::string isn't available. # error "Google Test cannot be used where ::std::string isn't available." #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 // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. // TODO(wan@google.com): uses autoconf to detect whether ::std::wstring // is available. // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). # define GTEST_HAS_STD_WSTRING \ (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) #endif // GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_GLOBAL_WSTRING // The user didn't tell us whether ::wstring is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_WSTRING \ (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) #endif // GTEST_HAS_GLOBAL_WSTRING // Determines whether RTTI is available. #ifndef GTEST_HAS_RTTI // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. # ifdef _MSC_VER # ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) # ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ !defined(__EXCEPTIONS) # define GTEST_HAS_RTTI 0 # else # define GTEST_HAS_RTTI 1 # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS # else # define GTEST_HAS_RTTI 0 # endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. # elif defined(__clang__) # define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) # ifdef __RTTI_ALL__ # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif # else // For all other compilers, we assume RTTI is enabled. # define GTEST_HAS_RTTI 1 # endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include <typeinfo> when RTTI // is enabled. #if GTEST_HAS_RTTI # include <typeinfo> #endif // Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD // The user didn't tell us explicitly, so we make reasonable assumptions about // which platforms have pthreads support. // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. # define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is // true. # include <pthread.h> // NOLINT // For timespec and nanosleep, used below. # include <time.h> // NOLINT #endif // Determines if hash_map/hash_set are available. // Only used for testing against those containers. #if !defined(GTEST_HAS_HASH_MAP_) # if defined(_MSC_VER) && (_MSC_VER < 1900) # define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. # define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. # endif // _MSC_VER #endif // !defined(GTEST_HAS_HASH_MAP_) // Determines whether Google Test can use tr1/tuple. You can define // this macro to 0 to prevent Google Test from using tuple (any // feature depending on tuple with be disabled in this mode). #ifndef GTEST_HAS_TR1_TUPLE # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) // STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>. # define GTEST_HAS_TR1_TUPLE 0 # else // The user didn't tell us not to do it, so we assume it's OK. # define GTEST_HAS_TR1_TUPLE 1 # endif #endif // GTEST_HAS_TR1_TUPLE // Determines whether Google Test's own tr1 tuple implementation // should be used. #ifndef GTEST_USE_OWN_TR1_TUPLE // The user didn't tell us, so we need to figure it out. // We use our own TR1 tuple if we aren't sure the user has an // implementation of it already. At this time, libstdc++ 4.0.0+ and // MSVC 2010 are the only mainstream standard libraries that come // with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler // pretends to be GCC by defining __GNUC__ and friends, but cannot // compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1 // tuple in a 323 MB Feature Pack download, which we cannot assume the // user has. QNX's QCC compiler is a modified GCC but it doesn't // support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, // and it can be used with some compilers that define __GNUC__. # if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 # define GTEST_ENV_HAS_TR1_TUPLE_ 1 # endif // C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 // can build with clang but need to use gcc4.2's libstdc++). # if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) # define GTEST_ENV_HAS_STD_TUPLE_ 1 # endif # if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ # define GTEST_USE_OWN_TR1_TUPLE 0 # else # define GTEST_USE_OWN_TR1_TUPLE 1 # endif #endif // GTEST_USE_OWN_TR1_TUPLE // To avoid conditional compilation everywhere, we make it // gtest-port.h's responsibility to #include the header implementing // tuple. #if GTEST_HAS_STD_TUPLE_ # include <tuple> // IWYU pragma: export # define GTEST_TUPLE_NAMESPACE_ ::std #endif // GTEST_HAS_STD_TUPLE_ // We include tr1::tuple even if std::tuple is available to define printers for // them. #if GTEST_HAS_TR1_TUPLE # ifndef GTEST_TUPLE_NAMESPACE_ # define GTEST_TUPLE_NAMESPACE_ ::std::tr1 # endif // GTEST_TUPLE_NAMESPACE_ # if GTEST_USE_OWN_TR1_TUPLE # include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT # elif GTEST_ENV_HAS_STD_TUPLE_ # include <tuple> // C++11 puts its tuple into the ::std namespace rather than // ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. // This causes undefined behavior, but supported compilers react in // the way we intend. namespace std { namespace tr1 { using ::std::get; using ::std::make_tuple; using ::std::tuple; using ::std::tuple_element; using ::std::tuple_size; } } # elif GTEST_OS_SYMBIAN // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to // use STLport's tuple implementation, which unfortunately doesn't // work as the copy of STLport distributed with Symbian is incomplete. // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to // use its own tuple implementation. # ifdef BOOST_HAS_TR1_TUPLE # undef BOOST_HAS_TR1_TUPLE # endif // BOOST_HAS_TR1_TUPLE // This prevents <boost/tr1/detail/config.hpp>, which defines // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>. # define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED # include <tuple> // IWYU pragma: export // NOLINT # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header. This does // not conform to the TR1 spec, which requires the header to be <tuple>. # if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 // Until version 4.3.2, gcc has a bug that causes <tr1/functional>, // which is #included by <tr1/tuple>, to not compile when RTTI is // disabled. _TR1_FUNCTIONAL is the header guard for // <tr1/functional>. Hence the following #define is a hack to prevent // <tr1/functional> from being included. # define _TR1_FUNCTIONAL 1 # include <tr1/tuple> # undef _TR1_FUNCTIONAL // Allows the user to #include // <tr1/functional> if he chooses to. # else # include <tr1/tuple> // NOLINT # endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 # else // If the compiler is not GCC 4.0+, we assume the user is using a // spec-conforming TR1 implementation. # include <tuple> // IWYU pragma: export // NOLINT # endif // GTEST_USE_OWN_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. // Also see http://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. # if GTEST_OS_LINUX && !defined(__ia64__) # if GTEST_OS_LINUX_ANDROID // On Android, clone() became available at different API levels for each 32-bit // architecture. # if defined(__LP64__) || \ (defined(__arm__) && __ANDROID_API__ >= 9) || \ (defined(__mips__) && __ANDROID_API__ >= 12) || \ (defined(__i386__) && __ANDROID_API__ >= 17) # define GTEST_HAS_CLONE 1 # else # define GTEST_HAS_CLONE 0 # endif # else # define GTEST_HAS_CLONE 1 # endif # else # define GTEST_HAS_CLONE 0 # endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE // Determines whether to support stream redirection. This is used to test // output correctness and to implement death tests. #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 # endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // Google Test does not support death tests for VC 7.1 and earlier as // abort() in a VC 7.1 application compiled as GUI in debug config // pops up a dialog window that cannot be suppressed programmatically. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ (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_NETBSD) # define GTEST_HAS_DEATH_TEST 1 #endif // We don't support MSVC 7.1 with exceptions disabled now. Therefore // all the compilers we care about are adequate for supporting // value-parameterized tests. #define GTEST_HAS_PARAM_TEST 1 // Determines whether to support type-driven tests. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0, // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) # define GTEST_HAS_TYPED_TEST 1 # define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether to support Combine(). This only makes sense when // value-parameterized tests are enabled. The implementation doesn't // work on Sun Studio since it doesn't understand templated conversion // operators. #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) # define GTEST_HAS_COMBINE 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX # define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. // The GNU compiler emits a warning if nested "if" statements are followed by // an "else" statement and braces are not used to explicitly disambiguate the // "else" binding. This leads to problems with code like: // // if (gate) // ASSERT_*(condition) << "Some message"; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to // prevent the compiler from optimizing away instances that are never // used. This is useful when all interesting logic happens inside the // c'tor and / or d'tor. Example: // // struct Foo { // Foo() { ... } // } GTEST_ATTRIBUTE_UNUSED_; // // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) #elif defined(__clang__) # if __has_attribute(unused) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) # endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ # define GTEST_ATTRIBUTE_UNUSED_ #endif // Use this annotation before a function that takes a printf format string. #if defined(__GNUC__) && !defined(COMPILER_ICC) # if defined(__MINGW_PRINTF_FORMAT) // MinGW has two different printf implementations. Ensure the format macro // matches the selected implementation. See // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \ first_to_check))) # else # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ __attribute__((__format__(__printf__, string_index, first_to_check))) # endif #else # define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) #endif // A macro to disallow operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type)\ void operator=(type const &) // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ type(type const &);\ GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations // following the argument list: // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) #else # define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time // constant. In some contexts this warning is false positive and needs to be // suppressed. Use the following two macros in such cases: // // GTEST_INTENTIONAL_CONST_COND_PUSH_() // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) # define GTEST_INTENTIONAL_CONST_COND_POP_() \ GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally // does not exist on any other system. #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. # define GTEST_HAS_SEH 1 # else // Assume no SEH. # define GTEST_HAS_SEH 0 # endif #define GTEST_IS_THREADSAFE \ (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \ || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \ || GTEST_HAS_PTHREAD) #endif // GTEST_HAS_SEH // GTEST_API_ qualifies all symbols that must be exported. The definitions below // are guarded by #ifndef to give embedders a chance to define GTEST_API_ in // gtest/internal/custom/gtest-port.h #ifndef GTEST_API_ #ifdef _MSC_VER # if GTEST_LINKED_AS_SHARED_LIBRARY # define GTEST_API_ __declspec(dllimport) # elif GTEST_CREATE_SHARED_LIBRARY # define GTEST_API_ __declspec(dllexport) # endif #elif __GNUC__ >= 4 || defined(__clang__) # define GTEST_API_ __attribute__((visibility ("default"))) #endif // _MSC_VER #endif // GTEST_API_ #ifndef GTEST_API_ # define GTEST_API_ #endif // GTEST_API_ #ifdef __GNUC__ // Ask the compiler to never inline a given function. # define GTEST_NO_INLINE_ __attribute__((noinline)) #else # define GTEST_NO_INLINE_ #endif // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) # define GTEST_HAS_CXXABI_H_ 1 #else # define GTEST_HAS_CXXABI_H_ 0 #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) # if __has_feature(memory_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ __attribute__((no_sanitize_memory)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ # endif // __has_feature(memory_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) # if __has_feature(address_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ __attribute__((no_sanitize_address)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ # endif // __has_feature(address_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) # if __has_feature(thread_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ __attribute__((no_sanitize_thread)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ # endif // __has_feature(thread_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { class Message; #if defined(GTEST_TUPLE_NAMESPACE_) // Import tuple and friends into the ::testing namespace. // It is part of our interface, having them in ::testing allows us to change // their types as needed. using GTEST_TUPLE_NAMESPACE_::get; using GTEST_TUPLE_NAMESPACE_::make_tuple; using GTEST_TUPLE_NAMESPACE_::tuple; using GTEST_TUPLE_NAMESPACE_::tuple_size; using GTEST_TUPLE_NAMESPACE_::tuple_element; #endif // defined(GTEST_TUPLE_NAMESPACE_) namespace internal { // A secret type that Google Test users don't know about. It has no // definition on purpose. Therefore it's impossible to create a // Secret object, which is what we want. class Secret; // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, // names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // // GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); // // The second argument to the macro is the name of the variable. If // the expression is false, most compilers will issue a warning/error // containing the name of the variable. #if GTEST_LANG_CXX11 # define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) #else // !GTEST_LANG_CXX11 template <bool> struct CompileAssert { }; # define GTEST_COMPILE_ASSERT_(expr, msg) \ typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \ msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ #endif // !GTEST_LANG_CXX11 // Implementation details of GTEST_COMPILE_ASSERT_: // // (In C++11, we simply use static_assert instead of the following) // // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 // elements (and thus is invalid) when the expression is false. // // - The simpler definition // // #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] // // does not work, as gcc supports variable-length arrays whose sizes // are determined at run-time (this is gcc's extension and not part // of the C++ standard). As a result, gcc fails to reject the // following code with the simple definition: // // int foo; // GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is // // not a compile-time constant. // // - By using the type CompileAssert<(bool(expr))>, we ensures that // expr is a compile-time constant. (Template arguments must be // determined at compile-time.) // // - The outter parentheses in CompileAssert<(bool(expr))> are necessary // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written // // CompileAssert<bool(expr)> // // instead, these compilers will refuse to compile // // GTEST_COMPILE_ASSERT_(5 > 0, some_message); // // (They seem to think the ">" in "5 > 0" marks the end of the // template argument list.) // // - The array size is (bool(expr) ? 1 : -1), instead of simply // // ((expr) ? 1 : -1). // // This is to avoid running into a bug in MS VC 7.1, which // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. // // This template is declared, but intentionally undefined. template <typename T1, typename T2> struct StaticAssertTypeEqHelper; template <typename T> struct StaticAssertTypeEqHelper<T, T> { enum { value = true }; }; // Evaluates to the number of elements in 'array'. #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) #if GTEST_HAS_GLOBAL_STRING typedef ::string string; #else typedef ::std::string string; #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING typedef ::wstring wstring; #elif GTEST_HAS_STD_WSTRING typedef ::std::wstring wstring; #endif // GTEST_HAS_GLOBAL_WSTRING // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); // Defines scoped_ptr. // This implementation of scoped_ptr is PARTIAL - it only contains // enough stuff to satisfy Google Test's need. template <typename T> class scoped_ptr { public: typedef T element_type; explicit scoped_ptr(T* p = NULL) : ptr_(p) {} ~scoped_ptr() { reset(); } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } T* get() const { return ptr_; } T* release() { T* const ptr = ptr_; ptr_ = NULL; return ptr; } void reset(T* p = NULL) { if (p != ptr_) { if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. delete ptr_; } ptr_ = p; } } friend void swap(scoped_ptr& a, scoped_ptr& b) { using std::swap; swap(a.ptr_, b.ptr_); } private: T* ptr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); }; // Defines RE. // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended // Regular Expression syntax. class GTEST_API_ RE { public: // A copy constructor is required by the Standard to initialize object // references from r-values. RE(const RE& other) { Init(other.pattern()); } // Constructs an RE from a string. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT #if GTEST_HAS_GLOBAL_STRING RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT #endif // GTEST_HAS_GLOBAL_STRING RE(const char* regex) { Init(regex); } // NOLINT ~RE(); // Returns the string representation of the regex. const char* pattern() const { return pattern_; } // FullMatch(str, re) returns true iff regular expression re matches // the entire str. // PartialMatch(str, re) returns true iff regular expression re // matches a substring of str (including str itself). // // TODO(wan@google.com): make FullMatch() and PartialMatch() work // when str contains NUL characters. static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #if GTEST_HAS_GLOBAL_STRING static bool FullMatch(const ::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #endif // GTEST_HAS_GLOBAL_STRING static bool FullMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re); private: void Init(const char* regex); // We use a const char* instead of an std::string, as Google Test used to be // used where std::string is not available. TODO(wan@google.com): change to // std::string. const char* pattern_; bool is_valid_; #if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). #else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); #endif GTEST_DISALLOW_ASSIGN_(RE); }; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line); // Defines logging utilities: // GTEST_LOG_(severity) - logs messages at the specified severity level. The // message itself is streamed into the macro. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of // scope. class GTEST_API_ GTestLog { public: GTestLog(GTestLogSeverity severity, const char* file, int line); // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. ~GTestLog(); ::std::ostream& GetStream() { return ::std::cerr; } private: const GTestLogSeverity severity_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); }; #if !defined(GTEST_LOG_) # define GTEST_LOG_(severity) \ ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ __FILE__, __LINE__).GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(NULL); } #endif // !defined(GTEST_LOG_) #if !defined(GTEST_CHECK_) // INTERNAL IMPLEMENTATION - DO NOT USE. // // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition // is not satisfied. // Synopsys: // GTEST_CHECK_(boolean_condition); // or // GTEST_CHECK_(boolean_condition) << "Additional message"; // // This checks the condition and if the condition is not satisfied // it prints message about the condition violation, including the // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. # define GTEST_CHECK_(condition) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ ; \ else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function // call returns 0 (indicating success). Known limitation: this // doesn't expand to a balanced 'if' statement, so enclose the macro // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ if (const int gtest_error = (posix_call)) \ GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ << gtest_error #if GTEST_HAS_STD_MOVE_ using std::move; #else // GTEST_HAS_STD_MOVE_ template <typename T> const T& move(const T& t) { return t; } #endif // GTEST_HAS_STD_MOVE_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Use ImplicitCast_ as a safe version of static_cast for upcasting in // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a // const Foo*). When you use ImplicitCast_, the compiler checks that // the cast is safe. Such explicit ImplicitCast_s are necessary in // surprisingly many situations where C++ demands an exact type match // instead of an argument type convertable to a target type. // // The syntax for using ImplicitCast_ is the same as for static_cast: // // ImplicitCast_<ToType>(expr) // // ImplicitCast_ would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. template<typename To> inline To ImplicitCast_(To x) { return x; } // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts // always succeed. When you downcast (that is, cast a pointer from // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because // how do you know the pointer is really of type SubclassOfFoo? It // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, // when you downcast, you should use this macro. In debug mode, we // use dynamic_cast<> to double-check the downcast is legal (we die // if it's not). In normal mode, we do the efficient static_cast<> // instead. Thus, it's important to test in debug mode to make sure // the cast is legal! // This is the only place in the code we should use dynamic_cast<>. // In particular, you SHOULDN'T be using dynamic_cast<> in order to // do RTTI (eg code like this: // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo); // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo); // You should design the code some other way not to need this. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. template<typename To, typename From> // use like this: DownCast_<T*>(foo); inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { GTEST_INTENTIONAL_CONST_COND_POP_() const To to = NULL; ::testing::internal::ImplicitCast_<From*>(to); } #if GTEST_HAS_RTTI // RTTI: debug mode only! GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL); #endif return static_cast<To>(f); } // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. // When RTTI is available, the function performs a runtime // check to enforce this. template <class Derived, class Base> Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); #endif #if GTEST_HAS_DOWNCAST_ return ::down_cast<Derived*>(base); #elif GTEST_HAS_RTTI return dynamic_cast<Derived*>(base); // NOLINT #else return static_cast<Derived*>(base); // Poor man's downcast. #endif } #if GTEST_HAS_STREAM_REDIRECTION // Defines the stderr capturer: // CaptureStdout - starts capturing stdout. // GetCapturedStdout - stops capturing stdout and returns the captured string. // CaptureStderr - starts capturing stderr. // GetCapturedStderr - stops capturing stderr and returns the captured string. // GTEST_API_ void CaptureStdout(); GTEST_API_ std::string GetCapturedStdout(); GTEST_API_ void CaptureStderr(); GTEST_API_ std::string GetCapturedStderr(); #endif // GTEST_HAS_STREAM_REDIRECTION // Returns the size (in bytes) of a file. GTEST_API_ size_t GetFileSize(FILE* file); // Reads the entire content of a file as a string. GTEST_API_ std::string ReadEntireFile(FILE* file); // All command line arguments. GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs(); #if GTEST_HAS_DEATH_TEST const ::std::vector<testing::internal::string>& GetInjectableArgvs(); void SetInjectableArgvs(const ::std::vector<testing::internal::string>* new_argvs); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. #if GTEST_IS_THREADSAFE # if GTEST_HAS_PTHREAD // Sleeps for (roughly) n milliseconds. This function is only for testing // Google Test's own constructs. Don't use it in user tests, either // directly or indirectly. inline void SleepMilliseconds(int n) { const timespec time = { 0, // 0 seconds. n * 1000L * 1000L, // And n ms. }; nanosleep(&time, NULL); } # endif // GTEST_HAS_PTHREAD # if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. # elif GTEST_HAS_PTHREAD // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class Notification { public: Notification() : notified_(false) { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); } ~Notification() { pthread_mutex_destroy(&mutex_); } // Notifies all threads created with this notification to start. Must // be called from the controller thread. void Notify() { pthread_mutex_lock(&mutex_); notified_ = true; pthread_mutex_unlock(&mutex_); } // Blocks until the controller thread notifies. Must be called from a test // thread. void WaitForNotification() { for (;;) { pthread_mutex_lock(&mutex_); const bool notified = notified_; pthread_mutex_unlock(&mutex_); if (notified) break; SleepMilliseconds(10); } } private: pthread_mutex_t mutex_; bool notified_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT GTEST_API_ void SleepMilliseconds(int n); // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { public: // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to // avoid including <windows.h> in this header file. Including <windows.h> is // undesirable because it defines a lot of symbols and macros that tend to // conflict with client code. This assumption is verified by // WindowsTypesTest.HANDLEIsVoidStar. typedef void* Handle; AutoHandle(); explicit AutoHandle(Handle handle); ~AutoHandle(); Handle Get() const; void Reset(); void Reset(Handle handle); private: // Returns true iff the handle is a valid handle object that can be closed. bool IsCloseable() const; Handle handle_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); }; // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class GTEST_API_ Notification { public: Notification(); void Notify(); void WaitForNotification(); private: AutoHandle event_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam // in order to call its Run(). Introducing ThreadWithParamBase as a // non-templated base class for ThreadWithParam allows us to bypass this // problem. class ThreadWithParamBase { public: virtual ~ThreadWithParamBase() {} virtual void Run() = 0; }; // pthread_create() accepts a pointer to a function type with the C linkage. // According to the Standard (7.5/1), function types with different linkages // are different even if they are otherwise identical. Some compilers (for // example, SunStudio) treat them as different types. Since class methods // cannot be defined with C-linkage we need to define a free C-function to // pass into pthread_create(). extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { static_cast<ThreadWithParamBase*>(thread)->Run(); return NULL; } // Helper class for testing Google Test's multi-threading constructs. // To use it, write: // // void ThreadFunc(int param) { /* Do things with param */ } // Notification thread_can_start; // ... // // The thread_can_start parameter is optional; you can supply NULL. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start); // thread_can_start.Notify(); // // These classes are only for testing Google Test's own constructs. Do // not use them in user tests, either directly or indirectly. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : func_(func), param_(param), thread_can_start_(thread_can_start), finished_(false) { ThreadWithParamBase* const base = this; // The thread can be created only after all fields except thread_ // have been initialized. GTEST_CHECK_POSIX_SUCCESS_( pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); } ~ThreadWithParam() { Join(); } void Join() { if (!finished_) { GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); finished_ = true; } } virtual void Run() { if (thread_can_start_ != NULL) thread_can_start_->WaitForNotification(); func_(param_); } private: UserThreadFunc* const func_; // User-supplied thread function. const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; bool finished_; // true iff we know that the thread function has finished. pthread_t thread_; // The native thread object. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: // // Mutex mutex; // ... // MutexLock lock(&mutex); // Acquires the mutex and releases it at the // // end of the current scope. // // A static Mutex *must* be defined or declared using one of the following // macros: // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); // // (A non-static Mutex is defined/declared in the usual way). class GTEST_API_ Mutex { public: enum MutexType { kStatic = 0, kDynamic = 1 }; // We rely on kStaticMutex being 0 as it is to what the linker initializes // type_ in static mutexes. critical_section_ will be initialized lazily // in ThreadSafeLazyInit(). enum StaticConstructorSelector { kStaticMutex = 0 }; // This constructor intentionally does nothing. It relies on type_ being // statically initialized to 0 (effectively setting it to kStatic) and on // ThreadSafeLazyInit() to lazily initialize the rest of the members. explicit Mutex(StaticConstructorSelector /*dummy*/) {} Mutex(); ~Mutex(); void Lock(); void Unlock(); // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld(); private: // 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, // we assume that 0 is an invalid value for thread IDs. unsigned int owner_thread_id_; // For static mutexes, we rely on these members being initialized to zeros // by the linker. MutexType type_; long critical_section_init_phase_; // NOLINT GTEST_CRITICAL_SECTION* critical_section_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: Mutex* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Base class for ValueHolder<T>. Allows a caller to hold and delete a value // without knowing its type. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Provides a way for a thread to send notifications to a ThreadLocal // regardless of its parameter type. class ThreadLocalBase { public: // Creates a new ValueHolder<T> object holding a default value passed to // this ThreadLocal<T>'s constructor and returns it. It is the caller's // responsibility not to call this when the ThreadLocal<T> instance already // has a value on the current thread. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; protected: ThreadLocalBase() {} virtual ~ThreadLocalBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase); }; // Maps a thread to a set of ThreadLocals that have values instantiated on that // thread and notifies them when the thread exits. A ThreadLocal instance is // expected to persist until all threads it has values on have terminated. class GTEST_API_ ThreadLocalRegistry { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance); // Invoked when a ThreadLocal instance is destroyed. static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance); }; class GTEST_API_ ThreadWithParamBase { public: void Join(); protected: class Runnable { public: virtual ~Runnable() {} virtual void Run() = 0; }; ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); virtual ~ThreadWithParamBase(); private: AutoHandle thread_; }; // Helper class for testing Google Test's multi-threading constructs. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { } virtual ~ThreadWithParam() {} private: class RunnableImpl : public Runnable { public: RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) { } virtual ~RunnableImpl() {} virtual void Run() { func_(param_); } private: UserThreadFunc* const func_; const T param_; GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl); }; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; // Implements thread-local storage on Windows systems. // // // Thread 1 // ThreadLocal<int> tl(100); // 100 is the default value for each thread. // // // Thread 2 // tl.set(150); // Changes the value for thread 2 only. // EXPECT_EQ(150, tl.get()); // // // Thread 1 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. // tl.set(200); // EXPECT_EQ(200, tl.get()); // // The template type argument T must have a public copy constructor. // In addition, the default ThreadLocal constructor requires T to have // a public default constructor. // // The users of a TheadLocal instance have to make sure that all but one // threads (including the main one) using that instance have exited before // destroying it. Otherwise, the per-thread objects managed for them by the // ThreadLocal instance are not guaranteed to be destroyed on all platforms. // // Google Test only uses global ThreadLocal objects. That means they // will die after main() has returned. Therefore, no per-thread // object managed by Google Test will be leaked as long as all threads // using Google Test have exited when main() returns. template <typename T> class ThreadLocal : public ThreadLocalBase { public: ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of T. Can be deleted via its base class without the caller // knowing the type of T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; T* GetOrCreateValue() const { return static_cast<ValueHolder*>( ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); } virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { return default_factory_->MakeNewHolder(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; scoped_ptr<ValueHolderFactory> default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # elif GTEST_HAS_PTHREAD // MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { public: // Acquires this mutex. void Lock() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); owner_ = pthread_self(); has_owner_ = true; } // Releases this mutex. void Unlock() { // Since the lock is being released the owner_ field should no longer be // considered valid. We don't protect writing to has_owner_ here, as it's // the caller's responsibility to ensure that the current thread holds the // mutex when this is called. has_owner_ = false; GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld() const { GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) << "The current thread is not holding the mutex @" << this; } // A static mutex may be used before main() is entered. It may even // be used before the dynamic initialization stage. Therefore we // must be able to initialize a static mutex object at link time. // This means MutexBase has to be a POD and its member variables // have to be public. public: pthread_mutex_t mutex_; // The underlying pthread mutex. // has_owner_ indicates whether the owner_ field below contains a valid thread // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All // accesses to the owner_ field should be protected by a check of this field. // An alternative might be to memset() owner_ to all zeros, but there's no // guarantee that a zero'd pthread_t is necessarily invalid or even different // from pthread_self(). bool has_owner_; pthread_t owner_; // The thread holding the mutex. }; // Forward-declares a static mutex. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, pthread_t() } // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. class Mutex : public MutexBase { public: Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); has_owner_ = false; } ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: MutexBase* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Helpers for ThreadLocal. // pthread_key_create() requires DeleteThreadLocalValue() to have // C-linkage. Therefore it cannot be templatized to access // ThreadLocal<T>. Hence the need for class // ThreadLocalValueHolderBase. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Called by pthread to delete thread-local data stored by // pthread_setspecific(). extern "C" inline void DeleteThreadLocalValue(void* value_holder) { delete static_cast<ThreadLocalValueHolderBase*>(value_holder); } // Implements thread-local storage on pthreads-based systems. template <typename T> class ThreadLocal { public: ThreadLocal() : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : key_(CreateKey()), default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. DeleteThreadLocalValue(pthread_getspecific(key_)); // Releases resources associated with the key. This will *not* // delete managed objects for other threads. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of type T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; static pthread_key_t CreateKey() { pthread_key_t key; // When a thread exits, DeleteThreadLocalValue() will be called on // the object managed for that thread. GTEST_CHECK_POSIX_SUCCESS_( pthread_key_create(&key, &DeleteThreadLocalValue)); return key; } T* GetOrCreateValue() const { ThreadLocalValueHolderBase* const holder = static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_)); if (holder != NULL) { return CheckedDowncastToActualType<ValueHolder>(holder)->pointer(); } ValueHolder* const new_holder = default_factory_->MakeNewHolder(); ThreadLocalValueHolderBase* const holder_base = new_holder; GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); return new_holder->pointer(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; scoped_ptr<ValueHolderFactory> default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #else // GTEST_IS_THREADSAFE // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where // mutex is not supported - using Google Test in multiple threads is not // supported on such platforms. class Mutex { public: Mutex() {} void Lock() {} void Unlock() {} void AssertHeld() const {} }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT }; typedef GTestMutexLock MutexLock; template <typename T> class ThreadLocal { public: ThreadLocal() : value_() {} explicit ThreadLocal(const T& value) : value_(value) {} T* pointer() { return &value_; } const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } private: T value_; }; #endif // GTEST_IS_THREADSAFE // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. GTEST_API_ size_t GetThreadCount(); // Passing non-POD classes through ellipsis (...) crashes the ARM -// compiler and generates a warning in Sun Studio. The Nokia Symbian +// compiler and generates a warning in Sun Studio before 12u4. The Nokia Symbian // and the IBM XL C/C++ compiler try to instantiate a copy constructor // for objects passed through ellipsis (...), failing for uncopyable // objects. We define this to ensure that only POD is passed through // ellipsis on these systems. -#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) +#if defined(__SYMBIAN32__) || defined(__IBMCPP__) || \ + (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x5130) // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). # define GTEST_ELLIPSIS_NEEDS_POD_ 1 #else # define GTEST_CAN_COMPARE_NULL 1 #endif // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between // const T& and const T* in a function template. These compilers // _can_ decide between class template specializations for T and T*, // so a tr1::type_traits-like is_pointer works. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) # define GTEST_NEEDS_IS_POINTER_ 1 #endif template <bool bool_value> struct bool_constant { typedef bool_constant<bool_value> type; static const bool value = bool_value; }; template <bool bool_value> const bool bool_constant<bool_value>::value; typedef bool_constant<false> false_type; typedef bool_constant<true> true_type; template <typename T, typename U> struct is_same : public false_type {}; template <typename T> struct is_same<T, T> : public true_type {}; template <typename T> struct is_pointer : public false_type {}; template <typename T> struct is_pointer<T*> : public true_type {}; template <typename Iterator> struct IteratorTraits { typedef typename Iterator::value_type value_type; }; template <typename T> struct IteratorTraits<T*> { typedef T value_type; }; template <typename T> struct IteratorTraits<const T*> { typedef T value_type; }; #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 // The biggest signed integer type the compiler supports. typedef __int64 BiggestInt; #else # define GTEST_PATH_SEP_ "/" # define GTEST_HAS_ALT_PATH_SEP_ 0 typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS // Utilities for char. // isspace(int ch) and friends accept an unsigned char or EOF. char // may be signed, depending on the compiler (or compiler flags). // Therefore we need to cast a char to unsigned char before calling // isspace(), etc. inline bool IsAlpha(char ch) { return isalpha(static_cast<unsigned char>(ch)) != 0; } inline bool IsAlNum(char ch) { return isalnum(static_cast<unsigned char>(ch)) != 0; } inline bool IsDigit(char ch) { return isdigit(static_cast<unsigned char>(ch)) != 0; } inline bool IsLower(char ch) { return islower(static_cast<unsigned char>(ch)) != 0; } inline bool IsSpace(char ch) { return isspace(static_cast<unsigned char>(ch)) != 0; } inline bool IsUpper(char ch) { return isupper(static_cast<unsigned char>(ch)) != 0; } inline bool IsXDigit(char ch) { return isxdigit(static_cast<unsigned char>(ch)) != 0; } inline bool IsXDigit(wchar_t ch) { const unsigned char low_byte = static_cast<unsigned char>(ch); return ch == low_byte && isxdigit(low_byte) != 0; } inline char ToLower(char ch) { return static_cast<char>(tolower(static_cast<unsigned char>(ch))); } inline char ToUpper(char ch) { return static_cast<char>(toupper(static_cast<unsigned char>(ch))); } inline std::string StripTrailingSpaces(std::string str) { std::string::iterator it = str.end(); while (it != str.begin() && IsSpace(*--it)) it = str.erase(it); return str; } // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these // standard functions as macros, the wrapper cannot have the same name // as the wrapped function. namespace posix { // Functions with a different name on Windows. #if GTEST_OS_WINDOWS typedef struct _stat StatStruct; # ifdef __BORLANDC__ inline int IsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } # else // !__BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int IsATTY(int /* fd */) { return 0; } # else inline int IsATTY(int fd) { return _isatty(fd); } # endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } # endif // __BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. # else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } # endif // GTEST_OS_WINDOWS_MOBILE #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int IsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif // GTEST_OS_WINDOWS // Functions deprecated by MSVC 8.0. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); } // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not // defined there. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { return fopen(path, mode); } #if !GTEST_OS_WINDOWS_MOBILE inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif inline int FClose(FILE* fp) { return fclose(fp); } #if !GTEST_OS_WINDOWS_MOBILE inline int Read(int fd, void* buf, unsigned int count) { return static_cast<int>(read(fd, buf, count)); } inline int Write(int fd, const void* buf, unsigned int count) { return static_cast<int>(write(fd, buf, count)); } inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT // We are on Windows CE, which has no environment variables. static_cast<void>(name); // To prevent 'unused argument' warning. return NULL; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the // empty string rather than unset (NULL). Handle that case. const char* const env = getenv(name); return (env != NULL && env[0] != '\0') ? env : NULL; #else return getenv(name); #endif } GTEST_DISABLE_MSC_WARNINGS_POP_() #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in // several places in Google Test. This implementation provides a reasonable // imitation of standard behaviour. void Abort(); #else inline void Abort() { abort(); } #endif // GTEST_OS_WINDOWS_MOBILE } // namespace posix // MSVC "deprecates" snprintf and issues warnings wherever it is used. In // order to avoid these warnings, we need to use _snprintf or _snprintf_s on // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate // function in order to achieve that. We use macro definition here because // snprintf is a variadic function. #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. # define GTEST_SNPRINTF_(buffer, size, format, ...) \ _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't // complain about _snprintf. # define GTEST_SNPRINTF_ _snprintf #else # define GTEST_SNPRINTF_ snprintf #endif // The maximum number a BiggestInt can represent. This definition // works no matter BiggestInt is represented in one's complement or // two's complement. // // We cannot rely on numeric_limits in STL, as __int64 and long long // are not part of standard C++ and numeric_limits doesn't need to be // defined for them. const BiggestInt kMaxBiggestInt = ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1)); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that // size. e.g. // // TypeWithSize<4>::UInt // // is typedef-ed to be unsigned int (unsigned integer made up of 4 // bytes). // // Such functionality should belong to STL, but I cannot find it // there. // // Google Test uses this class in the implementation of floating-point // comparison. // // For now it only handles UInt (unsigned int) as that's all Google Test // needs. Other types can be easily added in the future if need // arises. template <size_t size> class TypeWithSize { public: // This prevents the user from using TypeWithSize<N> with incorrect // values of N. typedef void UInt; }; // The specialization for size 4. template <> class TypeWithSize<4> { public: // unsigned int has size 4 in both gcc and MSVC. // // As base/basictypes.h doesn't compile on Windows, we cannot use // uint32, uint64, and etc here. typedef int Int; typedef unsigned int UInt; }; // The specialization for size 8. template <> class TypeWithSize<8> { public: #if GTEST_OS_WINDOWS typedef __int64 Int; typedef unsigned __int64 UInt; #else typedef long long Int; // NOLINT typedef unsigned long long UInt; // NOLINT #endif // GTEST_OS_WINDOWS }; // Integer types of known sizes. typedef TypeWithSize<4>::Int Int32; typedef TypeWithSize<4>::UInt UInt32; typedef TypeWithSize<8>::Int Int64; typedef TypeWithSize<8>::UInt UInt64; typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Utilities for command line flags and environment variables. // Macro for referencing flags. #if !defined(GTEST_FLAG) # define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) #if !defined(GTEST_DECLARE_bool_) # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) # define GTEST_DECLARE_int32_(name) \ GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) #define GTEST_DECLARE_string_(name) \ GTEST_API_ extern ::std::string GTEST_FLAG(name) // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) #endif // !defined(GTEST_DECLARE_bool_) // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) # define GTEST_LOCK_EXCLUDED_(locks) #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. // TODO(chandlerc): Find a better way to refactor flag and environment parsing // out of both gtest-port.cc and gtest.cc to avoid exporting this utility // function. bool ParseInt32(const Message& src_text, const char* str, Int32* value); // Parses a bool/Int32/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); std::string StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal // Returns a path to temporary directory. // Tries to determine an appropriate directory for the platform. GTEST_API_ std::string TempDir(); } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ diff --git a/googletest/samples/sample1.cc b/googletest/samples/sample1.cc index f171e260..7c08b28f 100644 --- a/googletest/samples/sample1.cc +++ b/googletest/samples/sample1.cc @@ -1,68 +1,68 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. // // Author: wan@google.com (Zhanyong Wan) #include "sample1.h" // Returns n! (the factorial of n). For negative n, n! is defined to be 1. int Factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } // Returns true iff n is a prime number. bool IsPrime(int n) { // Trivial case 1: small numbers if (n <= 1) return false; // Trivial case 2: even numbers if (n % 2 == 0) return n == 2; // Now, we have that n is odd and n >= 3. // Try to divide n by every odd number i, starting from 3 for (int i = 3; ; i += 2) { - // We only have to try i up to the squre root of n + // We only have to try i up to the square root of n if (i > n/i) break; // Now, we have i <= n/i < n. // If n is divisible by i, n is not prime. if (n % i == 0) return false; } // n has no integer factor in the range (1, n), and thus is prime. return true; } diff --git a/googletest/samples/sample10_unittest.cc b/googletest/samples/sample10_unittest.cc index 0051cd5d..977e5ff6 100644 --- a/googletest/samples/sample10_unittest.cc +++ b/googletest/samples/sample10_unittest.cc @@ -1,144 +1,141 @@ // Copyright 2009 Google Inc. All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vladl@google.com (Vlad Losev) // This sample shows how to use Google Test listener API to implement // a primitive leak checker. #include <stdio.h> #include <stdlib.h> #include "gtest/gtest.h" - using ::testing::EmptyTestEventListener; using ::testing::InitGoogleTest; using ::testing::Test; using ::testing::TestCase; using ::testing::TestEventListeners; using ::testing::TestInfo; using ::testing::TestPartResult; using ::testing::UnitTest; namespace { - // We will track memory used by this class. class Water { public: // Normal Water declarations go here. // operator new and operator delete help us control water allocation. void* operator new(size_t allocation_size) { allocated_++; return malloc(allocation_size); } void operator delete(void* block, size_t /* allocation_size */) { allocated_--; free(block); } static int allocated() { return allocated_; } private: static int allocated_; }; int Water::allocated_ = 0; // This event listener monitors how many Water objects are created and // destroyed by each test, and reports a failure if a test leaks some Water // objects. It does this by comparing the number of live Water objects at // the beginning of a test and at the end of a test. class LeakChecker : public EmptyTestEventListener { private: // Called before a test starts. virtual void OnTestStart(const TestInfo& /* test_info */) { initially_allocated_ = Water::allocated(); } // Called after a test ends. virtual void OnTestEnd(const TestInfo& /* test_info */) { int difference = Water::allocated() - initially_allocated_; // You can generate a failure in any event handler except // OnTestPartResult. Just use an appropriate Google Test assertion to do // it. EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!"; } int initially_allocated_; }; TEST(ListenersTest, DoesNotLeak) { Water* water = new Water; delete water; } // This should fail when the --check_for_leaks command line flag is // specified. TEST(ListenersTest, LeaksWater) { Water* water = new Water; EXPECT_TRUE(water != NULL); } - } // namespace int main(int argc, char **argv) { InitGoogleTest(&argc, argv); bool check_for_leaks = false; if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 ) check_for_leaks = true; else printf("%s\n", "Run this program with --check_for_leaks to enable " "custom leak checking in the tests."); // If we are given the --check_for_leaks command line flag, installs the // leak checker. if (check_for_leaks) { TestEventListeners& listeners = UnitTest::GetInstance()->listeners(); // Adds the leak checker to the end of the test event listener list, // after the default text output printer and the default XML report // generator. // // The order is important - it ensures that failures generated in the // leak checker's OnTestEnd() method are processed by the text and XML // printers *before* their OnTestEnd() methods are called, such that // they are attributed to the right test. Remember that a listener // receives an OnXyzStart event *after* listeners preceding it in the // list received that event, and receives an OnXyzEnd event *before* // listeners preceding it. // // We don't need to worry about deleting the new listener later, as // Google Test will do it. listeners.Append(new LeakChecker); } return RUN_ALL_TESTS(); } diff --git a/googletest/samples/sample1_unittest.cc b/googletest/samples/sample1_unittest.cc index aefc4f1d..8376bb43 100644 --- a/googletest/samples/sample1_unittest.cc +++ b/googletest/samples/sample1_unittest.cc @@ -1,153 +1,154 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. // // Author: wan@google.com (Zhanyong Wan) // This sample shows how to write a simple unit test for a function, // using Google C++ testing framework. // // Writing a unit test using Google C++ testing framework is easy as 1-2-3: // Step 1. Include necessary header files such that the stuff your // test logic needs is declared. // // Don't forget gtest.h, which declares the testing framework. #include <limits.h> #include "sample1.h" #include "gtest/gtest.h" - +namespace { // Step 2. Use the TEST macro to define your tests. // // TEST has two parameters: the test case name and the test name. // After using the macro, you should define your test logic between a // pair of braces. You can use a bunch of macros to indicate the // success or failure of a test. EXPECT_TRUE and EXPECT_EQ are // examples of such macros. For a complete list, see gtest.h. // // <TechnicalDetails> // // In Google Test, tests are grouped into test cases. This is how we // keep test code organized. You should put logically related tests // into the same test case. // // The test case name and the test name should both be valid C++ // identifiers. And you should not use underscore (_) in the names. // // Google Test guarantees that each test you define is run exactly // once, but it makes no guarantee on the order the tests are // executed. Therefore, you should write your tests in such a way // that their results don't depend on their order. // // </TechnicalDetails> // Tests Factorial(). // Tests factorial of negative numbers. TEST(FactorialTest, Negative) { // This test is named "Negative", and belongs to the "FactorialTest" // test case. EXPECT_EQ(1, Factorial(-5)); EXPECT_EQ(1, Factorial(-1)); EXPECT_GT(Factorial(-10), 0); // <TechnicalDetails> // // EXPECT_EQ(expected, actual) is the same as // // EXPECT_TRUE((expected) == (actual)) // // except that it will print both the expected value and the actual // value when the assertion fails. This is very helpful for // debugging. Therefore in this case EXPECT_EQ is preferred. // // On the other hand, EXPECT_TRUE accepts any Boolean expression, // and is thus more general. // // </TechnicalDetails> } // Tests factorial of 0. TEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); } // Tests factorial of positive numbers. TEST(FactorialTest, Positive) { EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(2, Factorial(2)); EXPECT_EQ(6, Factorial(3)); EXPECT_EQ(40320, Factorial(8)); } // Tests IsPrime() // Tests negative input. TEST(IsPrimeTest, Negative) { // This test belongs to the IsPrimeTest test case. EXPECT_FALSE(IsPrime(-1)); EXPECT_FALSE(IsPrime(-2)); EXPECT_FALSE(IsPrime(INT_MIN)); } // Tests some trivial cases. TEST(IsPrimeTest, Trivial) { EXPECT_FALSE(IsPrime(0)); EXPECT_FALSE(IsPrime(1)); EXPECT_TRUE(IsPrime(2)); EXPECT_TRUE(IsPrime(3)); } // Tests positive input. TEST(IsPrimeTest, Positive) { EXPECT_FALSE(IsPrime(4)); EXPECT_TRUE(IsPrime(5)); EXPECT_FALSE(IsPrime(6)); EXPECT_TRUE(IsPrime(23)); } +} // namespace // Step 3. Call RUN_ALL_TESTS() in main(). // // We do this by linking in src/gtest_main.cc file, which consists of // a main() function which calls RUN_ALL_TESTS() for us. // // This runs all the tests you've defined, prints the result, and // returns 0 if successful, or 1 otherwise. // // Did you notice that we didn't register the tests? The // RUN_ALL_TESTS() macro magically knows about all the tests we // defined. Isn't this convenient? diff --git a/googletest/samples/sample2_unittest.cc b/googletest/samples/sample2_unittest.cc index 4fa19b71..df522da5 100644 --- a/googletest/samples/sample2_unittest.cc +++ b/googletest/samples/sample2_unittest.cc @@ -1,109 +1,110 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. // // Author: wan@google.com (Zhanyong Wan) // This sample shows how to write a more complex unit test for a class // that has multiple member functions. // // Usually, it's a good idea to have one test for each method in your // class. You don't have to do that exactly, but it helps to keep // your tests organized. You may also throw in additional tests as // needed. #include "sample2.h" #include "gtest/gtest.h" - +namespace { // In this example, we test the MyString class (a simple string). // Tests the default c'tor. TEST(MyString, DefaultConstructor) { const MyString s; // Asserts that s.c_string() returns NULL. // // <TechnicalDetails> // // If we write NULL instead of // // static_cast<const char *>(NULL) // // in this assertion, it will generate a warning on gcc 3.4. The // reason is that EXPECT_EQ needs to know the types of its // arguments in order to print them when it fails. Since NULL is // #defined as 0, the compiler will use the formatter function for // int to print it. However, gcc thinks that NULL should be used as // a pointer, not an int, and therefore complains. // // The root of the problem is C++'s lack of distinction between the // integer number 0 and the null pointer constant. Unfortunately, // we have to live with this fact. // // </TechnicalDetails> EXPECT_STREQ(NULL, s.c_string()); EXPECT_EQ(0u, s.Length()); } const char kHelloString[] = "Hello, world!"; // Tests the c'tor that accepts a C string. TEST(MyString, ConstructorFromCString) { const MyString s(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); EXPECT_EQ(sizeof(kHelloString)/sizeof(kHelloString[0]) - 1, s.Length()); } // Tests the copy c'tor. TEST(MyString, CopyConstructor) { const MyString s1(kHelloString); const MyString s2 = s1; EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString)); } // Tests the Set method. TEST(MyString, Set) { MyString s; s.Set(kHelloString); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); // Set should work when the input pointer is the same as the one // already in the MyString object. s.Set(s.c_string()); EXPECT_EQ(0, strcmp(s.c_string(), kHelloString)); // Can we set the MyString to NULL? s.Set(NULL); EXPECT_STREQ(NULL, s.c_string()); } +} // namespace diff --git a/googletest/samples/sample3_unittest.cc b/googletest/samples/sample3_unittest.cc index bf3877d0..7f51fd89 100644 --- a/googletest/samples/sample3_unittest.cc +++ b/googletest/samples/sample3_unittest.cc @@ -1,151 +1,152 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. // // Author: wan@google.com (Zhanyong Wan) // In this example, we use a more advanced feature of Google Test called // test fixture. // // A test fixture is a place to hold objects and functions shared by // all tests in a test case. Using a test fixture avoids duplicating // the test code necessary to initialize and cleanup those common // objects for each test. It is also useful for defining sub-routines // that your tests need to invoke a lot. // // <TechnicalDetails> // // The tests share the test fixture in the sense of code sharing, not // data sharing. Each test is given its own fresh copy of the // fixture. You cannot expect the data modified by one test to be // passed on to another test, which is a bad idea. // // The reason for this design is that tests should be independent and // repeatable. In particular, a test should not fail as the result of // another test's failure. If one test depends on info produced by // another test, then the two tests should really be one big test. // // The macros for indicating the success/failure of a test // (EXPECT_TRUE, FAIL, etc) need to know what the current test is // (when Google Test prints the test result, it tells you which test // each failure belongs to). Technically, these macros invoke a // member function of the Test class. Therefore, you cannot use them // in a global function. That's why you should put test sub-routines // in a test fixture. // // </TechnicalDetails> #include "sample3-inl.h" #include "gtest/gtest.h" - +namespace { // To use a test fixture, derive a class from testing::Test. -class QueueTest : public testing::Test { +class QueueTestSmpl3 : public testing::Test { protected: // You should make the members protected s.t. they can be // accessed from sub-classes. // virtual void SetUp() will be called before each test is run. You - // should define it if you need to initialize the varaibles. + // should define it if you need to initialize the variables. // Otherwise, this can be skipped. virtual void SetUp() { q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); } // virtual void TearDown() will be called after each test is run. // You should define it if there is cleanup work to do. Otherwise, // you don't have to provide it. // // virtual void TearDown() { // } // A helper function that some test uses. static int Double(int n) { return 2*n; } // A helper function for testing Queue::Map(). void MapTester(const Queue<int> * q) { // Creates a new queue, where each element is twice as big as the // corresponding one in q. const Queue<int> * const new_q = q->Map(Double); // Verifies that the new queue has the same size as q. ASSERT_EQ(q->Size(), new_q->Size()); // Verifies the relationship between the elements of the two queues. for ( const QueueNode<int> * n1 = q->Head(), * n2 = new_q->Head(); n1 != NULL; n1 = n1->next(), n2 = n2->next() ) { EXPECT_EQ(2 * n1->element(), n2->element()); } delete new_q; } // Declares the variables your tests want to use. Queue<int> q0_; Queue<int> q1_; Queue<int> q2_; }; // When you have a test fixture, you define a test using TEST_F // instead of TEST. // Tests the default c'tor. -TEST_F(QueueTest, DefaultConstructor) { +TEST_F(QueueTestSmpl3, DefaultConstructor) { // You can access data in the test fixture here. EXPECT_EQ(0u, q0_.Size()); } // Tests Dequeue(). -TEST_F(QueueTest, Dequeue) { +TEST_F(QueueTestSmpl3, Dequeue) { int * n = q0_.Dequeue(); EXPECT_TRUE(n == NULL); n = q1_.Dequeue(); ASSERT_TRUE(n != NULL); EXPECT_EQ(1, *n); EXPECT_EQ(0u, q1_.Size()); delete n; n = q2_.Dequeue(); ASSERT_TRUE(n != NULL); EXPECT_EQ(2, *n); EXPECT_EQ(1u, q2_.Size()); delete n; } // Tests the Queue::Map() function. -TEST_F(QueueTest, Map) { +TEST_F(QueueTestSmpl3, Map) { MapTester(&q0_); MapTester(&q1_); MapTester(&q2_); } +} // namespace diff --git a/googletest/samples/sample4_unittest.cc b/googletest/samples/sample4_unittest.cc index fa5afc7d..948266e8 100644 --- a/googletest/samples/sample4_unittest.cc +++ b/googletest/samples/sample4_unittest.cc @@ -1,45 +1,46 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) #include "gtest/gtest.h" #include "sample4.h" - +namespace { // Tests the Increment() method. TEST(Counter, Increment) { Counter c; // EXPECT_EQ() evaluates its arguments exactly once, so they // can have side effects. EXPECT_EQ(0, c.Increment()); EXPECT_EQ(1, c.Increment()); EXPECT_EQ(2, c.Increment()); } +} // namespace diff --git a/googletest/samples/sample5_unittest.cc b/googletest/samples/sample5_unittest.cc index 43d8e577..30999307 100644 --- a/googletest/samples/sample5_unittest.cc +++ b/googletest/samples/sample5_unittest.cc @@ -1,199 +1,199 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // This sample teaches how to reuse a test fixture in multiple test // cases by deriving sub-fixtures from it. // // When you define a test fixture, you specify the name of the test // case that will use this fixture. Therefore, a test fixture can // be used by only one test case. // // Sometimes, more than one test cases may want to use the same or // slightly different test fixtures. For example, you may want to // make sure that all tests for a GUI library don't leak important // system resources like fonts and brushes. In Google Test, you do // this by putting the shared logic in a super (as in "super class") // test fixture, and then have each test case use a fixture derived // from this super fixture. #include <limits.h> #include <time.h> #include "sample3-inl.h" #include "gtest/gtest.h" #include "sample1.h" - +namespace { // In this sample, we want to ensure that every test finishes within // ~5 seconds. If a test takes longer to run, we consider it a // failure. // // We put the code for timing a test in a test fixture called // "QuickTest". QuickTest is intended to be the super fixture that // other fixtures derive from, therefore there is no test case with // the name "QuickTest". This is OK. // // Later, we will derive multiple test fixtures from QuickTest. class QuickTest : public testing::Test { protected: // Remember that SetUp() is run immediately before a test starts. // This is a good place to record the start time. virtual void SetUp() { start_time_ = time(NULL); } // TearDown() is invoked immediately after a test finishes. Here we // check if the test was too slow. virtual void TearDown() { // Gets the time when the test finishes const time_t end_time = time(NULL); // Asserts that the test took no more than ~5 seconds. Did you // know that you can use assertions in SetUp() and TearDown() as // well? EXPECT_TRUE(end_time - start_time_ <= 5) << "The test took too long."; } // The UTC time (in seconds) when the test starts time_t start_time_; }; // We derive a fixture named IntegerFunctionTest from the QuickTest // fixture. All tests using this fixture will be automatically // required to be quick. class IntegerFunctionTest : public QuickTest { // We don't need any more logic than already in the QuickTest fixture. // Therefore the body is empty. }; // Now we can write tests in the IntegerFunctionTest test case. // Tests Factorial() TEST_F(IntegerFunctionTest, Factorial) { // Tests factorial of negative numbers. EXPECT_EQ(1, Factorial(-5)); EXPECT_EQ(1, Factorial(-1)); EXPECT_GT(Factorial(-10), 0); // Tests factorial of 0. EXPECT_EQ(1, Factorial(0)); // Tests factorial of positive numbers. EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(2, Factorial(2)); EXPECT_EQ(6, Factorial(3)); EXPECT_EQ(40320, Factorial(8)); } // Tests IsPrime() TEST_F(IntegerFunctionTest, IsPrime) { // Tests negative input. EXPECT_FALSE(IsPrime(-1)); EXPECT_FALSE(IsPrime(-2)); EXPECT_FALSE(IsPrime(INT_MIN)); // Tests some trivial cases. EXPECT_FALSE(IsPrime(0)); EXPECT_FALSE(IsPrime(1)); EXPECT_TRUE(IsPrime(2)); EXPECT_TRUE(IsPrime(3)); // Tests positive input. EXPECT_FALSE(IsPrime(4)); EXPECT_TRUE(IsPrime(5)); EXPECT_FALSE(IsPrime(6)); EXPECT_TRUE(IsPrime(23)); } // The next test case (named "QueueTest") also needs to be quick, so // we derive another fixture from QuickTest. // // The QueueTest test fixture has some logic and shared objects in // addition to what's in QuickTest already. We define the additional // stuff inside the body of the test fixture, as usual. class QueueTest : public QuickTest { protected: virtual void SetUp() { // First, we need to set up the super fixture (QuickTest). QuickTest::SetUp(); // Second, some additional setup for this fixture. q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); } // By default, TearDown() inherits the behavior of // QuickTest::TearDown(). As we have no additional cleaning work // for QueueTest, we omit it here. // // virtual void TearDown() { // QuickTest::TearDown(); // } Queue<int> q0_; Queue<int> q1_; Queue<int> q2_; }; // Now, let's write tests using the QueueTest fixture. // Tests the default constructor. TEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.Size()); } // Tests Dequeue(). TEST_F(QueueTest, Dequeue) { int* n = q0_.Dequeue(); EXPECT_TRUE(n == NULL); n = q1_.Dequeue(); EXPECT_TRUE(n != NULL); EXPECT_EQ(1, *n); EXPECT_EQ(0u, q1_.Size()); delete n; n = q2_.Dequeue(); EXPECT_TRUE(n != NULL); EXPECT_EQ(2, *n); EXPECT_EQ(1u, q2_.Size()); delete n; } - +} // namespace // If necessary, you can derive further test fixtures from a derived // fixture itself. For example, you can derive another fixture from // QueueTest. Google Test imposes no limit on how deep the hierarchy // can be. In practice, however, you probably don't want it to be too // deep as to be confusing. diff --git a/googletest/samples/sample6_unittest.cc b/googletest/samples/sample6_unittest.cc index 8f2036a5..1faf0c3d 100644 --- a/googletest/samples/sample6_unittest.cc +++ b/googletest/samples/sample6_unittest.cc @@ -1,224 +1,225 @@ // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // This sample shows how to test common properties of multiple // implementations of the same interface (aka interface tests). // The interface and its implementations are in this header. #include "prime_tables.h" #include "gtest/gtest.h" - +namespace { // First, we define some factory functions for creating instances of // the implementations. You may be able to skip this step if all your // implementations can be constructed the same way. template <class T> PrimeTable* CreatePrimeTable(); template <> PrimeTable* CreatePrimeTable<OnTheFlyPrimeTable>() { return new OnTheFlyPrimeTable; } template <> PrimeTable* CreatePrimeTable<PreCalculatedPrimeTable>() { return new PreCalculatedPrimeTable(10000); } // Then we define a test fixture class template. template <class T> class PrimeTableTest : public testing::Test { protected: // The ctor calls the factory function to create a prime table // implemented by T. PrimeTableTest() : table_(CreatePrimeTable<T>()) {} virtual ~PrimeTableTest() { delete table_; } // Note that we test an implementation via the base interface // instead of the actual implementation class. This is important // for keeping the tests close to the real world scenario, where the // implementation is invoked via the base interface. It avoids // got-yas where the implementation class has a method that shadows // a method with the same name (but slightly different argument // types) in the base interface, for example. PrimeTable* const table_; }; #if GTEST_HAS_TYPED_TEST using testing::Types; // Google Test offers two ways for reusing tests for different types. // The first is called "typed tests". You should use it if you // already know *all* the types you are gonna exercise when you write // the tests. // To write a typed test case, first use // // TYPED_TEST_CASE(TestCaseName, TypeList); // // to declare it and specify the type parameters. As with TEST_F, // TestCaseName must match the test fixture name. // The list of types we want to test. typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable> Implementations; TYPED_TEST_CASE(PrimeTableTest, Implementations); // Then use TYPED_TEST(TestCaseName, TestName) to define a typed test, // similar to TEST_F. TYPED_TEST(PrimeTableTest, ReturnsFalseForNonPrimes) { // Inside the test body, you can refer to the type parameter by // TypeParam, and refer to the fixture class by TestFixture. We // don't need them in this example. // Since we are in the template world, C++ requires explicitly // writing 'this->' when referring to members of the fixture class. // This is something you have to learn to live with. EXPECT_FALSE(this->table_->IsPrime(-5)); EXPECT_FALSE(this->table_->IsPrime(0)); EXPECT_FALSE(this->table_->IsPrime(1)); EXPECT_FALSE(this->table_->IsPrime(4)); EXPECT_FALSE(this->table_->IsPrime(6)); EXPECT_FALSE(this->table_->IsPrime(100)); } TYPED_TEST(PrimeTableTest, ReturnsTrueForPrimes) { EXPECT_TRUE(this->table_->IsPrime(2)); EXPECT_TRUE(this->table_->IsPrime(3)); EXPECT_TRUE(this->table_->IsPrime(5)); EXPECT_TRUE(this->table_->IsPrime(7)); EXPECT_TRUE(this->table_->IsPrime(11)); EXPECT_TRUE(this->table_->IsPrime(131)); } TYPED_TEST(PrimeTableTest, CanGetNextPrime) { EXPECT_EQ(2, this->table_->GetNextPrime(0)); EXPECT_EQ(3, this->table_->GetNextPrime(2)); EXPECT_EQ(5, this->table_->GetNextPrime(3)); EXPECT_EQ(7, this->table_->GetNextPrime(5)); EXPECT_EQ(11, this->table_->GetNextPrime(7)); EXPECT_EQ(131, this->table_->GetNextPrime(128)); } // That's it! Google Test will repeat each TYPED_TEST for each type // in the type list specified in TYPED_TEST_CASE. Sit back and be // happy that you don't have to define them multiple times. #endif // GTEST_HAS_TYPED_TEST #if GTEST_HAS_TYPED_TEST_P using testing::Types; // Sometimes, however, you don't yet know all the types that you want // to test when you write the tests. For example, if you are the // author of an interface and expect other people to implement it, you // might want to write a set of tests to make sure each implementation // conforms to some basic requirements, but you don't know what // implementations will be written in the future. // // How can you write the tests without committing to the type // parameters? That's what "type-parameterized tests" can do for you. // It is a bit more involved than typed tests, but in return you get a // test pattern that can be reused in many contexts, which is a big // win. Here's how you do it: // First, define a test fixture class template. Here we just reuse // the PrimeTableTest fixture defined earlier: template <class T> class PrimeTableTest2 : public PrimeTableTest<T> { }; // Then, declare the test case. The argument is the name of the test // fixture, and also the name of the test case (as usual). The _P // suffix is for "parameterized" or "pattern". TYPED_TEST_CASE_P(PrimeTableTest2); // Next, use TYPED_TEST_P(TestCaseName, TestName) to define a test, // similar to what you do with TEST_F. TYPED_TEST_P(PrimeTableTest2, ReturnsFalseForNonPrimes) { EXPECT_FALSE(this->table_->IsPrime(-5)); EXPECT_FALSE(this->table_->IsPrime(0)); EXPECT_FALSE(this->table_->IsPrime(1)); EXPECT_FALSE(this->table_->IsPrime(4)); EXPECT_FALSE(this->table_->IsPrime(6)); EXPECT_FALSE(this->table_->IsPrime(100)); } TYPED_TEST_P(PrimeTableTest2, ReturnsTrueForPrimes) { EXPECT_TRUE(this->table_->IsPrime(2)); EXPECT_TRUE(this->table_->IsPrime(3)); EXPECT_TRUE(this->table_->IsPrime(5)); EXPECT_TRUE(this->table_->IsPrime(7)); EXPECT_TRUE(this->table_->IsPrime(11)); EXPECT_TRUE(this->table_->IsPrime(131)); } TYPED_TEST_P(PrimeTableTest2, CanGetNextPrime) { EXPECT_EQ(2, this->table_->GetNextPrime(0)); EXPECT_EQ(3, this->table_->GetNextPrime(2)); EXPECT_EQ(5, this->table_->GetNextPrime(3)); EXPECT_EQ(7, this->table_->GetNextPrime(5)); EXPECT_EQ(11, this->table_->GetNextPrime(7)); EXPECT_EQ(131, this->table_->GetNextPrime(128)); } // Type-parameterized tests involve one extra step: you have to // enumerate the tests you defined: REGISTER_TYPED_TEST_CASE_P( PrimeTableTest2, // The first argument is the test case name. // The rest of the arguments are the test names. ReturnsFalseForNonPrimes, ReturnsTrueForPrimes, CanGetNextPrime); // At this point the test pattern is done. However, you don't have // any real test yet as you haven't said which types you want to run // the tests with. // To turn the abstract test pattern into real tests, you instantiate // it with a list of types. Usually the test pattern will be defined // in a .h file, and anyone can #include and instantiate it. You can // even instantiate it more than once in the same program. To tell // different instances apart, you give each of them a name, which will // become part of the test case name and can be used in test filters. // The list of types we want to test. Note that it doesn't have to be // defined at the time we write the TYPED_TEST_P()s. typedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable> PrimeTableImplementations; INSTANTIATE_TYPED_TEST_CASE_P(OnTheFlyAndPreCalculated, // Instance name PrimeTableTest2, // Test case name PrimeTableImplementations); // Type list #endif // GTEST_HAS_TYPED_TEST_P +} // namespace diff --git a/googletest/samples/sample7_unittest.cc b/googletest/samples/sample7_unittest.cc index 1b651a21..b59e1d96 100644 --- a/googletest/samples/sample7_unittest.cc +++ b/googletest/samples/sample7_unittest.cc @@ -1,130 +1,130 @@ // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vladl@google.com (Vlad Losev) // This sample shows how to test common properties of multiple // implementations of an interface (aka interface tests) using // value-parameterized tests. Each test in the test case has // a parameter that is an interface pointer to an implementation // tested. // The interface and its implementations are in this header. #include "prime_tables.h" #include "gtest/gtest.h" - +namespace { #if GTEST_HAS_PARAM_TEST using ::testing::TestWithParam; using ::testing::Values; // As a general rule, to prevent a test from affecting the tests that come // after it, you should create and destroy the tested objects for each test // instead of reusing them. In this sample we will define a simple factory // function for PrimeTable objects. We will instantiate objects in test's // SetUp() method and delete them in TearDown() method. typedef PrimeTable* CreatePrimeTableFunc(); PrimeTable* CreateOnTheFlyPrimeTable() { return new OnTheFlyPrimeTable(); } template <size_t max_precalculated> PrimeTable* CreatePreCalculatedPrimeTable() { return new PreCalculatedPrimeTable(max_precalculated); } // Inside the test body, fixture constructor, SetUp(), and TearDown() you // can refer to the test parameter by GetParam(). In this case, the test // parameter is a factory function which we call in fixture's SetUp() to // create and store an instance of PrimeTable. -class PrimeTableTest : public TestWithParam<CreatePrimeTableFunc*> { +class PrimeTableTestSmpl7 : public TestWithParam<CreatePrimeTableFunc*> { public: - virtual ~PrimeTableTest() { delete table_; } + virtual ~PrimeTableTestSmpl7() { delete table_; } virtual void SetUp() { table_ = (*GetParam())(); } virtual void TearDown() { delete table_; table_ = NULL; } protected: PrimeTable* table_; }; -TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) { +TEST_P(PrimeTableTestSmpl7, ReturnsFalseForNonPrimes) { EXPECT_FALSE(table_->IsPrime(-5)); EXPECT_FALSE(table_->IsPrime(0)); EXPECT_FALSE(table_->IsPrime(1)); EXPECT_FALSE(table_->IsPrime(4)); EXPECT_FALSE(table_->IsPrime(6)); EXPECT_FALSE(table_->IsPrime(100)); } -TEST_P(PrimeTableTest, ReturnsTrueForPrimes) { +TEST_P(PrimeTableTestSmpl7, ReturnsTrueForPrimes) { EXPECT_TRUE(table_->IsPrime(2)); EXPECT_TRUE(table_->IsPrime(3)); EXPECT_TRUE(table_->IsPrime(5)); EXPECT_TRUE(table_->IsPrime(7)); EXPECT_TRUE(table_->IsPrime(11)); EXPECT_TRUE(table_->IsPrime(131)); } -TEST_P(PrimeTableTest, CanGetNextPrime) { +TEST_P(PrimeTableTestSmpl7, CanGetNextPrime) { EXPECT_EQ(2, table_->GetNextPrime(0)); EXPECT_EQ(3, table_->GetNextPrime(2)); EXPECT_EQ(5, table_->GetNextPrime(3)); EXPECT_EQ(7, table_->GetNextPrime(5)); EXPECT_EQ(11, table_->GetNextPrime(7)); EXPECT_EQ(131, table_->GetNextPrime(128)); } // In order to run value-parameterized tests, you need to instantiate them, // or bind them to a list of values which will be used as test parameters. // You can instantiate them in a different translation module, or even // instantiate them several times. // // Here, we instantiate our tests with a list of two PrimeTable object // factory functions: -INSTANTIATE_TEST_CASE_P( - OnTheFlyAndPreCalculated, - PrimeTableTest, - Values(&CreateOnTheFlyPrimeTable, &CreatePreCalculatedPrimeTable<1000>)); +INSTANTIATE_TEST_CASE_P(OnTheFlyAndPreCalculated, PrimeTableTestSmpl7, + Values(&CreateOnTheFlyPrimeTable, + &CreatePreCalculatedPrimeTable<1000>)); #else // Google Test may not support value-parameterized tests with some // compilers. If we use conditional compilation to compile out all // code referring to the gtest_main library, MSVC linker will not link // that library at all and consequently complain about missing entry // point defined in that library (fatal error LNK1561: entry point // must be defined). This dummy test keeps gtest_main linked in. TEST(DummyTest, ValueParameterizedTestsAreNotSupportedOnThisPlatform) {} #endif // GTEST_HAS_PARAM_TEST +} // namespace diff --git a/googletest/samples/sample8_unittest.cc b/googletest/samples/sample8_unittest.cc index 72743340..b0ff2d1f 100644 --- a/googletest/samples/sample8_unittest.cc +++ b/googletest/samples/sample8_unittest.cc @@ -1,173 +1,174 @@ // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vladl@google.com (Vlad Losev) // This sample shows how to test code relying on some global flag variables. // Combine() helps with generating all possible combinations of such flags, // and each test is given one combination as a parameter. // Use class definitions to test from this header. #include "prime_tables.h" #include "gtest/gtest.h" - +namespace { #if GTEST_HAS_COMBINE // Suppose we want to introduce a new, improved implementation of PrimeTable // which combines speed of PrecalcPrimeTable and versatility of // OnTheFlyPrimeTable (see prime_tables.h). Inside it instantiates both // PrecalcPrimeTable and OnTheFlyPrimeTable and uses the one that is more // appropriate under the circumstances. But in low memory conditions, it can be // told to instantiate without PrecalcPrimeTable instance at all and use only // OnTheFlyPrimeTable. class HybridPrimeTable : public PrimeTable { public: HybridPrimeTable(bool force_on_the_fly, int max_precalculated) : on_the_fly_impl_(new OnTheFlyPrimeTable), precalc_impl_(force_on_the_fly ? NULL : new PreCalculatedPrimeTable(max_precalculated)), max_precalculated_(max_precalculated) {} virtual ~HybridPrimeTable() { delete on_the_fly_impl_; delete precalc_impl_; } virtual bool IsPrime(int n) const { if (precalc_impl_ != NULL && n < max_precalculated_) return precalc_impl_->IsPrime(n); else return on_the_fly_impl_->IsPrime(n); } virtual int GetNextPrime(int p) const { int next_prime = -1; if (precalc_impl_ != NULL && p < max_precalculated_) next_prime = precalc_impl_->GetNextPrime(p); return next_prime != -1 ? next_prime : on_the_fly_impl_->GetNextPrime(p); } private: OnTheFlyPrimeTable* on_the_fly_impl_; PreCalculatedPrimeTable* precalc_impl_; int max_precalculated_; }; using ::testing::TestWithParam; using ::testing::Bool; using ::testing::Values; using ::testing::Combine; // To test all code paths for HybridPrimeTable we must test it with numbers // both within and outside PreCalculatedPrimeTable's capacity and also with // PreCalculatedPrimeTable disabled. We do this by defining fixture which will // accept different combinations of parameters for instantiating a // HybridPrimeTable instance. class PrimeTableTest : public TestWithParam< ::testing::tuple<bool, int> > { protected: virtual void SetUp() { // This can be written as // // bool force_on_the_fly; // int max_precalculated; // tie(force_on_the_fly, max_precalculated) = GetParam(); // // once the Google C++ Style Guide allows use of ::std::tr1::tie. // bool force_on_the_fly = ::testing::get<0>(GetParam()); int max_precalculated = ::testing::get<1>(GetParam()); table_ = new HybridPrimeTable(force_on_the_fly, max_precalculated); } virtual void TearDown() { delete table_; table_ = NULL; } HybridPrimeTable* table_; }; TEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) { // Inside the test body, you can refer to the test parameter by GetParam(). // In this case, the test parameter is a PrimeTable interface pointer which // we can use directly. // Please note that you can also save it in the fixture's SetUp() method // or constructor and use saved copy in the tests. EXPECT_FALSE(table_->IsPrime(-5)); EXPECT_FALSE(table_->IsPrime(0)); EXPECT_FALSE(table_->IsPrime(1)); EXPECT_FALSE(table_->IsPrime(4)); EXPECT_FALSE(table_->IsPrime(6)); EXPECT_FALSE(table_->IsPrime(100)); } TEST_P(PrimeTableTest, ReturnsTrueForPrimes) { EXPECT_TRUE(table_->IsPrime(2)); EXPECT_TRUE(table_->IsPrime(3)); EXPECT_TRUE(table_->IsPrime(5)); EXPECT_TRUE(table_->IsPrime(7)); EXPECT_TRUE(table_->IsPrime(11)); EXPECT_TRUE(table_->IsPrime(131)); } TEST_P(PrimeTableTest, CanGetNextPrime) { EXPECT_EQ(2, table_->GetNextPrime(0)); EXPECT_EQ(3, table_->GetNextPrime(2)); EXPECT_EQ(5, table_->GetNextPrime(3)); EXPECT_EQ(7, table_->GetNextPrime(5)); EXPECT_EQ(11, table_->GetNextPrime(7)); EXPECT_EQ(131, table_->GetNextPrime(128)); } // In order to run value-parameterized tests, you need to instantiate them, // or bind them to a list of values which will be used as test parameters. // You can instantiate them in a different translation module, or even // instantiate them several times. // // Here, we instantiate our tests with a list of parameters. We must combine // all variations of the boolean flag suppressing PrecalcPrimeTable and some // meaningful values for tests. We choose a small value (1), and a value that // will put some of the tested numbers beyond the capability of the // PrecalcPrimeTable instance and some inside it (10). Combine will produce all // possible combinations. INSTANTIATE_TEST_CASE_P(MeaningfulTestParameters, PrimeTableTest, Combine(Bool(), Values(1, 10))); #else // Google Test may not support Combine() with some compilers. If we // use conditional compilation to compile out all code referring to // the gtest_main library, MSVC linker will not link that library at // all and consequently complain about missing entry point defined in // that library (fatal error LNK1561: entry point must be // defined). This dummy test keeps gtest_main linked in. TEST(DummyTest, CombineIsNotSupportedOnThisPlatform) {} #endif // GTEST_HAS_COMBINE +} // namespace diff --git a/googletest/samples/sample9_unittest.cc b/googletest/samples/sample9_unittest.cc index b2e2079b..75584bb0 100644 --- a/googletest/samples/sample9_unittest.cc +++ b/googletest/samples/sample9_unittest.cc @@ -1,160 +1,157 @@ // Copyright 2009 Google Inc. All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: vladl@google.com (Vlad Losev) // This sample shows how to use Google Test listener API to implement // an alternative console output and how to use the UnitTest reflection API // to enumerate test cases and tests and to inspect their results. #include <stdio.h> #include "gtest/gtest.h" using ::testing::EmptyTestEventListener; using ::testing::InitGoogleTest; using ::testing::Test; using ::testing::TestCase; using ::testing::TestEventListeners; using ::testing::TestInfo; using ::testing::TestPartResult; using ::testing::UnitTest; - namespace { - // Provides alternative output mode which produces minimal amount of // information about tests. class TersePrinter : public EmptyTestEventListener { private: // Called before any test activity starts. virtual void OnTestProgramStart(const UnitTest& /* unit_test */) {} // Called after all test activities have ended. virtual void OnTestProgramEnd(const UnitTest& unit_test) { fprintf(stdout, "TEST %s\n", unit_test.Passed() ? "PASSED" : "FAILED"); fflush(stdout); } // Called before a test starts. virtual void OnTestStart(const TestInfo& test_info) { fprintf(stdout, "*** Test %s.%s starting.\n", test_info.test_case_name(), test_info.name()); fflush(stdout); } // Called after a failed assertion or a SUCCEED() invocation. virtual void OnTestPartResult(const TestPartResult& test_part_result) { fprintf(stdout, "%s in %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", test_part_result.file_name(), test_part_result.line_number(), test_part_result.summary()); fflush(stdout); } // Called after a test ends. virtual void OnTestEnd(const TestInfo& test_info) { fprintf(stdout, "*** Test %s.%s ending.\n", test_info.test_case_name(), test_info.name()); fflush(stdout); } }; // class TersePrinter TEST(CustomOutputTest, PrintsMessage) { printf("Printing something from the test body...\n"); } TEST(CustomOutputTest, Succeeds) { SUCCEED() << "SUCCEED() has been invoked from here"; } TEST(CustomOutputTest, Fails) { EXPECT_EQ(1, 2) << "This test fails in order to demonstrate alternative failure messages"; } - } // namespace int main(int argc, char **argv) { InitGoogleTest(&argc, argv); bool terse_output = false; if (argc > 1 && strcmp(argv[1], "--terse_output") == 0 ) terse_output = true; else printf("%s\n", "Run this program with --terse_output to change the way " "it prints its output."); UnitTest& unit_test = *UnitTest::GetInstance(); // If we are given the --terse_output command line flag, suppresses the // standard output and attaches own result printer. if (terse_output) { TestEventListeners& listeners = unit_test.listeners(); // Removes the default console output listener from the list so it will // not receive events from Google Test and won't print any output. Since // this operation transfers ownership of the listener to the caller we // have to delete it as well. delete listeners.Release(listeners.default_result_printer()); // Adds the custom output listener to the list. It will now receive // events from Google Test and print the alternative output. We don't // have to worry about deleting it since Google Test assumes ownership // over it after adding it to the list. listeners.Append(new TersePrinter); } int ret_val = RUN_ALL_TESTS(); // This is an example of using the UnitTest reflection API to inspect test // results. Here we discount failures from the tests we expected to fail. int unexpectedly_failed_tests = 0; for (int i = 0; i < unit_test.total_test_case_count(); ++i) { const TestCase& test_case = *unit_test.GetTestCase(i); for (int j = 0; j < test_case.total_test_count(); ++j) { const TestInfo& test_info = *test_case.GetTestInfo(j); // Counts failed tests that were not meant to fail (those without // 'Fails' in the name). if (test_info.result()->Failed() && strcmp(test_info.name(), "Fails") != 0) { unexpectedly_failed_tests++; } } } // Test that were meant to fail should not affect the test program outcome. if (unexpectedly_failed_tests == 0) ret_val = 0; return ret_val; } diff --git a/googletest/scripts/upload.py b/googletest/scripts/upload.py index 6e6f9a14..81e8e04d 100755 --- a/googletest/scripts/upload.py +++ b/googletest/scripts/upload.py @@ -1,1387 +1,1387 @@ #!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tool for uploading diffs from a version control system to the codereview app. Usage summary: upload.py [options] [-- diff_options] Diff options are passed to the diff command of the underlying system. Supported version control systems: Git Mercurial Subversion It is important for Git/Mercurial users to specify a tree/node/branch to diff against by using the '--rev' option. """ # This code is derived from appcfg.py in the App Engine SDK (open source), # and from ASPN recipe #146306. import cookielib import getpass import logging import md5 import mimetypes import optparse import os import re import socket import subprocess import sys import urllib import urllib2 import urlparse try: import readline except ImportError: pass # The logging verbosity: # 0: Errors only. # 1: Status messages. # 2: Info logs. # 3: Debug logs. verbosity = 1 # Max size of patch or base file. MAX_UPLOAD_SIZE = 900 * 1024 def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email def StatusUpdate(msg): """Print a status message to stdout. If 'verbosity' is greater than 0, print the message. Args: msg: The string to print. """ if verbosity > 0: print msg def ErrorExit(msg): """Print an error message to stderr and exit.""" print >>sys.stderr, msg sys.exit(1) class ClientLoginError(urllib2.HTTPError): """Raised to indicate there was an error authenticating with ClientLogin.""" def __init__(self, url, code, msg, headers, args): urllib2.HTTPError.__init__(self, url, code, msg, headers, None) self.args = args self.reason = args["Error"] class AbstractRpcServer(object): """Provides a common interface for a simple RPC server.""" def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False): """Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. save_cookies: If True, save the authentication cookies to local disk. If False, use an in-memory cookiejar instead. Subclasses must implement this functionality. Defaults to False. """ self.host = host self.host_override = host_override self.auth_function = auth_function self.authenticated = False self.extra_headers = extra_headers self.save_cookies = save_cookies self.opener = self._GetOpener() if self.host_override: logging.info("Server: %s; Host: %s", self.host, self.host_override) else: logging.info("Server: %s", self.host) def _GetOpener(self): """Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object. """ raise NotImplementedError() def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com"): # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True def _Authenticate(self): """Authenticates the user. 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). 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. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.reason == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.reason == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.reason == "NotVerified": print >>sys.stderr, "Account not verified." break if e.reason == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.reason == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.reason == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.reason == "ServiceDisabled": print >>sys.stderr, ("The user's access to the service has been " "disabled.") break if e.reason == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401: self._Authenticate() ## elif e.code >= 500 and e.code < 600: ## # Server Error - try again. ## continue else: raise finally: socket.setdefaulttimeout(old_timeout) class HttpRpcServer(AbstractRpcServer): """Provides a simplified RPC-style interface for HTTP requests.""" def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save() def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies") self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]") parser.add_option("-y", "--assume_yes", action="store_true", dest="assume_yes", default=False, help="Assume that the answer to yes/no questions is 'yes'.") # Logging group = parser.add_option_group("Logging options") group.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose", help="Print errors only.") group.add_option("-v", "--verbose", action="store_const", const=2, dest="verbose", default=1, help="Print info level logs (default).") group.add_option("--noisy", action="store_const", const=3, dest="verbose", help="Print all logs.") # Review server group = parser.add_option_group("Review server options") group.add_option("-s", "--server", action="store", dest="server", default="codereview.appspot.com", metavar="SERVER", help=("The server to upload to. The format is host[:port]. " "Defaults to 'codereview.appspot.com'.")) group.add_option("-e", "--email", action="store", dest="email", metavar="EMAIL", default=None, help="The username to use. Will prompt if omitted.") group.add_option("-H", "--host", action="store", dest="host", metavar="HOST", default=None, help="Overrides the Host header sent with all RPCs.") group.add_option("--no_cookies", action="store_false", dest="save_cookies", default=True, help="Do not save authentication cookies to local disk.") # Issue group = parser.add_option_group("Issue options") group.add_option("-d", "--description", action="store", dest="description", metavar="DESCRIPTION", default=None, help="Optional description when creating an issue.") group.add_option("-f", "--description_file", action="store", dest="description_file", metavar="DESCRIPTION_FILE", default=None, help="Optional path of a file that contains " "the description when creating an issue.") group.add_option("-r", "--reviewers", action="store", dest="reviewers", metavar="REVIEWERS", default=None, help="Add reviewers (comma separated email addresses).") group.add_option("--cc", action="store", dest="cc", metavar="CC", default=None, help="Add CC (comma separated email addresses).") # Upload options group = parser.add_option_group("Patch options") group.add_option("-m", "--message", action="store", dest="message", metavar="MESSAGE", default=None, help="A message to identify the patch. " "Will prompt if omitted.") group.add_option("-i", "--issue", type="int", action="store", metavar="ISSUE", default=None, help="Issue number to which to add. Defaults to new issue.") group.add_option("--download_base", action="store_true", dest="download_base", default=False, help="Base files will be downloaded by the server " "(side-by-side diffs may not work on files with CRs).") group.add_option("--rev", action="store", dest="revision", metavar="REV", default=None, help="Branch/tree/revision to diff against (used by DVCS).") group.add_option("--send_mail", action="store_true", dest="send_mail", default=False, help="Send notification email to reviewers.") def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies) def EncodeMultipartFormData(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for (key, value) in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, value) in files: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % GetContentType(filename)) lines.append('') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def GetContentType(filename): """Helper to guess the content-type from the filename.""" return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # Use a shell for subcommands on Windows to get a PATH search. use_shell = sys.platform.startswith("win") def RunShellWithReturnCode(command, print_output=False, universal_newlines=True): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode def RunShell(command, silent_ok=False, universal_newlines=True, print_output=False): data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines) if retcode: ErrorExit("Got error status from %s:\n%s" % (command, data)) if not silent_ok and not data: ErrorExit("No output from %s" % command) return data class VersionControlSystem(object): """Abstract base class providing an interface to the VCS.""" def __init__(self, options): """Constructor. Args: options: Command line options. """ self.options = options def GenerateDiff(self, args): """Return the current diff as a string. Args: args: Extra arguments to pass to the diff command. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted") def GetBaseFile(self, filename): """Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = filename.strip().replace('\\', '/') files[filename] = self.GetBaseFile(filename) return files def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" file_too_large = False if is_base: type = "base" else: type = "current" if len(content) > MAX_UPLOAD_SIZE: print ("Not uploading the %s file for %s because it's too large." % (type, filename)) file_too_large = True content = "" checksum = md5.new(content).hexdigest() if options.verbose > 0 and not file_too_large: print "Uploading %s file for %s" % (type, filename) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) form_fields = [("filename", filename), ("status", status), ("checksum", checksum), ("is_binary", str(is_binary)), ("is_current", str(not is_base)), ] if file_too_large: form_fields.append(("file_too_large", "1")) if options.email: form_fields.append(("user", options.email)) ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)]) response_body = rpc_server.Send(url, body, content_type=ctype) if not response_body.startswith("OK"): StatusUpdate(" --> %s" % response_body) sys.exit(1) patches = dict() [patches.setdefault(v, k) for k, v in patch_list] for filename in patches.keys(): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: base_content = None file_id_str = file_id_str[file_id_str.rfind("_") + 1:] file_id = int(file_id_str) if base_content != None: UploadFile(filename, file_id, base_content, is_binary, status, True) if new_content != None: UploadFile(filename, file_id, new_content, is_binary, status, False) def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/") class SubversionVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Subversion.""" def __init__(self, options): super(SubversionVCS, self).__init__(options) if self.options.revision: match = re.match(r"(\d+)(:(\d+))?", self.options.revision) if not match: ErrorExit("Invalid Subversion revision %s." % self.options.revision) self.rev_start = match.group(1) self.rev_end = match.group(3) else: self.rev_start = self.rev_end = None # Cache output from "svn list -r REVNO dirname". - # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev). + # Keys: dirname, Values: 2-tuple (output for start rev and end rev). self.svnls_cache = {} # SVN base URL is required to fetch files deleted in an older revision. # Result is cached to not guess it over and over again in GetBaseFile(). required = self.options.download_base or self.options.revision is not None self.svn_base = self._GuessBase(required) def GuessBase(self, required): """Wrapper for _GuessBase.""" return self.svn_base def _GuessBase(self, required): """Returns the SVN base URL. Args: required: If true, exits if the url can't be guessed, otherwise None is returned. """ info = RunShell(["svn", "info"]) for line in info.splitlines(): words = line.split() if len(words) == 2 and words[0] == "URL:": url = words[1] scheme, netloc, path, params, query, fragment = urlparse.urlparse(url) username, netloc = urllib.splituser(netloc) if username: logging.info("Removed username from base URL") if netloc.endswith("svn.python.org"): if netloc == "svn.python.org": if path.startswith("/projects/"): path = path[9:] elif netloc != "pythondev@svn.python.org": ErrorExit("Unrecognized Python URL: %s" % url) base = "http://svn.python.org/view/*checkout*%s/" % path logging.info("Guessed Python base = %s", base) elif netloc.endswith("svn.collab.net"): if path.startswith("/repos/"): path = path[6:] base = "http://svn.collab.net/viewvc/*checkout*%s/" % path logging.info("Guessed CollabNet base = %s", base) elif netloc.endswith(".googlecode.com"): path = path + "/" base = urlparse.urlunparse(("http", netloc, path, params, query, fragment)) logging.info("Guessed Google Code base = %s", base) else: path = path + "/" base = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) logging.info("Guessed base = %s", base) return base if required: ErrorExit("Can't find URL in output from svn info") return None def GenerateDiff(self, args): cmd = ["svn", "diff"] if self.options.revision: cmd += ["-r", self.options.revision] cmd.extend(args) data = RunShell(cmd) count = 0 for line in data.splitlines(): if line.startswith("Index:") or line.startswith("Property changes on:"): count += 1 logging.info(line) if not count: ErrorExit("No valid patches found in output from svn diff") return data def _CollapseKeywords(self, content, keyword_str): """Collapses SVN keywords.""" # 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/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords 'Date': ['Date', 'LastChangedDate'], 'Revision': ['Revision', 'LastChangedRevision', 'Rev'], 'Author': ['Author', 'LastChangedBy'], 'HeadURL': ['HeadURL', 'URL'], 'Id': ['Id'], # Aliases 'LastChangedDate': ['LastChangedDate', 'Date'], 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'], 'LastChangedBy': ['LastChangedBy', 'Author'], 'URL': ['URL', 'HeadURL'], } def repl(m): if m.group(2): return "$%s::%s$" % (m.group(1), " " * len(m.group(3))) return "$%s$" % m.group(1) keywords = [keyword for name in keyword_str.split(" ") for keyword in svn_keywords.get(name, [])] return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content) def GetUnknownFiles(self): status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True) unknown_files = [] for line in status.split("\n"): if line and line[0] == "?": unknown_files.append(line) return unknown_files def ReadFile(self, filename): """Returns the contents of a file.""" file = open(filename, 'rb') result = "" try: result = file.read() finally: file.close() return result def GetStatus(self, filename): """Returns the status of a file.""" if not self.options.revision: status = RunShell(["svn", "status", "--ignore-externals", filename]) if not status: ErrorExit("svn status returned no output for %s" % filename) 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 if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): status = status_lines[2] else: status = status_lines[0] # If we have a revision to diff against we need to run "svn list" # for the old and the new revision and compare the results to get # the correct status for a file. else: dirname, relfilename = os.path.split(filename) if dirname not in self.svnls_cache: cmd = ["svn", "list", "-r", self.rev_start, dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to get status for %s." % filename) old_files = out.splitlines() args = ["svn", "list"] if self.rev_end: args += ["-r", self.rev_end] cmd = args + [dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to run command %s" % cmd) self.svnls_cache[dirname] = (old_files, out.splitlines()) old_files, new_files = self.svnls_cache[dirname] if relfilename in old_files and relfilename not in new_files: status = "D " elif relfilename in old_files and relfilename in new_files: status = "M " else: status = "A " return status def GetBaseFile(self, filename): status = self.GetStatus(filename) base_content = None new_content = None # If a file is copied its status will be "A +", which signifies # "addition-with-history". See "svn st" for more information. We need to # upload the original file or else diff parsing will fail if the file was # edited. if status[0] == "A" and status[3] != "+": # We'll need to upload the new content if we're adding a binary file # since diff's output won't contain it. mimetype = RunShell(["svn", "propget", "svn:mime-type", filename], silent_ok=True) base_content = "" is_binary = mimetype and not mimetype.startswith("text/") if is_binary and self.IsImage(filename): new_content = self.ReadFile(filename) elif (status[0] in ("M", "D", "R") or (status[0] == "A" and status[3] == "+") or # Copied file. (status[0] == " " and status[1] == "M")): # Property change. args = [] if self.options.revision: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: # Don't change filename, it's needed later. url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:mime-type", url] mimetype, returncode = RunShellWithReturnCode(cmd) if returncode: # File does not exist in the requested revision. # Reset mimetype, it contains an error message. mimetype = "" get_base = False is_binary = mimetype and not mimetype.startswith("text/") if status[0] == " ": # Empty base content just to force an upload. base_content = "" elif is_binary: if self.IsImage(filename): get_base = True if status[0] == "M": if not self.rev_end: new_content = self.ReadFile(filename) else: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end) new_content = RunShell(["svn", "cat", url], universal_newlines=True, silent_ok=True) else: base_content = "" else: get_base = True if get_base: if is_binary: universal_newlines = False else: universal_newlines = True if self.rev_start: # "svn cat -r REV delete_file.txt" doesn't work. cat requires # the full URL with "@REV" appended instead of using "-r" option. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) base_content = RunShell(["svn", "cat", url], universal_newlines=universal_newlines, silent_ok=True) else: base_content = RunShell(["svn", "cat", filename], universal_newlines=universal_newlines, silent_ok=True) if not is_binary: args = [] if self.rev_start: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:keywords", url] keywords, returncode = RunShellWithReturnCode(cmd) if keywords and not returncode: base_content = self._CollapseKeywords(base_content, keywords) else: StatusUpdate("svn status returned unexpected output: %s" % status) sys.exit(1) return base_content, new_content, is_binary, status[0:5] class GitVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Git.""" def __init__(self, options): super(GitVCS, self).__init__(options) # Map of filename -> hash of base file. self.base_hashes = {} def GenerateDiff(self, extra_args): # This is more complicated than svn's GenerateDiff because we must convert # the diff output to include an svn-style "Index:" line as well as record # the hashes of the base files, so we can upload them along with our diff. if self.options.revision: extra_args = [self.options.revision] + extra_args gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args) svndiff = [] filecount = 0 filename = None for line in gitdiff.splitlines(): match = re.match(r"diff --git a/(.*) b/.*$", line) if match: filecount += 1 filename = match.group(1) svndiff.append("Index: %s\n" % filename) else: # The "index" line in a git diff looks like this (long hashes elided): # index 82c0d44..b2cee3f 100755 # We want to save the left hash, as that identifies the base file. match = re.match(r"index (\w+)\.\.", line) if match: self.base_hashes[filename] = match.group(1) svndiff.append(line + "\n") if not filecount: ErrorExit("No valid patches found in output from git diff") return "".join(svndiff) def GetUnknownFiles(self): status = RunShell(["git", "ls-files", "--exclude-standard", "--others"], silent_ok=True) return status.splitlines() def GetBaseFile(self, filename): hash = self.base_hashes[filename] base_content = None new_content = None is_binary = False if hash == "0" * 40: # All-zero hash indicates no base file. status = "A" base_content = "" else: status = "M" base_content, returncode = RunShellWithReturnCode(["git", "show", hash]) if returncode: ErrorExit("Got error status from 'git show %s'" % hash) return (base_content, new_content, is_binary, status) class MercurialVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Mercurial.""" def __init__(self, options, repo_dir): super(MercurialVCS, self).__init__(options) # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo_dir) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") if self.options.revision: self.base_rev = self.options.revision else: self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip() def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), filename return filename[len(self.subdir):].lstrip(r"\/") def GenerateDiff(self, extra_args): # If no file specified, restrict to the current subdir extra_args = extra_args or ["."] cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args data = RunShell(cmd, silent_ok=True) svndiff = [] filecount = 0 for line in data.splitlines(): m = re.match("diff --git a/(\S+) b/(\S+)", line) if m: # Modify line to make it look like as it comes from svn diff. # With this modification no changes on the server side are required # to make upload.py work with Mercurial repos. # NOTE: for proper handling of moved/copied files, we have to use # the second filename. filename = m.group(2) svndiff.append("Index: %s" % filename) svndiff.append("=" * 67) filecount += 1 logging.info(line) else: svndiff.append(line) if not filecount: ErrorExit("No valid patches found in output from hg diff") return "\n".join(svndiff) + "\n" def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files def GetBaseFile(self, filename): # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -C" returns two lines for moved/copied files, one otherwise out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) out = out.splitlines() # HACK: strip error message about missing file/directory if it isn't in # the working copy if out[0].startswith('%s: ' % relpath): out = out[1:] if len(out) > 1: # Moved/copied => considered as modified, use old filename to # retrieve base contents oldrelpath = out[1].strip() status = "M" else: status, _ = out[0].split(' ', 1) if status != "A": base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], silent_ok=True) is_binary = "\0" in base_content # Mercurial's heuristic if status != "R": new_content = open(relpath, "rb").read() is_binary = is_binary or "\0" in new_content if is_binary and base_content: # Fetch again without converting newlines base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], silent_ok=True, universal_newlines=False) if not is_binary or not self.IsImage(relpath): new_content = None return base_content, new_content, is_binary, status # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = temp_filename.strip().replace('\\', '/') if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv def GuessVCS(options): """Helper to guess the version control system. This examines the current directory, guesses which VersionControlSystem we're using, and returns an instance of the appropriate class. Exit with an error if we can't figure it out. Returns: A VersionControlSystem instance. Exits if the VCS can't be guessed. """ # Mercurial has a command to get the base directory of a repository # Try running it, but don't die if we don't have hg installed. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy. try: out, returncode = RunShellWithReturnCode(["hg", "root"]) if returncode == 0: return MercurialVCS(options, out.strip()) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have hg installed. raise # Subversion has a .svn in all working directories. if os.path.isdir('.svn'): logging.info("Guessed VCS = Subversion") return SubversionVCS(options) # Git has a command to test if you're in a git tree. # Try running it, but don't die if we don't have git installed. try: out, returncode = RunShellWithReturnCode(["git", "rev-parse", "--is-inside-work-tree"]) if returncode == 0: return GitVCS(options) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have git installed. raise ErrorExit(("Could not guess version control system. " "Are you in a working copy directory?")) def RealMain(argv, data=None): """The real main function. Args: argv: Command line arguments. data: Diff contents. If None (default) the diff is generated by the VersionControlSystem implementation returned by GuessVCS(). Returns: A 2-tuple (issue id, patchset id). The patchset id is None if the base files are not uploaded by this script (applies only to SVN checkouts). """ logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:" "%(lineno)s %(message)s ")) os.environ['LC_ALL'] = 'C' options, args = parser.parse_args(argv[1:]) global verbosity verbosity = options.verbose if verbosity >= 3: logging.getLogger().setLevel(logging.DEBUG) elif verbosity >= 2: logging.getLogger().setLevel(logging.INFO) vcs = GuessVCS(options) if isinstance(vcs, SubversionVCS): # base field is only allowed for Subversion. # Note: Fetching base files may become deprecated in future releases. base = vcs.GuessBase(options.download_base) else: base = None if not base and options.download_base: options.download_base = True logging.info("Enabled upload of base file") if not options.assume_yes: vcs.CheckForUnknownFiles() if data is None: data = vcs.GenerateDiff(args) files = vcs.GetBaseFiles(data) if verbosity >= 1: print "Upload server:", options.server, "(change with -s/--server)" if options.issue: prompt = "Message describing this patch set: " else: prompt = "New issue subject: " message = options.message or raw_input(prompt).strip() if not message: ErrorExit("A non-empty message is required") rpc_server = GetRpcServer(options) form_fields = [("subject", message)] if base: form_fields.append(("base", base)) if options.issue: form_fields.append(("issue", str(options.issue))) if options.email: form_fields.append(("user", options.email)) if options.reviewers: for reviewer in options.reviewers.split(','): if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1: ErrorExit("Invalid email address: %s" % reviewer) form_fields.append(("reviewers", options.reviewers)) if options.cc: for cc in options.cc.split(','): if "@" in cc and not cc.split("@")[1].count(".") == 1: ErrorExit("Invalid email address: %s" % cc) form_fields.append(("cc", options.cc)) description = options.description if options.description_file: if options.description: ErrorExit("Can't specify description and description_file") file = open(options.description_file, 'r') description = file.read() file.close() if description: form_fields.append(("description", description)) # Send a hash of all the base file so the server can determine if a copy # already exists in an earlier patchset. base_hashes = "" for file, info in files.iteritems(): if not info[0] is None: checksum = md5.new(info[0]).hexdigest() if base_hashes: base_hashes += "|" base_hashes += checksum + ":" + file form_fields.append(("base_hashes", base_hashes)) # If we're uploading base files, don't send the email before the uploads, so # that it contains the file status. if options.send_mail and options.download_base: form_fields.append(("send_mail", "1")) if not options.download_base: form_fields.append(("content_upload", "1")) if len(data) > MAX_UPLOAD_SIZE: print "Patch is large, so uploading file patches separately." uploaded_diff_file = [] form_fields.append(("separate_patches", "1")) else: uploaded_diff_file = [("data", "data.diff", data)] ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) response_body = rpc_server.Send("/upload", body, content_type=ctype) patchset = None if not options.download_base or not uploaded_diff_file: lines = response_body.splitlines() if len(lines) >= 2: msg = lines[0] patchset = lines[1].strip() patches = [x.split(" ", 1) for x in lines[2:]] else: msg = response_body else: msg = response_body StatusUpdate(msg) if not response_body.startswith("Issue created.") and \ not response_body.startswith("Issue updated."): sys.exit(0) issue = msg[msg.rfind("/")+1:] if not uploaded_diff_file: result = UploadSeparatePatches(issue, rpc_server, patchset, data, options) if not options.download_base: patches = result if not options.download_base: vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files) if options.send_mail: rpc_server.Send("/" + issue + "/mail", payload="") return issue, patchset def main(): try: RealMain(sys.argv) except KeyboardInterrupt: print StatusUpdate("Interrupted.") sys.exit(1) if __name__ == "__main__": main() diff --git a/googletest/src/gtest-death-test.cc b/googletest/src/gtest-death-test.cc index fd1cc3fc..fca10355 100644 --- a/googletest/src/gtest-death-test.cc +++ b/googletest/src/gtest-death-test.cc @@ -1,1341 +1,1341 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) // // This file implements death tests. #include "gtest/gtest-death-test.h" #include "gtest/internal/gtest-port.h" #include "gtest/internal/custom/gtest.h" #if GTEST_HAS_DEATH_TEST # if GTEST_OS_MAC # include <crt_externs.h> # endif // GTEST_OS_MAC # include <errno.h> # include <fcntl.h> # include <limits.h> # if GTEST_OS_LINUX # include <signal.h> # endif // GTEST_OS_LINUX # include <stdarg.h> # if GTEST_OS_WINDOWS # include <windows.h> # else # include <sys/mman.h> # include <sys/wait.h> # endif // GTEST_OS_WINDOWS # if GTEST_OS_QNX # include <spawn.h> # endif // GTEST_OS_QNX #endif // GTEST_HAS_DEATH_TEST #include "gtest/gtest-message.h" #include "gtest/internal/gtest-string.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick exists to // prevent the accidental inclusion of gtest-internal-inl.h in the // user's code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ namespace testing { // Constants. // The default death test style. static const char kDefaultDeathTestStyle[] = "fast"; GTEST_DEFINE_string_( death_test_style, internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\"threadsafe\" (child process re-executes the test binary " "from the beginning, running only the specific death test) or " "\"fast\" (child process runs the death test immediately " "after forking)."); GTEST_DEFINE_bool_( death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " "it sees an unsupported combination of clone() flags. " "It is not recommended to use this flag w/o valgrind though it will " "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed."); namespace internal { GTEST_DEFINE_string_( internal_run_death_test, "", "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " "the '|' characters. This flag is specified if and only if the current " "process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY."); } // namespace internal #if GTEST_HAS_DEATH_TEST 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 static bool g_in_fast_death_test_child = false; # endif // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as // Valgrind heap checkers may need this to modify their behavior in death // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. bool InDeathTestChild() { # if GTEST_OS_WINDOWS // On Windows, death tests are thread-safe regardless of the value of the // death_test_style flag. return !GTEST_FLAG(internal_run_death_test).empty(); # else if (GTEST_FLAG(death_test_style) == "threadsafe") return !GTEST_FLAG(internal_run_death_test).empty(); else return g_in_fast_death_test_child; #endif } } // namespace internal // ExitedWithCode constructor. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { } // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { # if GTEST_OS_WINDOWS return exit_status == exit_code_; # else return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; # endif // GTEST_OS_WINDOWS } # if !GTEST_OS_WINDOWS // KilledBySignal constructor. KilledBySignal::KilledBySignal(int signum) : signum_(signum) { } // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) { bool result; if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { return result; } } # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } # endif // !GTEST_OS_WINDOWS namespace internal { // Utilities needed for death tests. // Generates a textual description of a given exit code, in the format // specified by wait(2). static std::string ExitSummary(int exit_code) { Message m; # if GTEST_OS_WINDOWS m << "Exited with exit status " << exit_code; # else if (WIFEXITED(exit_code)) { m << "Exited with exit status " << WEXITSTATUS(exit_code); } else if (WIFSIGNALED(exit_code)) { m << "Terminated by signal " << WTERMSIG(exit_code); } # ifdef WCOREDUMP if (WCOREDUMP(exit_code)) { m << " (core dumped)"; } # endif # endif // GTEST_OS_WINDOWS return m.GetString(); } // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } # if !GTEST_OS_WINDOWS // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the // caller not to pass a thread_count of 1. static std::string DeathTestThreadWarning(size_t thread_count) { Message msg; msg << "Death tests use fork(), which is unsafe particularly" << " in a threaded context. For this test, " << GTEST_NAME_ << " "; if (thread_count == 0) msg << "couldn't detect the number of threads."; else msg << "detected " << thread_count << " threads."; return msg.GetString(); } # endif // !GTEST_OS_WINDOWS // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; static const char kDeathTestReturned = 'R'; static const char kDeathTestThrew = 'T'; static const char kDeathTestInternalError = 'I'; // An enumeration describing all of the possible ways that a death test can // conclude. DIED means that the process died while executing the test // code; LIVED means that process lived beyond the end of the test code; // RETURNED means that the test statement attempted to execute a return // statement, which is not allowed; THREW means that the test statement // returned control by throwing an exception. IN_PROGRESS means the test // has not yet concluded. // TODO(vladl@google.com): Unify names and possibly values for // AbortReason, DeathTestOutcome, and flag characters above. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; // Routine for aborting the program which is safe to call from an // exec-style death test child process, in which case the error // message is propagated back to the parent process. Otherwise, the // message is simply printed to stderr. In either case, the program // then exits with status 1. void DeathTestAbort(const std::string& message) { // On a POSIX system, this function may be called from a threadsafe-style // death test child process, which operates on a very small stack. Use // the heap for any additional non-minuscule memory requirements. const InternalRunDeathTestFlag* const flag = GetUnitTestImpl()->internal_run_death_test_flag(); if (flag != NULL) { FILE* parent = posix::FDOpen(flag->write_fd(), "w"); fputc(kDeathTestInternalError, parent); fprintf(parent, "%s", message.c_str()); fflush(parent); _exit(1); } else { fprintf(stderr, "%s", message.c_str()); fflush(stderr); posix::Abort(); } } // A replacement for CHECK that calls DeathTestAbort if the assertion // fails. # define GTEST_DEATH_TEST_CHECK_(expression) \ do { \ if (!::testing::internal::IsTrue(expression)) { \ DeathTestAbort( \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + ::testing::internal::StreamableToString(__LINE__) + ": " \ + #expression); \ } \ } while (::testing::internal::AlwaysFalse()) // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for // evaluating any system call that fulfills two conditions: it must return // -1 on failure, and set errno to EINTR when it is interrupted and // should be tried again. The macro expands to a loop that repeatedly // evaluates the expression as long as it evaluates to -1 and sets // errno to EINTR. If the expression evaluates to -1 but errno is // something other than EINTR, DeathTestAbort is called. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ do { \ int gtest_retval; \ do { \ gtest_retval = (expression); \ } while (gtest_retval == -1 && errno == EINTR); \ if (gtest_retval == -1) { \ DeathTestAbort( \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + ::testing::internal::StreamableToString(__LINE__) + ": " \ + #expression + " != -1"); \ } \ } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. std::string GetLastErrnoDescription() { return errno == 0 ? "" : posix::StrError(errno); } // This is called from a death test parent process to read a failure // message from the death test child process and log it with the FATAL // severity. On Windows, the message is read from a pipe handle. On other // platforms, it is read from a file descriptor. static void FailFromInternalError(int fd) { Message error; char buffer[256]; int num_read; do { while ((num_read = posix::Read(fd, buffer, 255)) > 0) { buffer[num_read] = '\0'; error << buffer; } } while (num_read == -1 && errno == EINTR); if (num_read == 0) { GTEST_LOG_(FATAL) << error.GetString(); } else { const int last_error = errno; GTEST_LOG_(FATAL) << "Error while reading death test internal: " << GetLastErrnoDescription() << " [" << last_error << "]"; } } // Death test constructor. Increments the running death test count // for the current test. DeathTest::DeathTest() { TestInfo* const info = GetUnitTestImpl()->current_test_info(); if (info == NULL) { DeathTestAbort("Cannot run a death test outside of a TEST or " "TEST_F construct"); } } // Creates and returns a death test by dispatching to the current // death test factory. bool DeathTest::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { return GetUnitTestImpl()->death_test_factory()->Create( statement, regex, file, line, test); } const char* DeathTest::LastMessage() { return last_death_test_message_.c_str(); } void DeathTest::set_last_death_test_message(const std::string& message) { last_death_test_message_ = message; } std::string DeathTest::last_death_test_message_; // Provides cross platform implementation for some death functionality. class DeathTestImpl : public DeathTest { protected: DeathTestImpl(const char* a_statement, const RE* a_regex) : statement_(a_statement), regex_(a_regex), spawned_(false), status_(-1), outcome_(IN_PROGRESS), read_fd_(-1), write_fd_(-1) {} // read_fd_ is expected to be closed and cleared by a derived class. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } void Abort(AbortReason reason); virtual bool Passed(bool status_ok); const char* statement() const { return statement_; } const RE* regex() const { return regex_; } bool spawned() const { return spawned_; } void set_spawned(bool is_spawned) { spawned_ = is_spawned; } int status() const { return status_; } void set_status(int a_status) { status_ = a_status; } DeathTestOutcome outcome() const { return outcome_; } void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } int read_fd() const { return read_fd_; } void set_read_fd(int fd) { read_fd_ = fd; } int write_fd() const { return write_fd_; } void set_write_fd(int fd) { write_fd_ = fd; } // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void ReadAndInterpretStatusByte(); private: // The textual content of the code this object is testing. This class // doesn't own this string and should not attempt to delete it. const char* const statement_; // The regular expression which test output must match. DeathTestImpl // doesn't own this object and should not attempt to delete it. const RE* const regex_; // True if the death test child process has been successfully spawned. bool spawned_; // The exit status of the child process. int status_; // How the death test concluded. DeathTestOutcome outcome_; // Descriptor to the read end of the pipe to the child process. It is // always -1 in the child process. The child keeps its write end of the // pipe in write_fd_. int read_fd_; // Descriptor to the child's write end of the pipe to the parent process. // It is always -1 in the parent process. The parent keeps its end of the // pipe in read_fd_. int write_fd_; }; // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void DeathTestImpl::ReadAndInterpretStatusByte() { char flag; int bytes_read; // The read() here blocks until data is available (signifying the // failure of the death test) or until the pipe is closed (signifying // its success), so it's okay to call this in the parent before // the child process has exited. do { bytes_read = posix::Read(read_fd(), &flag, 1); } while (bytes_read == -1 && errno == EINTR); if (bytes_read == 0) { set_outcome(DIED); } else if (bytes_read == 1) { switch (flag) { case kDeathTestReturned: set_outcome(RETURNED); break; case kDeathTestThrew: set_outcome(THREW); break; case kDeathTestLived: set_outcome(LIVED); break; case kDeathTestInternalError: FailFromInternalError(read_fd()); // Does not return. break; default: GTEST_LOG_(FATAL) << "Death test child process reported " << "unexpected status byte (" << static_cast<unsigned int>(flag) << ")"; } } else { GTEST_LOG_(FATAL) << "Read from death test child process failed: " << GetLastErrnoDescription(); } GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); set_read_fd(-1); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. // Writes a status byte to the child's status file descriptor, then // calls _exit(1). void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte // to the pipe, then exit. const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., // when built as Windows DLL), destructors of global objects will still // run after calling _exit(). On such systems, write_fd_ will be // indirectly closed from the destructor of UnitTestImpl, causing double // close if it is also closed here. On debug configurations, double close // may assert. As there are no in-process buffers to flush here, we are // relying on the OS to close the descriptor after the process terminates // when the destructors are not run. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) } // Returns an indented copy of stderr output for a death test. // This makes distinguishing death test output lines from regular log lines // much easier. static ::std::string FormatDeathTestOutput(const ::std::string& output) { ::std::string ret; for (size_t at = 0; ; ) { const size_t line_end = output.find('\n', at); ret += "[ DEATH ] "; if (line_end == ::std::string::npos) { ret += output.substr(at); break; } ret += output.substr(at, line_end + 1 - at); at = line_end + 1; } return ret; } // Assesses the success or failure of a death test, using both private // members which have previously been set, and one argument: // // Private data members: // outcome: An enumeration describing how the death test // concluded: DIED, LIVED, THREW, or RETURNED. The death test // fails in the latter three cases. // status: The exit status of the child process. On *nix, it is in the // in the format specified by wait(2). On Windows, this is the // value supplied to the ExitProcess() API or a numeric code // of the exception that terminated the program. // regex: A regular expression object to be applied to // the test's captured standard error output; the death test // fails if it does not match. // // Argument: // status_ok: true if exit_status is acceptable in the context of // this particular death test, which fails if it is false // // Returns true iff all of the above conditions are met. Otherwise, the // first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { if (!spawned()) return false; const std::string error_message = GetCapturedStderr(); bool success = false; Message buffer; buffer << "Death test: " << statement() << "\n"; switch (outcome()) { case LIVED: buffer << " Result: failed to die.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case THREW: buffer << " Result: threw an exception.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case RETURNED: buffer << " Result: illegal return in test statement.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case DIED: if (status_ok) { const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); if (matched) { success = true; } else { buffer << " Result: died but not with expected error.\n" << " Expected: " << regex()->pattern() << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } } else { buffer << " Result: died but not with expected exit code:\n" << " " << ExitSummary(status()) << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } break; case IN_PROGRESS: default: GTEST_LOG_(FATAL) << "DeathTest::Passed somehow called before conclusion of test"; } DeathTest::set_last_death_test_message(buffer.GetString()); return success; } # if GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the // --gtest_death_test_style=fast setting to be equivalent to // --gtest_death_test_style=threadsafe there. // // A few implementation notes: Like the Linux version, the Windows // implementation uses pipes for child-to-parent communication. But due to // the specifics of pipes on Windows, some extra steps are required: // // 1. The parent creates a communication pipe and stores handles to both // ends of it. // 2. The parent starts the child and provides it with the information // necessary to acquire the handle to the write end of the pipe. // 3. The child acquires the write end of the pipe and signals the parent // using a Windows event. // 4. Now the parent can release the write end of the pipe on its side. If // this is done before step 3, the object's reference count goes down to // 0 and it is destroyed, preventing the child from acquiring it. The // parent now has to release it, or read operations on the read end of // the pipe will not return when the child terminates. // 5. The parent reads child's output through the pipe (outcome code and // any possible error messages) from the pipe, and its stderr and then // determines whether to fail the test. // // Note: to distinguish Win32 API calls from the local method and function // calls, the former are explicitly resolved in the global namespace. // class WindowsDeathTest : public DeathTestImpl { public: WindowsDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} // All of these virtual functions are inherited from DeathTest. virtual int Wait(); virtual TestRole AssumeRole(); private: // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; // Handle to the write end of the pipe to the child process. AutoHandle write_handle_; // Child process handle. AutoHandle child_handle_; // Event the child process uses to signal the parent that it has // acquired the handle to the write end of the pipe. After seeing this // event the parent can release its own handles to make sure its // ReadFile() calls return when the child terminates. AutoHandle event_handle_; }; // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int WindowsDeathTest::Wait() { if (!spawned()) return 0; // Wait until the child either signals that it has acquired the write end // of the pipe or it dies. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; switch (::WaitForMultipleObjects(2, wait_handles, FALSE, // Waits for any of the handles. INFINITE)) { case WAIT_OBJECT_0: case WAIT_OBJECT_0 + 1: break; default: GTEST_DEATH_TEST_CHECK_(false); // Should not get here. } // The child has acquired the write end of the pipe or exited. // We release the handle on our side and continue. write_handle_.Reset(); event_handle_.Reset(); ReadAndInterpretStatusByte(); // Waits for the child process to exit if it haven't already. This // returns immediately if the child has already exited, regardless of // whether previous calls to WaitForMultipleObjects synchronized on this // handle or not. GTEST_DEATH_TEST_CHECK_( WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), INFINITE)); DWORD status_code; GTEST_DEATH_TEST_CHECK_( ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); child_handle_.Reset(); set_status(static_cast<int>(status_code)); return status(); } // The AssumeRole process for a Windows death test. It creates a child // process with the same executable as the current process to run the // death test. The child process is given the --gtest_filter and // --gtest_internal_run_death_test flags such that it knows to run the // current death test only. DeathTest::TestRole WindowsDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != NULL) { // ParseInternalRunDeathTestFlag() has performed all the necessary // processing. set_write_fd(flag->write_fd()); return EXECUTE_TEST; } // WindowsDeathTest uses an anonymous pipe to communicate results of // a death test. SECURITY_ATTRIBUTES handles_are_inheritable = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; HANDLE read_handle, write_handle; GTEST_DEATH_TEST_CHECK_( ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, 0) // Default buffer size. != FALSE); set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY)); write_handle_.Reset(write_handle); event_handle_.Reset(::CreateEvent( &handles_are_inheritable, TRUE, // The event will automatically reset to non-signaled state. FALSE, // The initial state is non-signalled. NULL)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_case_name() + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) + // size_t has the same width as pointers on both 32-bit and 64-bit // Windows platforms. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); char executable_path[_MAX_PATH + 1]; // NOLINT GTEST_DEATH_TEST_CHECK_( _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, executable_path, _MAX_PATH)); std::string command_line = std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + internal_flag + "\""; DeathTest::set_last_death_test_message(""); CaptureStderr(); // Flush the log buffers since the log streams are shared with the child. FlushInfoLog(); // The child process will share the standard handles with the parent. STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(STARTUPINFO)); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION process_info; GTEST_DEATH_TEST_CHECK_(::CreateProcessA( executable_path, const_cast<char*>(command_line.c_str()), NULL, // Retuned process handle is not inheritable. NULL, // Retuned thread handle is not inheritable. TRUE, // Child inherits all inheritable handles (for write_handle_). 0x0, // Default creation flags. NULL, // Inherit the parent's environment. UnitTest::GetInstance()->original_working_dir(), &startup_info, &process_info) != FALSE); child_handle_.Reset(process_info.hProcess); ::CloseHandle(process_info.hThread); set_spawned(true); return OVERSEE_TEST; } # else // We are not on Windows. // ForkingDeathTest provides implementations for most of the abstract // methods of the DeathTest interface. Only the AssumeRole method is // left undefined. class ForkingDeathTest : public DeathTestImpl { public: ForkingDeathTest(const char* statement, const RE* regex); // All of these virtual functions are inherited from DeathTest. virtual int Wait(); protected: void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } private: // PID of child process during death test; 0 in the child process itself. pid_t child_pid_; }; // Constructs a ForkingDeathTest. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {} // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int ForkingDeathTest::Wait() { if (!spawned()) return 0; ReadAndInterpretStatusByte(); int status_value; GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); set_status(status_value); return status_value; } // A concrete death test class that forks, then immediately runs the test // in the child process. class NoExecDeathTest : public ForkingDeathTest { public: NoExecDeathTest(const char* a_statement, const RE* a_regex) : ForkingDeathTest(a_statement, a_regex) { } virtual TestRole AssumeRole(); }; // The AssumeRole process for a fork-and-run death test. It implements a // straightforward fork, with a simple pipe to transmit the status byte. DeathTest::TestRole NoExecDeathTest::AssumeRole() { const size_t thread_count = GetThreadCount(); if (thread_count != 1) { GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); DeathTest::set_last_death_test_message(""); CaptureStderr(); // When we fork the process below, the log file buffers are copied, but the // file descriptors are shared. We flush all log files here so that closing // the file descriptors in the child process doesn't throw off the // synchronization between descriptors and buffers in the parent process. // This is as close to the fork as possible to avoid a race condition in case // there are multiple threads running before the death test, and another // thread writes to the log file. FlushInfoLog(); const pid_t child_pid = fork(); GTEST_DEATH_TEST_CHECK_(child_pid != -1); set_child_pid(child_pid); if (child_pid == 0) { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); set_write_fd(pipe_fd[1]); // Redirects all logging to stderr in the child process to prevent // concurrent writes to the log files. We capture stderr in the parent // process and append the child process' output to a log. LogToStderr(); // Event forwarding to the listeners of event listener API mush be shut // down in death test subprocesses. GetUnitTestImpl()->listeners()->SuppressEventForwarding(); g_in_fast_death_test_child = true; return EXECUTE_TEST; } else { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } } // A concrete death test class that forks and re-executes the main // program from the beginning, with command-line flags set that cause // only this specific death test to be run. class ExecDeathTest : public ForkingDeathTest { public: ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } virtual TestRole AssumeRole(); private: static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() { ::std::vector<std::string> args = GetInjectableArgvs(); # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) ::std::vector<std::string> extra_args = GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); args.insert(args.end(), extra_args.begin(), extra_args.end()); # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) return args; } // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; }; // Utility class for accumulating command-line arguments. class Arguments { public: Arguments() { args_.push_back(NULL); } ~Arguments() { for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); ++i) { free(*i); } } void AddArgument(const char* argument) { args_.insert(args_.end() - 1, posix::StrDup(argument)); } template <typename Str> void AddArguments(const ::std::vector<Str>& arguments) { for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } char* const* Argv() { return &args_[0]; } private: std::vector<char*> args_; }; // A struct that encompasses the arguments to the child process of a // threadsafe-style death test process. struct ExecDeathTestArgs { char* const* argv; // Command-line arguments for the child's call to exec int close_fd; // File descriptor to close; the read end of a pipe }; # if GTEST_OS_MAC inline char** GetEnviron() { // When Google Test is built as a framework on MacOS X, the environ variable // is unavailable. Apple's documentation (man environ) recommends using // _NSGetEnviron() instead. return *_NSGetEnviron(); } # else // Some POSIX platforms expect you to declare environ. extern "C" makes // it reside in the global namespace. extern "C" char** environ; inline char** GetEnviron() { return environ; } # endif // GTEST_OS_MAC # if !GTEST_OS_QNX // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. static int ExecDeathTestChildMain(void* child_arg) { ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } // We can safely call execve() as it's a direct system call. We // cannot use execvp() as it's a libc function and thus potentially // unsafe. Since execve() doesn't search the PATH, the user must // invoke the test program via a valid path that contains at least // one path separator. execve(args->argv[0], args->argv, GetEnviron()); DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + original_dir + " failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } # endif // !GTEST_OS_QNX // Two utility routines that together determine the direction the stack // grows. // This could be accomplished more elegantly by a single recursive // function, but we want to guard against the unlikely possibility of // a smart compiler optimizing the recursion away. // // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining // StackLowerThanAddress into StackGrowsDown, which then doesn't give // correct answer. void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; void StackLowerThanAddress(const void* ptr, bool* result) { int dummy; *result = (&dummy < ptr); } // Make sure AddressSanitizer does not tamper with the stack here. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ bool StackGrowsDown() { int dummy; bool result; StackLowerThanAddress(&dummy, &result); return result; } // Spawns a child process with the same executable as the current process in // a thread-safe manner and instructs it to run the death test. The // implementation uses fork(2) + exec. On systems where clone(2) is // available, it is used instead, being slightly more thread-safe. On QNX, // fork supports only single-threaded environments, so this function uses // spawn(2) there instead. The function dies with an error message if // anything goes wrong. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ExecDeathTestArgs args = { argv, close_fd }; pid_t child_pid = -1; # if GTEST_OS_QNX // Obtains the current directory and sets it to be closed in the child // process. const int cwd_fd = open(".", O_RDONLY); GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } int fd_flags; // Set close_fd to be closed after spawn. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC)); struct inheritance inherit = {0}; // spawn is a system call. child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); // Restores the current working directory. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); # else // GTEST_OS_QNX # if GTEST_OS_LINUX // When a SIGPROF signal is received while fork() or clone() are executing, // the process may hang. To avoid this, we ignore SIGPROF here and re-enable // it after the call to fork()/clone() is complete. struct sigaction saved_sigprof_action; struct sigaction ignore_sigprof_action; memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); sigemptyset(&ignore_sigprof_action.sa_mask); ignore_sigprof_action.sa_handler = SIG_IGN; GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); # endif // GTEST_OS_LINUX # if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG(death_test_use_fork); if (!use_fork) { static const bool stack_grows_down = StackGrowsDown(); const size_t stack_size = getpagesize(); // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); // Maximum stack alignment in bytes: For a downward-growing stack, this // amount is subtracted from size of the stack space to get an address // that is within the stack space and is aligned on all systems we care // about. As far as I know there is no ABI with stack alignment greater // than 64. We assume stack and stack_size already have alignment of // kMaxStackAlignment. const size_t kMaxStackAlignment = 64; void* const stack_top = static_cast<char*>(stack) + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0); child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } # else const bool use_fork = true; # endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { ExecDeathTestChildMain(&args); _exit(0); } # endif // GTEST_OS_QNX # if GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_SYSCALL_( sigaction(SIGPROF, &saved_sigprof_action, NULL)); # endif // GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; } // The AssumeRole process for a fork-and-exec death test. It re-executes the // main program from the beginning, setting the --gtest_filter // and --gtest_internal_run_death_test flags to cause only the current // death test to be re-run. DeathTest::TestRole ExecDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != NULL) { set_write_fd(flag->write_fd()); return EXECUTE_TEST; } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); // Clear the close-on-exec flag on the write end of the pipe, lest // it be closed when the child process does an exec: GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_case_name() + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(pipe_fd[1]); Arguments args; args.AddArguments(GetArgvsForDeathTestChildProcess()); args.AddArgument(filter_flag.c_str()); args.AddArgument(internal_flag.c_str()); DeathTest::set_last_death_test_message(""); CaptureStderr(); // See the comment in NoExecDeathTest::AssumeRole for why the next line // is necessary. FlushInfoLog(); const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_child_pid(child_pid); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } # endif // !GTEST_OS_WINDOWS // Creates a concrete DeathTest-derived class that depends on the // --gtest_death_test_style flag, and sets the pointer pointed to // by the "test" argument to its address. If the test should be // skipped, sets that pointer to NULL. Returns true, unless the // flag is set to an invalid value. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const int death_test_index = impl->current_test_info() ->increment_death_test_count(); if (flag != NULL) { if (death_test_index > flag->index()) { DeathTest::set_last_death_test_message( "Death test count (" + StreamableToString(death_test_index) + ") somehow exceeded expected maximum (" + StreamableToString(flag->index()) + ")"); return false; } if (!(flag->file() == file && flag->line() == line && flag->index() == death_test_index)) { *test = NULL; return true; } } # if GTEST_OS_WINDOWS if (GTEST_FLAG(death_test_style) == "threadsafe" || GTEST_FLAG(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, regex, file, line); } # else if (GTEST_FLAG(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, regex, file, line); } else if (GTEST_FLAG(death_test_style) == "fast") { *test = new NoExecDeathTest(statement, regex); } # endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. DeathTest::set_last_death_test_message( "Unknown death test style \"" + GTEST_FLAG(death_test_style) + "\" encountered"); return false; } return true; } # if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. int GetStatusFileDescriptor(unsigned int parent_process_id, size_t write_handle_as_size_t, size_t event_handle_as_size_t) { AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, // Non-inheritable. parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { DeathTestAbort("Unable to open parent process " + StreamableToString(parent_process_id)); } // TODO(vladl@google.com): Replace the following check with a // compile-time assertion when available. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t); HANDLE dup_write_handle; - // The newly initialized handle is accessible only in in the parent + // The newly initialized handle is accessible only in the parent // process. To obtain one accessible within the child, we need to use // DuplicateHandle. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, ::GetCurrentProcess(), &dup_write_handle, 0x0, // Requested privileges ignored since // DUPLICATE_SAME_ACCESS is used. FALSE, // Request non-inheritable handler. DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the pipe handle " + StreamableToString(write_handle_as_size_t) + " from the parent process " + StreamableToString(parent_process_id)); } const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); HANDLE dup_event_handle; if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE, DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the event handle " + StreamableToString(event_handle_as_size_t) + " from the parent process " + StreamableToString(parent_process_id)); } const int write_fd = ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); if (write_fd == -1) { DeathTestAbort("Unable to convert pipe handle " + StreamableToString(write_handle_as_size_t) + " to a file descriptor"); } // Signals the parent that the write end of the pipe has been acquired // so the parent can release its own write end. ::SetEvent(dup_event_handle); return write_fd; } # endif // GTEST_OS_WINDOWS // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { if (GTEST_FLAG(internal_run_death_test) == "") return NULL; // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we // can use it here. int line = -1; int index = -1; ::std::vector< ::std::string> fields; SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); int write_fd = -1; # if GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; size_t event_handle_as_size_t = 0; if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &parent_process_id) || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); # else if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &write_fd)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } # endif // GTEST_OS_WINDOWS return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); } } // namespace internal #endif // GTEST_HAS_DEATH_TEST } // namespace testing diff --git a/googletest/src/gtest-port.cc b/googletest/src/gtest-port.cc index d80bd80c..5a6eb873 100644 --- a/googletest/src/gtest-port.cc +++ b/googletest/src/gtest-port.cc @@ -1,1241 +1,1241 @@ // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) #include "gtest/internal/gtest-port.h" #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fstream> #if GTEST_OS_WINDOWS # include <windows.h> # include <io.h> # include <sys/stat.h> # include <map> // Used in ThreadLocal. #else # include <unistd.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC # include <mach/mach_init.h> # include <mach/task.h> # include <mach/vm_map.h> #endif // GTEST_OS_MAC #if GTEST_OS_QNX # include <devctl.h> # include <fcntl.h> # include <sys/procfs.h> #endif // GTEST_OS_QNX #if GTEST_OS_AIX # include <procinfo.h> # include <sys/types.h> #endif // GTEST_OS_AIX #include "gtest/gtest-spi.h" #include "gtest/gtest-message.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick exists to // prevent the accidental inclusion of gtest-internal-inl.h in the // user's code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ namespace testing { namespace internal { #if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC and C++Builder do not provide a definition of STDERR_FILENO. const int kStdOutFileno = 1; const int kStdErrFileno = 2; #else const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER #if GTEST_OS_LINUX namespace { template <typename T> T ReadProcFileField(const std::string& filename, int field) { std::string dummy; std::ifstream file(filename.c_str()); while (field-- > 0) { file >> dummy; } T output = 0; file >> output; return output; } } // namespace // Returns the number of active threads, or 0 when there is an error. size_t GetThreadCount() { const std::string filename = (Message() << "/proc/" << getpid() << "/stat").GetString(); return ReadProcFileField<int>(filename, 19); } #elif GTEST_OS_MAC size_t GetThreadCount() { const task_t task = mach_task_self(); mach_msg_type_number_t thread_count; thread_act_array_t thread_list; const kern_return_t status = task_threads(task, &thread_list, &thread_count); if (status == KERN_SUCCESS) { // task_threads allocates resources in thread_list and we need to free them // to avoid leaks. vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list), sizeof(thread_t) * thread_count); return static_cast<size_t>(thread_count); } else { return 0; } } #elif GTEST_OS_QNX // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. size_t GetThreadCount() { const int fd = open("/proc/self/as", O_RDONLY); if (fd < 0) { return 0; } procfs_info process_info; const int status = devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); close(fd); if (status == EOK) { return static_cast<size_t>(process_info.num_threads); } else { return 0; } } #elif GTEST_OS_AIX size_t GetThreadCount() { struct procentry64 entry; pid_t pid = getpid(); int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1); if (status == 1) { return entry.pi_thcount; } else { return 0; } } #else size_t GetThreadCount() { // There's no portable way to detect the number of threads, so we just // return 0 to indicate that we cannot detect it. return 0; } #endif // GTEST_OS_LINUX #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS void SleepMilliseconds(int n) { ::Sleep(n); } AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} AutoHandle::AutoHandle(Handle handle) : handle_(handle) {} AutoHandle::~AutoHandle() { Reset(); } AutoHandle::Handle AutoHandle::Get() const { return handle_; } void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); } void AutoHandle::Reset(HANDLE handle) { // Resetting with the same handle we already own is invalid. if (handle_ != handle) { if (IsCloseable()) { ::CloseHandle(handle_); } handle_ = handle; } else { GTEST_CHECK_(!IsCloseable()) << "Resetting a valid handle to itself is likely a programmer error " "and thus not allowed."; } } bool AutoHandle::IsCloseable() const { // Different Windows APIs may use either of these values to represent an // invalid handle. return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE; } Notification::Notification() : event_(::CreateEvent(NULL, // Default security attributes. TRUE, // Do not reset automatically. FALSE, // Initially unset. NULL)) { // Anonymous event. GTEST_CHECK_(event_.Get() != NULL); } void Notification::Notify() { GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); } void Notification::WaitForNotification() { GTEST_CHECK_( ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); } Mutex::Mutex() : owner_thread_id_(0), type_(kDynamic), critical_section_init_phase_(0), critical_section_(new CRITICAL_SECTION) { ::InitializeCriticalSection(critical_section_); } Mutex::~Mutex() { // Static mutexes are leaked intentionally. It is not thread-safe to try // 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 if (type_ == kDynamic) { ::DeleteCriticalSection(critical_section_); delete critical_section_; critical_section_ = NULL; } } void Mutex::Lock() { ThreadSafeLazyInit(); ::EnterCriticalSection(critical_section_); owner_thread_id_ = ::GetCurrentThreadId(); } void Mutex::Unlock() { ThreadSafeLazyInit(); // We don't protect writing to owner_thread_id_ here, as it's the // caller's responsibility to ensure that the current thread holds the // mutex when this is called. owner_thread_id_ = 0; ::LeaveCriticalSection(critical_section_); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void Mutex::AssertHeld() { ThreadSafeLazyInit(); GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) << "The current thread is not holding the mutex @" << this; } // Initializes owner_thread_id_ and critical_section_ in static mutexes. void Mutex::ThreadSafeLazyInit() { // Dynamic mutexes are initialized in the constructor. if (type_ == kStatic) { switch ( ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { case 0: // If critical_section_init_phase_ was 0 before the exchange, we // are the first to test it and need to perform the initialization. owner_thread_id_ = 0; critical_section_ = new CRITICAL_SECTION; ::InitializeCriticalSection(critical_section_); // Updates the critical_section_init_phase_ to 2 to signal // initialization complete. GTEST_CHECK_(::InterlockedCompareExchange( &critical_section_init_phase_, 2L, 1L) == 1L); break; case 1: // Somebody else is already initializing the mutex; spin until they // are done. while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L, 2L) != 2L) { // Possibly yields the rest of the thread's time slice to other // threads. ::Sleep(0); } break; case 2: break; // The mutex is already initialized and ready for use. default: GTEST_CHECK_(false) << "Unexpected value of critical_section_init_phase_ " << "while initializing a static mutex."; } } } namespace { class ThreadWithParamSupport : public ThreadWithParamBase { public: static HANDLE CreateThread(Runnable* runnable, Notification* thread_can_start) { ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); DWORD thread_id; // TODO(yukawa): Consider to use _beginthreadex instead. HANDLE thread_handle = ::CreateThread( NULL, // Default security. 0, // Default stack size. &ThreadWithParamSupport::ThreadMain, param, // Parameter to ThreadMainStatic 0x0, // Default creation flags. &thread_id); // Need a valid pointer for the call to work under Win98. GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error " << ::GetLastError() << "."; if (thread_handle == NULL) { delete param; } return thread_handle; } private: struct ThreadMainParam { ThreadMainParam(Runnable* runnable, Notification* thread_can_start) : runnable_(runnable), thread_can_start_(thread_can_start) { } scoped_ptr<Runnable> runnable_; // Does not own. Notification* thread_can_start_; }; static DWORD WINAPI ThreadMain(void* ptr) { // Transfers ownership. scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr)); if (param->thread_can_start_ != NULL) param->thread_can_start_->WaitForNotification(); param->runnable_->Run(); return 0; } // Prohibit instantiation. ThreadWithParamSupport(); GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); }; } // namespace ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start) : thread_(ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) { } ThreadWithParamBase::~ThreadWithParamBase() { Join(); } void ThreadWithParamBase::Join() { GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) << "Failed to join the thread with error " << ::GetLastError() << "."; } // Maps a thread to a set of ThreadIdToThreadLocals that have values // instantiated on that thread and notifies them when the thread exits. A // ThreadLocal instance is expected to persist until all threads it has // values on have terminated. class ThreadLocalRegistryImpl { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { DWORD current_thread = ::GetCurrentThreadId(); MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(current_thread); if (thread_local_pos == thread_to_thread_locals->end()) { thread_local_pos = thread_to_thread_locals->insert( std::make_pair(current_thread, ThreadLocalValues())).first; StartWatcherThreadFor(current_thread); } ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos == thread_local_values.end()) { value_pos = thread_local_values .insert(std::make_pair( thread_local_instance, linked_ptr<ThreadLocalValueHolderBase>( thread_local_instance->NewValueForCurrentThread()))) .first; } return value_pos->second.get(); } static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; // Clean up the ThreadLocalValues data structure while holding the lock, but // defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); for (ThreadIdToThreadLocals::iterator it = thread_to_thread_locals->begin(); it != thread_to_thread_locals->end(); ++it) { ThreadLocalValues& thread_local_values = it->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos != thread_local_values.end()) { value_holders.push_back(value_pos->second); thread_local_values.erase(value_pos); // This 'if' can only be successful at most once, so theoretically we // could break out of the loop here, but we don't bother doing so. } } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } static void OnThreadExit(DWORD thread_id) { GTEST_CHECK_(thread_id != 0) << ::GetLastError(); std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; // Clean up the ThreadIdToThreadLocals data structure while holding the // lock, but defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(thread_id); if (thread_local_pos != thread_to_thread_locals->end()) { ThreadLocalValues& thread_local_values = thread_local_pos->second; for (ThreadLocalValues::iterator value_pos = thread_local_values.begin(); value_pos != thread_local_values.end(); ++value_pos) { value_holders.push_back(value_pos->second); } thread_to_thread_locals->erase(thread_local_pos); } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } private: // In a particular thread, maps a ThreadLocal object to its value. typedef std::map<const ThreadLocalBase*, linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues; // Stores all ThreadIdToThreadLocals having values in a thread, indexed by // thread's ID. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals; // Holds the thread id and thread handle that we pass from // StartWatcherThreadFor to WatcherThreadFunc. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle; static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by // watcher_thread in WatcherThreadFunc. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != NULL); - // We need to to pass a valid thread ID pointer into CreateThread for it + // We need to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. DWORD watcher_thread_id; HANDLE watcher_thread = ::CreateThread( NULL, // Default security. 0, // Default stack size &ThreadLocalRegistryImpl::WatcherThreadFunc, reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)), CREATE_SUSPENDED, &watcher_thread_id); GTEST_CHECK_(watcher_thread != NULL); // Give the watcher thread the same priority as ours to avoid being // blocked by it. ::SetThreadPriority(watcher_thread, ::GetThreadPriority(::GetCurrentThread())); ::ResumeThread(watcher_thread); ::CloseHandle(watcher_thread); } // Monitors exit from a given thread and notifies those // ThreadIdToThreadLocals about thread termination. static DWORD WINAPI WatcherThreadFunc(LPVOID param) { const ThreadIdAndHandle* tah = reinterpret_cast<const ThreadIdAndHandle*>(param); GTEST_CHECK_( ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); OnThreadExit(tah->first); ::CloseHandle(tah->second); delete tah; return 0; } // Returns map of thread local instances. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { mutex_.AssertHeld(); static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals; return map; } // Protects access to GetThreadLocalsMapLocked() and its return value. static Mutex mutex_; // Protects access to GetThreadMapLocked() and its return value. static Mutex thread_map_mutex_; }; Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { return ThreadLocalRegistryImpl::GetValueOnCurrentThread( thread_local_instance); } void ThreadLocalRegistry::OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); } #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS #if GTEST_USES_POSIX_RE // Implements RE. Currently only needed for death tests. RE::~RE() { if (is_valid_) { // regfree'ing an invalid regex might crash because the content // of the regex is undefined. Since the regex's are essentially // the same, one cannot be valid (or invalid) without the other // being so too. regfree(&partial_regex_); regfree(&full_regex_); } free(const_cast<char*>(pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.full_regex_, str, 1, &match, 0) == 0; } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = posix::StrDup(regex); // Reserves enough bytes to hold the regular expression used for a // full match. const size_t full_regex_len = strlen(regex) + 10; char* const full_pattern = new char[full_regex_len]; snprintf(full_pattern, full_regex_len, "^(%s)$", regex); is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; // We want to call regcomp(&partial_regex_, ...) even if the // previous expression returns false. Otherwise partial_regex_ may // not be properly initialized can may cause trouble when it's // freed. // // Some implementation of POSIX regex (e.g. on at least some // versions of Cygwin) doesn't accept the empty string as a valid // regex. We change it to an equivalent form "()" to be safe. if (is_valid_) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex << "\" is not a valid POSIX Extended regular expression."; delete[] full_pattern; } #elif GTEST_USES_SIMPLE_RE // Returns true iff ch appears anywhere in str (excluding the // terminating '\0' character). bool IsInSet(char ch, const char* str) { return ch != '\0' && strchr(str, ch) != NULL; } // Returns true iff ch belongs to the given classification. Unlike // similar functions in <ctype.h>, these aren't affected by the // current locale. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } bool IsAsciiPunct(char ch) { return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); } bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWordChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true iff "\\c" is a supported escape sequence. bool IsValidEscape(char c) { return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } // Returns true iff the given atom (specified by escaped and pattern) // matches ch. The result is undefined if the atom is invalid. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { case 'd': return IsAsciiDigit(ch); case 'D': return !IsAsciiDigit(ch); case 'f': return ch == '\f'; case 'n': return ch == '\n'; case 'r': return ch == '\r'; case 's': return IsAsciiWhiteSpace(ch); case 'S': return !IsAsciiWhiteSpace(ch); case 't': return ch == '\t'; case 'v': return ch == '\v'; case 'w': return IsAsciiWordChar(ch); case 'W': return !IsAsciiWordChar(ch); } return IsAsciiPunct(pattern_char) && pattern_char == ch; } return (pattern_char == '.' && ch != '\n') || pattern_char == ch; } // Helper function used by ValidateRegex() to format error messages. std::string FormatRegexSyntaxError(const char* regex, int index) { return (Message() << "Syntax error at index " << index << " in simple regular expression \"" << regex << "\": ").GetString(); } // Generates non-fatal failures and returns false if regex is invalid; // otherwise returns true. bool ValidateRegex(const char* regex) { if (regex == NULL) { // TODO(wan@google.com): fix the source file location in the // assertion failures to match where the regex is used in user // code. ADD_FAILURE() << "NULL is not a valid simple regular expression."; return false; } bool is_valid = true; // True iff ?, *, or + can follow the previous atom. bool prev_repeatable = false; for (int i = 0; regex[i]; i++) { if (regex[i] == '\\') { // An escape sequence i++; if (regex[i] == '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "'\\' cannot appear at the end."; return false; } if (!IsValidEscape(regex[i])) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "invalid escape sequence \"\\" << regex[i] << "\"."; is_valid = false; } prev_repeatable = true; } else { // Not an escape sequence. const char ch = regex[i]; if (ch == '^' && i > 0) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'^' can only appear at the beginning."; is_valid = false; } else if (ch == '$' && regex[i + 1] != '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'$' can only appear at the end."; is_valid = false; } else if (IsInSet(ch, "()[]{}|")) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' is unsupported."; is_valid = false; } else if (IsRepeat(ch) && !prev_repeatable) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' can only follow a repeatable token."; is_valid = false; } prev_repeatable = !IsInSet(ch, "^$?*+"); } } return is_valid; } // Matches a repeated regex atom followed by a valid simple regular // expression. The regex atom is defined as c if escaped is false, // or \c otherwise. repeat is the repetition meta character (?, *, // or +). The behavior is undefined if str contains too many // characters to be indexable by size_t, in which case the test will // probably time out anyway. We are fine with this limitation as // std::string has it too. bool MatchRepetitionAndRegexAtHead( bool escaped, char c, char repeat, const char* regex, const char* str) { const size_t min_count = (repeat == '+') ? 1 : 0; const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. for (size_t i = 0; i <= max_count; ++i) { // We know that the atom matches each of the first i characters in str. if (i >= min_count && MatchRegexAtHead(regex, str + i)) { // We have enough matches at the head, and the tail matches too. // Since we only care about *whether* the pattern matches str // (as opposed to *how* it matches), there is no need to find a // greedy match. return true; } if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false; } return false; } // Returns true iff regex matches a prefix of str. regex must be a // valid simple regular expression and not start with "^", or the // result is undefined. bool MatchRegexAtHead(const char* regex, const char* str) { if (*regex == '\0') // An empty regex matches a prefix of anything. return true; // "$" only matches the end of a string. Note that regex being // valid guarantees that there's nothing after "$" in it. if (*regex == '$') return *str == '\0'; // Is the first thing in regex an escape sequence? const bool escaped = *regex == '\\'; if (escaped) ++regex; if (IsRepeat(regex[1])) { // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // here's an indirect recursion. It terminates as the regex gets // shorter in each recursion. return MatchRepetitionAndRegexAtHead( escaped, regex[0], regex[1], regex + 2, str); } else { // regex isn't empty, isn't "$", and doesn't start with a // repetition. We match the first atom of regex with the first // character of str and recurse. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && MatchRegexAtHead(regex + 1, str + 1); } } // Returns true iff regex matches any substring of str. regex must be // a valid simple regular expression, or the result is undefined. // // The algorithm is recursive, but the recursion depth doesn't exceed // the regex length, so we won't need to worry about running out of // stack space normally. In rare cases the time complexity can be // exponential with respect to the regex length + the string length, // but usually it's must faster (often close to linear). bool MatchRegexAnywhere(const char* regex, const char* str) { if (regex == NULL || str == NULL) return false; if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } // Implements the RE class. RE::~RE() { free(const_cast<char*>(pattern_)); free(const_cast<char*>(full_pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = full_pattern_ = NULL; if (regex != NULL) { pattern_ = posix::StrDup(regex); } is_valid_ = ValidateRegex(regex); if (!is_valid_) { // No need to calculate the full pattern when the regex is invalid. return; } const size_t len = strlen(regex); // Reserves enough bytes to hold the regular expression used for a // full match: we need space to prepend a '^', append a '$', and // terminate the string with '\0'. char* buffer = static_cast<char*>(malloc(len + 3)); full_pattern_ = buffer; if (*regex != '^') *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. // We don't use snprintf or strncpy, as they trigger a warning when // compiled with VC++ 8.0. memcpy(buffer, regex, len); buffer += len; if (len == 0 || regex[len - 1] != '$') *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. *buffer = '\0'; } #endif // GTEST_USES_POSIX_RE const char kUnknownFile[] = "unknown file"; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { const std::string file_name(file == NULL ? kUnknownFile : file); if (line < 0) { return file_name + ":"; } #ifdef _MSC_VER return file_name + "(" + StreamableToString(line) + "):"; #else return file_name + ":" + StreamableToString(line) + ":"; #endif // _MSC_VER } // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. // Note that FormatCompilerIndependentFileLocation() does NOT append colon // to the file location it produces, unlike FormatFileLocation(). GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( const char* file, int line) { const std::string file_name(file == NULL ? kUnknownFile : file); if (line < 0) return file_name; else return file_name + ":" + StreamableToString(line); } GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { const char* const marker = severity == GTEST_INFO ? "[ INFO ]" : severity == GTEST_WARNING ? "[WARNING]" : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; GetStream() << ::std::endl << marker << " " << FormatFileLocation(file, line).c_str() << ": "; } // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. GTestLog::~GTestLog() { GetStream() << ::std::endl; if (severity_ == GTEST_FATAL) { fflush(stderr); posix::Abort(); } } // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) #if GTEST_HAS_STREAM_REDIRECTION // Object that captures an output stream (stdout/stderr). class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { # if GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; # else // There's no guarantee that a test has write access to the current // directory, so we create the temporary file in the /tmp directory // instead. We use /tmp on most systems, and /sdcard on Android. // That's because Android doesn't have /tmp. # if GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, // this requires a Context handle, which cannot be retrieved // globally from native code. Doing so also precludes running the // code as part of a regular standalone executable, which doesn't // run in a Dalvik process (e.g. when running it through 'adb shell'). // // The location /sdcard is directly accessible from native code // and is the only location (unofficially) supported by the Android // team. It's generally a symlink to the real SD Card mount point // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or // other OEM-customized locations. Never rely on these, and always // use /sdcard. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; # else char name_template[] = "/tmp/captured_stream.XXXXXX"; # endif // GTEST_OS_LINUX_ANDROID const int captured_fd = mkstemp(name_template); filename_ = name_template; # endif // GTEST_OS_WINDOWS fflush(NULL); dup2(captured_fd, fd_); close(captured_fd); } ~CapturedStream() { remove(filename_.c_str()); } std::string GetCapturedString() { if (uncaptured_fd_ != -1) { // Restores the original stream. fflush(NULL); dup2(uncaptured_fd_, fd_); close(uncaptured_fd_); uncaptured_fd_ = -1; } FILE* const file = posix::FOpen(filename_.c_str(), "r"); const std::string content = ReadEntireFile(file); posix::FClose(file); return content; } private: const int fd_; // A stream to capture. int uncaptured_fd_; // Name of the temporary file holding the stderr output. ::std::string filename_; GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); }; GTEST_DISABLE_MSC_WARNINGS_POP_() static CapturedStream* g_captured_stderr = NULL; static CapturedStream* g_captured_stdout = NULL; // Starts capturing an output stream (stdout/stderr). void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { if (*stream != NULL) { GTEST_LOG_(FATAL) << "Only one " << stream_name << " capturer can exist at a time."; } *stream = new CapturedStream(fd); } // Stops capturing the output stream and returns the captured string. std::string GetCapturedStream(CapturedStream** captured_stream) { const std::string content = (*captured_stream)->GetCapturedString(); delete *captured_stream; *captured_stream = NULL; return content; } // Starts capturing stdout. void CaptureStdout() { CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); } // Starts capturing stderr. void CaptureStderr() { CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); } // Stops capturing stdout and returns the captured string. std::string GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } // Stops capturing stderr and returns the captured string. std::string GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } #endif // GTEST_HAS_STREAM_REDIRECTION size_t GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast<size_t>(ftell(file)); } std::string ReadEntireFile(FILE* file) { const size_t file_size = GetFileSize(file); char* const buffer = new char[file_size]; size_t bytes_last_read = 0; // # of bytes read in the last fread() size_t bytes_read = 0; // # of bytes read so far fseek(file, 0, SEEK_SET); // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); const std::string content(buffer, bytes_read); delete[] buffer; return content; } #if GTEST_HAS_DEATH_TEST static const ::std::vector<testing::internal::string>* g_injected_test_argvs = NULL; // Owned. void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) { if (g_injected_test_argvs != argvs) delete g_injected_test_argvs; g_injected_test_argvs = argvs; } const ::std::vector<testing::internal::string>& GetInjectableArgvs() { if (g_injected_test_argvs != NULL) { return *g_injected_test_argvs; } return GetArgvs(); } #endif // GTEST_HAS_DEATH_TEST #if GTEST_OS_WINDOWS_MOBILE namespace posix { void Abort() { DebugBreak(); TerminateProcess(GetCurrentProcess(), 1); } } // namespace posix #endif // GTEST_OS_WINDOWS_MOBILE // Returns the name of the environment variable corresponding to the // given flag. For example, FlagToEnvVar("foo") will return // "GTEST_FOO" in the open-source version. static std::string FlagToEnvVar(const char* flag) { const std::string full_flag = (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); Message env_var; for (size_t i = 0; i != full_flag.length(); i++) { env_var << ToUpper(full_flag.c_str()[i]); } return env_var.GetString(); } // Parses 'str' for a 32-bit signed integer. If successful, writes // the result to *value and returns true; otherwise leaves *value // unchanged and returns false. bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // Parses the environment variable as a decimal integer. char* end = NULL; const long long_value = strtol(str, &end, 10); // NOLINT // Has strtol() consumed all characters in the string? if (*end != '\0') { // No - an invalid character was encountered. Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value \"" << str << "\".\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } // Is the parsed value in the range of an Int32? const Int32 result = static_cast<Int32>(long_value); if (long_value == LONG_MAX || long_value == LONG_MIN || // The parsed value overflows as a long. (strtol() returns // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an Int32. ) { Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value " << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } *value = result; return true; } // Reads and returns the Boolean environment variable corresponding to // the given flag; if it's not set, returns default_value. // // The value is considered true iff it's not "0". bool BoolFromGTestEnv(const char* flag, bool default_value) { #if defined(GTEST_GET_BOOL_FROM_ENV_) return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); #endif // defined(GTEST_GET_BOOL_FROM_ENV_) const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); return string_value == NULL ? default_value : strcmp(string_value, "0") != 0; } // Reads and returns a 32-bit integer stored in the environment // variable corresponding to the given flag; if it isn't set or // doesn't represent a valid 32-bit integer, returns default_value. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { #if defined(GTEST_GET_INT32_FROM_ENV_) return GTEST_GET_INT32_FROM_ENV_(flag, default_value); #endif // defined(GTEST_GET_INT32_FROM_ENV_) const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); if (string_value == NULL) { // The environment variable is not set. return default_value; } Int32 result = default_value; if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, &result)) { printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); return default_value; } return result; } // Reads and returns the string environment variable corresponding to // the given flag; if it's not set, returns default_value. std::string StringFromGTestEnv(const char* flag, const char* default_value) { #if defined(GTEST_GET_STRING_FROM_ENV_) return GTEST_GET_STRING_FROM_ENV_(flag, default_value); #endif // defined(GTEST_GET_STRING_FROM_ENV_) const std::string env_var = FlagToEnvVar(flag); const char* value = posix::GetEnv(env_var.c_str()); if (value != NULL) { return value; } // As a special case for the 'output' flag, if GTEST_OUTPUT is not // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build // system. The value of XML_OUTPUT_FILE is a filename without the // "xml:" prefix of GTEST_OUTPUT. // // The net priority order after flag processing is thus: // --gtest_output command line flag // GTEST_OUTPUT environment variable // XML_OUTPUT_FILE environment variable // 'default_value' if (strcmp(flag, "output") == 0) { value = posix::GetEnv("XML_OUTPUT_FILE"); if (value != NULL) { return std::string("xml:") + value; } } return default_value; } } // namespace internal } // namespace testing diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index a0308d43..b6087f9b 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -1,5408 +1,5437 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) #include "gtest/gtest.h" #include "gtest/internal/custom/gtest.h" #include "gtest/gtest-spi.h" #include <ctype.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> #include <iomanip> #include <limits> #include <list> #include <map> #include <ostream> // NOLINT #include <sstream> #include <vector> #if GTEST_OS_LINUX // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <fcntl.h> // NOLINT # include <limits.h> // NOLINT # include <sched.h> // NOLINT // Declares vsnprintf(). This header is not available on Windows. # include <strings.h> // NOLINT # include <sys/mman.h> // NOLINT # include <sys/time.h> // NOLINT # include <unistd.h> // NOLINT # include <string> #elif GTEST_OS_SYMBIAN # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT #elif GTEST_OS_ZOS # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT // On z/OS we additionally need strings.h for strcasecmp. # include <strings.h> // NOLINT #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. # include <windows.h> // NOLINT # undef min #elif GTEST_OS_WINDOWS // We are on Windows proper. # include <io.h> // NOLINT # include <sys/timeb.h> // NOLINT # include <sys/types.h> // NOLINT # include <sys/stat.h> // NOLINT # if GTEST_OS_WINDOWS_MINGW // MinGW has gettimeofday() but not _ftime64(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). // TODO(kenton@google.com): There are other ways to get the time on // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW // supports these. consider using them instead. # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT # endif // GTEST_OS_WINDOWS_MINGW // cpplint thinks that the header is already included, so we want to // silence it. # include <windows.h> // NOLINT # undef min #else // Assume other platforms have gettimeofday(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 // cpplint thinks that the header is already included, so we want to // silence it. # include <sys/time.h> // NOLINT # include <unistd.h> // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS # include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ # include <arpa/inet.h> // NOLINT # include <netdb.h> // NOLINT # include <sys/socket.h> // NOLINT # include <sys/types.h> // NOLINT #endif // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ #if GTEST_OS_WINDOWS # define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS namespace testing { using internal::CountIf; using internal::ForEach; using internal::GetElementOr; using internal::Shuffle; // Constants. // A test whose test case name or test name matches this filter is // disabled and not run. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; // A test case whose name matches this filter is considered a death // test case and will be run before test cases whose name doesn't // match this filter. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; // A test filter that matches everything. static const char kUniversalFilter[] = "*"; // The default output file for XML output. static const char kDefaultOutputFile[] = "test_detail.xml"; // The environment variable name for the test shard index. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; // The environment variable name for the total number of test shards. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; // The environment variable name for the test shard status file. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; namespace internal { // The text used in failure messages to indicate the start of the // stack trace. const char kStackTraceMarker[] = "\nStack trace:\n"; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. bool g_help_flag = false; } // namespace internal static const char* GetDefaultFilter() { #ifdef GTEST_TEST_FILTER_ENV_VAR_ const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_); if (testbridge_test_only != NULL) { return testbridge_test_only; } #endif // GTEST_TEST_FILTER_ENV_VAR_ return kUniversalFilter; } GTEST_DEFINE_bool_( also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), "True iff a failed assertion should be a debugger break-point."); GTEST_DEFINE_bool_( catch_exceptions, internal::BoolFromGTestEnv("catch_exceptions", true), "True iff " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors."); GTEST_DEFINE_string_( filter, internal::StringFromGTestEnv("filter", GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " "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_(list_tests, false, "List all tests without running them."); GTEST_DEFINE_string_( output, internal::StringFromGTestEnv("output", ""), "A format (currently must be \"xml\"), optionally followed " "by a colon and an output file name or directory. A directory " "is indicated by a trailing pathname separator. " "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " "If a directory is specified, output files will be created " "within that directory, with file-names based on the test " "executable's name and, if necessary, made unique by adding " "digits."); GTEST_DEFINE_bool_( print_time, internal::BoolFromGTestEnv("print_time", true), "True iff " GTEST_NAME_ " should display elapsed time in text output."); GTEST_DEFINE_int32_( random_seed, internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( repeat, internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( show_internal_stack_frames, false, "True iff " GTEST_NAME_ " should include internal stack frames when " "printing test failure stack traces."); GTEST_DEFINE_bool_( shuffle, internal::BoolFromGTestEnv("shuffle", false), "True iff " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux."); GTEST_DEFINE_bool_( throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DEFINE_string_( flagfile, internal::StringFromGTestEnv("flagfile", ""), "This flag specifies the flagfile to read command-line flags from."); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ namespace internal { // Generates a random number from [0, range), using a Linear // Congruential Generator (LCG). Crashes if 'range' is 0 or greater // than kMaxRange. UInt32 Random::Generate(UInt32 range) { // These constants are the same as are used in glibc's rand(3). - state_ = (1103515245U*state_ + 12345U) % kMaxRange; + // Use wider types than necessary to prevent unsigned overflow diagnostics. + state_ = static_cast<UInt32>(1103515245ULL*state_ + 12345U) % kMaxRange; GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " << "but this can only generate numbers in [0, " << kMaxRange << ")."; // Converting via modulus introduces a bit of downward bias, but // it's simple, and a linear congruential generator isn't too good // to begin with. return state_ % range; } // GTestIsInitialized() returns true iff the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). static bool GTestIsInitialized() { return GetArgvs().size() > 0; } // Iterates over a vector of TestCases, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list, int (TestCase::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); } return sum; } // Returns true iff the test case passed. static bool TestCasePassed(const TestCase* test_case) { return test_case->should_run() && test_case->Passed(); } // Returns true iff the test case failed. static bool TestCaseFailed(const TestCase* test_case) { return test_case->should_run() && test_case->Failed(); } // Returns true iff test_case contains at least one test that should // run. static bool ShouldRunTestCase(const TestCase* test_case) { return test_case->should_run(); } // AssertHelper constructor. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) : data_(new AssertHelperData(type, file, line, message)) { } AssertHelper::~AssertHelper() { delete data_; } // Message assignment, for assertion streaming support. void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()-> AddTestPartResult(data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), UnitTest::GetInstance()->impl() ->CurrentOsStackTraceExceptTop(1) // Skips the stack frame for this function itself. ); // NOLINT } // Mutex for linked pointers. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); // A copy of all command line arguments. Set by InitGoogleTest(). ::std::vector<testing::internal::string> g_argvs; const ::std::vector<testing::internal::string>& GetArgvs() { #if defined(GTEST_CUSTOM_GET_ARGVS_) return GTEST_CUSTOM_GET_ARGVS_(); #else // defined(GTEST_CUSTOM_GET_ARGVS_) return g_argvs; #endif // defined(GTEST_CUSTOM_GET_ARGVS_) } // Returns the current application's name, removing directory path if that // is present. FilePath GetCurrentExecutableName() { FilePath result; #if GTEST_OS_WINDOWS result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); #else result.Set(FilePath(GetArgvs()[0])); #endif // GTEST_OS_WINDOWS return result.RemoveDirectoryName(); } // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. std::string UnitTestOptions::GetOutputFormat() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); if (gtest_output_flag == NULL) return std::string(""); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == NULL) ? std::string(gtest_output_flag) : std::string(gtest_output_flag, colon - gtest_output_flag); } // Returns the name of the requested output file, or the default if none // was explicitly specified. std::string UnitTestOptions::GetAbsolutePathToOutputFile() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); if (gtest_output_flag == NULL) return ""; const char* const colon = strchr(gtest_output_flag, ':'); if (colon == NULL) return internal::FilePath::ConcatPaths( internal::FilePath( UnitTest::GetInstance()->original_working_dir()), internal::FilePath(kDefaultOutputFile)).string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) // TODO(wan@google.com): on Windows \some\path is not an absolute // path (as its meaning depends on the current drive), yet the // following logic for turning it into an absolute path is wrong. // Fix it. output_name = internal::FilePath::ConcatPaths( internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); return result.string(); } // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. bool UnitTestOptions::PatternMatchesString(const char *pattern, const char *str) { switch (*pattern) { case '\0': case ':': // Either ':' or '\0' marks the end of the pattern. return *str == '\0'; case '?': // Matches any single character. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); case '*': // Matches any string (possibly empty) of characters. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || PatternMatchesString(pattern + 1, str); default: // Non-special character. Matches itself. return *pattern == *str && PatternMatchesString(pattern + 1, str + 1); } } bool UnitTestOptions::MatchesFilter( const std::string& name, const char* filter) { const char *cur_pattern = filter; for (;;) { if (PatternMatchesString(cur_pattern, name.c_str())) { return true; } // Finds the next pattern in the filter. cur_pattern = strchr(cur_pattern, ':'); // Returns if no more pattern can be found. if (cur_pattern == NULL) { return false; } // Skips the pattern separater (the ':' character). cur_pattern++; } } // Returns true iff the user-specified filter matches the test case // name and the test name. bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, const std::string &test_name) { const std::string& full_name = test_case_name + "." + test_name.c_str(); // Split --gtest_filter at '-', if there is one, to separate into // positive filter and negative filter portions const char* const p = GTEST_FLAG(filter).c_str(); const char* const dash = strchr(p, '-'); std::string positive; std::string negative; if (dash == NULL) { positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter negative = ""; } else { positive = std::string(p, dash); // Everything up to the dash negative = std::string(dash + 1); // Everything after the dash if (positive.empty()) { // Treat '-test1' as the same as '*-test1' positive = kUniversalFilter; } } // A filter is a colon-separated list of patterns. It matches a // test if any pattern in it matches the test. return (MatchesFilter(full_name, positive.c_str()) && !MatchesFilter(full_name, negative.c_str())); } #if GTEST_HAS_SEH // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { // Google Test should handle a SEH exception if: // 1. the user wants it to, AND // 2. this is not a breakpoint exception, AND // 3. this is not a C++ exception (VC++ implements them via SEH, // apparently). // // SEH exception code for C++ exceptions. // (see http://support.microsoft.com/kb/185294 for more information). const DWORD kCxxExceptionCode = 0xe06d7363; bool should_handle = true; if (!GTEST_FLAG(catch_exceptions)) should_handle = false; else if (exception_code == EXCEPTION_BREAKPOINT) should_handle = false; else if (exception_code == kCxxExceptionCode) should_handle = false; return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; } #endif // GTEST_HAS_SEH } // namespace internal // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. Intercepts only failures from the current thread. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( TestPartResultArray* result) : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) { Init(); } // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( InterceptMode intercept_mode, TestPartResultArray* result) : intercept_mode_(intercept_mode), result_(result) { Init(); } void ScopedFakeTestPartResultReporter::Init() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { old_reporter_ = impl->GetGlobalTestPartResultReporter(); impl->SetGlobalTestPartResultReporter(this); } else { old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); impl->SetTestPartResultReporterForCurrentThread(this); } } // The d'tor restores the test part result reporter used by Google Test // before. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { impl->SetGlobalTestPartResultReporter(old_reporter_); } else { impl->SetTestPartResultReporterForCurrentThread(old_reporter_); } } // Increments the test part result count and remembers the result. // This method is from the TestPartResultReporterInterface interface. void ScopedFakeTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { result_->Append(result); } namespace internal { // Returns the type ID of ::testing::Test. We should always call this // instead of GetTypeId< ::testing::Test>() to get the type ID of // testing::Test. This is to work around a suspected linker bug when // using Google Test as a framework on Mac OS X. The bug causes // GetTypeId< ::testing::Test>() to return different values depending // on whether the call is from the Google Test framework itself or // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. TypeId GetTestTypeId() { return GetTypeId<Test>(); } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); // This predicate-formatter checks that 'results' contains a test part // failure of the given type and that the failure message contains the // given substring. AssertionResult HasOneFailure(const char* /* results_expr */, const char* /* type_expr */, const char* /* substr_expr */, const TestPartResultArray& results, TestPartResult::Type type, const std::string& substr) { const std::string expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" << " Actual: " << results.size() << " failures"; for (int i = 0; i < results.size(); i++) { msg << "\n" << results.GetTestPartResult(i); } return AssertionFailure() << msg; } const TestPartResult& r = results.GetTestPartResult(0); if (r.type() != type) { return AssertionFailure() << "Expected: " << expected << "\n" << " Actual:\n" << r; } if (strstr(r.message(), substr.c_str()) == NULL) { return AssertionFailure() << "Expected: " << expected << " containing \"" << substr << "\"\n" << " Actual:\n" << r; } return AssertionSuccess(); } // The constructor of SingleFailureChecker remembers where to look up // test part results, what type of failure we expect, and what // substring the failure message should contain. SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const std::string& substr) : results_(results), type_(type), substr_(substr) {} // The destructor of SingleFailureChecker verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. SingleFailureChecker::~SingleFailureChecker() { EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->current_test_result()->AddTestPartResult(result); unit_test_->listeners()->repeater()->OnTestPartResult(result); } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); } // Returns the global test part result reporter. TestPartResultReporterInterface* UnitTestImpl::GetGlobalTestPartResultReporter() { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); return global_test_part_result_repoter_; } // Sets the global test part result reporter. void UnitTestImpl::SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter) { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); global_test_part_result_repoter_ = reporter; } // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* UnitTestImpl::GetTestPartResultReporterForCurrentThread() { return per_thread_test_part_result_reporter_.get(); } // Sets the test part result reporter for the current thread. void UnitTestImpl::SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter) { per_thread_test_part_result_reporter_.set(reporter); } // Gets the number of successful test cases. int UnitTestImpl::successful_test_case_count() const { return CountIf(test_cases_, TestCasePassed); } // Gets the number of failed test cases. int UnitTestImpl::failed_test_case_count() const { return CountIf(test_cases_, TestCaseFailed); } // Gets the number of all test cases. int UnitTestImpl::total_test_case_count() const { return static_cast<int>(test_cases_.size()); } // Gets the number of all test cases that contain at least one test // that should run. int UnitTestImpl::test_case_to_run_count() const { return CountIf(test_cases_, ShouldRunTestCase); } // Gets the number of successful tests. int UnitTestImpl::successful_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); } // Gets the number of failed tests. int UnitTestImpl::failed_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTestImpl::reportable_disabled_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::reportable_disabled_test_count); } // Gets the number of disabled tests. int UnitTestImpl::disabled_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); } // Gets the number of tests to be printed in the XML report. int UnitTestImpl::reportable_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); } // Gets the number of all tests. int UnitTestImpl::total_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); } // Gets the number of tests that should run. int UnitTestImpl::test_to_run_count() const { return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { return os_stack_trace_getter()->CurrentStackTrace( static_cast<int>(GTEST_FLAG(stack_trace_depth)), skip_count + 1 // Skips the user-specified number of frames plus this function // itself. ); // NOLINT } // Returns the current time in milliseconds. TimeInMillis GetTimeInMillis() { #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) // Difference between 1970-01-01 and 1601-01-01 in milliseconds. // http://analogous.blogspot.com/2005/04/epoch.html const TimeInMillis kJavaEpochToWinFileTimeDelta = static_cast<TimeInMillis>(116444736UL) * 100000UL; const DWORD kTenthMicrosInMilliSecond = 10000; SYSTEMTIME now_systime; FILETIME now_filetime; ULARGE_INTEGER now_int64; // TODO(kenton@google.com): Shouldn't this just use // GetSystemTimeAsFileTime()? GetSystemTime(&now_systime); if (SystemTimeToFileTime(&now_systime, &now_filetime)) { now_int64.LowPart = now_filetime.dwLowDateTime; now_int64.HighPart = now_filetime.dwHighDateTime; now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - kJavaEpochToWinFileTimeDelta; return now_int64.QuadPart; } return 0; #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ __timeb64 now; // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 // (deprecated function) there. // TODO(kenton@google.com): Use GetTickCount()? Or use // SystemTimeToFileTime() GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) _ftime64(&now); GTEST_DISABLE_MSC_WARNINGS_POP_() return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm; #elif GTEST_HAS_GETTIMEOFDAY_ struct timeval now; gettimeofday(&now, NULL); return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000; #else # error "Don't know how to get the current time on your system." #endif } // Utilities // class String. #if GTEST_OS_WINDOWS_MOBILE // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. LPCWSTR String::AnsiToUtf16(const char* ansi) { if (!ansi) return NULL; const int length = strlen(ansi); const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, NULL, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return NULL; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, NULL, 0, NULL, NULL); char* ansi = new char[ansi_length + 1]; WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, NULL, NULL); ansi[ansi_length] = 0; return ansi; } #endif // GTEST_OS_WINDOWS_MOBILE // Compares two C strings. Returns true iff they have the same content. // // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::CStringEquals(const char * lhs, const char * rhs) { if ( lhs == NULL ) return rhs == NULL; if ( rhs == NULL ) return false; return strcmp(lhs, rhs) == 0; } #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING // Converts an array of wide chars to a narrow string using the UTF-8 // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { for (size_t i = 0; i != length; ) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; } } } #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { ::std::vector< ::std::string> parsed; ::std::string::size_type pos = 0; while (::testing::internal::AlwaysTrue()) { const ::std::string::size_type colon = str.find(delimiter, pos); if (colon == ::std::string::npos) { parsed.push_back(str.substr(pos)); break; } else { parsed.push_back(str.substr(pos, colon - pos)); pos = colon + 1; } } dest->swap(parsed); } } // namespace internal // Constructs an empty Message. // We allocate the stringstream separately because otherwise each use of // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's // stack frame leading to huge stack frames in some cases; gcc does not reuse // the stack space. Message::Message() : ss_(new ::std::stringstream) { // By default, we want there to be enough precision when printing // a double to a Message. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& Message::operator <<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } Message& Message::operator <<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator <<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator <<(const ::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif // GTEST_HAS_GLOBAL_WSTRING // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". std::string Message::GetString() const { return internal::StringStreamToString(ss_.get()); } // AssertionResult constructors. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) : success_(other.success_), message_(other.message_.get() != NULL ? new ::std::string(*other.message_) : static_cast< ::std::string*>(NULL)) { } // Swaps two AssertionResults. void AssertionResult::swap(AssertionResult& other) { using std::swap; swap(success_, other.success_); swap(message_, other.message_); } // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult AssertionResult::operator!() const { AssertionResult negation(!success_); if (message_.get() != NULL) negation << *message_; return negation; } // Makes a successful assertion result. AssertionResult AssertionSuccess() { return AssertionResult(true); } // Makes a failed assertion result. AssertionResult AssertionFailure() { return AssertionResult(false); } // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << message. AssertionResult AssertionFailure(const Message& message) { return AssertionFailure() << message; } namespace internal { namespace edit_distance { std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left, const std::vector<size_t>& right) { std::vector<std::vector<double> > costs( left.size() + 1, std::vector<double>(right.size() + 1)); std::vector<std::vector<EditType> > best_move( left.size() + 1, std::vector<EditType>(right.size() + 1)); // Populate for empty right. for (size_t l_i = 0; l_i < costs.size(); ++l_i) { costs[l_i][0] = static_cast<double>(l_i); best_move[l_i][0] = kRemove; } // Populate for empty left. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { costs[0][r_i] = static_cast<double>(r_i); best_move[0][r_i] = kAdd; } for (size_t l_i = 0; l_i < left.size(); ++l_i) { for (size_t r_i = 0; r_i < right.size(); ++r_i) { if (left[l_i] == right[r_i]) { // Found a match. Consume it. costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; best_move[l_i + 1][r_i + 1] = kMatch; continue; } const double add = costs[l_i + 1][r_i]; const double remove = costs[l_i][r_i + 1]; const double replace = costs[l_i][r_i]; if (add < remove && add < replace) { costs[l_i + 1][r_i + 1] = add + 1; best_move[l_i + 1][r_i + 1] = kAdd; } else if (remove < add && remove < replace) { costs[l_i + 1][r_i + 1] = remove + 1; best_move[l_i + 1][r_i + 1] = kRemove; } else { // We make replace a little more expensive than add/remove to lower // their priority. costs[l_i + 1][r_i + 1] = replace + 1.00001; best_move[l_i + 1][r_i + 1] = kReplace; } } } // Reconstruct the best path. We do it in reverse order. std::vector<EditType> best_path; for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { EditType move = best_move[l_i][r_i]; best_path.push_back(move); l_i -= move != kAdd; r_i -= move != kRemove; } std::reverse(best_path.begin(), best_path.end()); return best_path; } namespace { // Helper class to convert string into ids with deduplication. class InternalStrings { public: size_t GetId(const std::string& str) { IdMap::iterator it = ids_.find(str); if (it != ids_.end()) return it->second; size_t id = ids_.size(); return ids_[str] = id; } private: typedef std::map<std::string, size_t> IdMap; IdMap ids_; }; } // namespace std::vector<EditType> CalculateOptimalEdits( const std::vector<std::string>& left, const std::vector<std::string>& right) { std::vector<size_t> left_ids, right_ids; { InternalStrings intern_table; for (size_t i = 0; i < left.size(); ++i) { left_ids.push_back(intern_table.GetId(left[i])); } for (size_t i = 0; i < right.size(); ++i) { right_ids.push_back(intern_table.GetId(right[i])); } } return CalculateOptimalEdits(left_ids, right_ids); } namespace { // Helper class that holds the state for one hunk and prints it out to the // stream. // It reorders adds/removes when possible to group all removes before all // adds. It also adds the hunk header before printint into the stream. class Hunk { public: Hunk(size_t left_start, size_t right_start) : left_start_(left_start), right_start_(right_start), adds_(), removes_(), common_() {} void PushLine(char edit, const char* line) { switch (edit) { case ' ': ++common_; FlushEdits(); hunk_.push_back(std::make_pair(' ', line)); break; case '-': ++removes_; hunk_removes_.push_back(std::make_pair('-', line)); break; case '+': ++adds_; hunk_adds_.push_back(std::make_pair('+', line)); break; } } void PrintTo(std::ostream* os) { PrintHeader(os); FlushEdits(); for (std::list<std::pair<char, const char*> >::const_iterator it = hunk_.begin(); it != hunk_.end(); ++it) { *os << it->first << it->second << "\n"; } } bool has_edits() const { return adds_ || removes_; } private: void FlushEdits() { hunk_.splice(hunk_.end(), hunk_removes_); hunk_.splice(hunk_.end(), hunk_adds_); } // Print a unified diff header for one hunk. // The format is // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@" - // where the left/right parts are ommitted if unnecessary. + // where the left/right parts are omitted if unnecessary. void PrintHeader(std::ostream* ss) const { *ss << "@@ "; if (removes_) { *ss << "-" << left_start_ << "," << (removes_ + common_); } if (removes_ && adds_) { *ss << " "; } if (adds_) { *ss << "+" << right_start_ << "," << (adds_ + common_); } *ss << " @@\n"; } size_t left_start_, right_start_; size_t adds_, removes_, common_; std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_; }; } // namespace // Create a list of diff hunks in Unified diff format. // Each hunk has a header generated by PrintHeader above plus a body with // lines prefixed with ' ' for no change, '-' for deletion and '+' for // addition. // 'context' represents the desired unchanged prefix/suffix around the diff. // If two hunks are close enough that their contexts overlap, then they are // joined into one hunk. std::string CreateUnifiedDiff(const std::vector<std::string>& left, const std::vector<std::string>& right, size_t context) { const std::vector<EditType> edits = CalculateOptimalEdits(left, right); size_t l_i = 0, r_i = 0, edit_i = 0; std::stringstream ss; while (edit_i < edits.size()) { // Find first edit. while (edit_i < edits.size() && edits[edit_i] == kMatch) { ++l_i; ++r_i; ++edit_i; } // Find the first line to include in the hunk. const size_t prefix_context = std::min(l_i, context); Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); for (size_t i = prefix_context; i > 0; --i) { hunk.PushLine(' ', left[l_i - i].c_str()); } // Iterate the edits until we found enough suffix for the hunk or the input // is over. size_t n_suffix = 0; for (; edit_i < edits.size(); ++edit_i) { if (n_suffix >= context) { // Continue only if the next hunk is very close. std::vector<EditType>::const_iterator it = edits.begin() + edit_i; while (it != edits.end() && *it == kMatch) ++it; if (it == edits.end() || (it - edits.begin()) - edit_i >= context) { // There is no next edit or it is too far away. break; } } EditType edit = edits[edit_i]; // Reset count when a non match is found. n_suffix = edit == kMatch ? n_suffix + 1 : 0; if (edit == kMatch || edit == kRemove || edit == kReplace) { hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); } if (edit == kAdd || edit == kReplace) { hunk.PushLine('+', right[r_i].c_str()); } // Advance indices, depending on edit type. l_i += edit != kAdd; r_i += edit != kRemove; } if (!hunk.has_edits()) { // We are done. We don't want this hunk. break; } hunk.PrintTo(&ss); } return ss.str(); } } // namespace edit_distance namespace { // The string representation of the values received in EqFailure() are already // escaped. Split them on escaped '\n' boundaries. Leave all other escaped // characters the same. std::vector<std::string> SplitEscapedString(const std::string& str) { std::vector<std::string> lines; size_t start = 0, end = str.size(); if (end > 2 && str[0] == '"' && str[end - 1] == '"') { ++start; --end; } bool escaped = false; for (size_t i = start; i + 1 < end; ++i) { if (escaped) { escaped = false; if (str[i] == 'n') { lines.push_back(str.substr(start, i - start - 1)); start = i + 1; } } else { escaped = str[i] == '\\'; } } lines.push_back(str.substr(start, end - start)); return lines; } } // namespace // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // // The first four parameters are the expressions used in the assertion // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // // lhs_expression: "foo" // rhs_expression: "bar" // lhs_value: "5" // rhs_value: "6" // // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string "Ignoring case" will // be inserted into the message. AssertionResult EqFailure(const char* lhs_expression, const char* rhs_expression, const std::string& lhs_value, const std::string& rhs_value, bool ignoring_case) { Message msg; msg << " Expected: " << lhs_expression; if (lhs_value != lhs_expression) { msg << "\n Which is: " << lhs_value; } msg << "\nTo be equal to: " << rhs_expression; if (rhs_value != rhs_expression) { msg << "\n Which is: " << rhs_value; } if (ignoring_case) { msg << "\nIgnoring case"; } if (!lhs_value.empty() && !rhs_value.empty()) { const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value); const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value); if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { msg << "\nWith diff:\n" << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); } } return AssertionFailure() << msg; } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. std::string GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } // Helper function for implementing ASSERT_NEAR. AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); // TODO(wan): do not print the value of an expression if it's // already a literal. return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << expr1 << " evaluates to " << val1 << ",\n" << expr2 << " evaluates to " << val2 << ", and\n" << abs_error_expr << " evaluates to " << abs_error << "."; } // Helper template for implementing FloatLE() and DoubleLE(). template <typename RawType> AssertionResult FloatingPointLE(const char* expr1, const char* expr2, RawType val1, RawType val2) { // Returns success if val1 is less than val2, if (val1 < val2) { return AssertionSuccess(); } // or if val1 is almost equal to val2. const FloatingPoint<RawType> lhs(val1), rhs(val2); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } // Note that the above two checks will both fail if either val1 or // val2 is NaN, as the IEEE floating-point standard requires that // any predicate involving a NaN must return false. ::std::stringstream val1_ss; val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val1; ::std::stringstream val2_ss; val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val2; return AssertionFailure() << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" << " Actual: " << StringStreamToString(&val1_ss) << " vs " << StringStreamToString(&val2_ss); } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2) { return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); } // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2) { return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); } namespace internal { // The helper function for {ASSERT|EXPECT}_EQ with int or enum // arguments. AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { if (lhs == rhs) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), FormatForComparisonFailureMessage(rhs, lhs), false); } // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here // just to avoid copy-and-paste of similar code. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ BiggestInt val1, BiggestInt val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ return AssertionFailure() \ << "Expected: (" << expr1 << ") " #op " (" << expr2\ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ << " vs " << FormatForComparisonFailureMessage(val2, val1);\ }\ } // Implements the helper function for {ASSERT|EXPECT}_NE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(NE, !=) // Implements the helper function for {ASSERT|EXPECT}_LE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LE, <=) // Implements the helper function for {ASSERT|EXPECT}_LT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LT, < ) // Implements the helper function for {ASSERT|EXPECT}_GE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GE, >=) // Implements the helper function for {ASSERT|EXPECT}_GT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GT, > ) #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), true); } // The helper function for {ASSERT|EXPECT}_STRNE. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } // The helper function for {ASSERT|EXPECT}_STRCASENE. AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } } // namespace internal namespace { // Helper functions for implementing IsSubString() and IsNotSubstring(). // This group of overloaded functions return true iff needle is a // substring of haystack. NULL is considered a substring of itself // only. bool IsSubstringPred(const char* needle, const char* haystack) { if (needle == NULL || haystack == NULL) return needle == haystack; return strstr(haystack, needle) != NULL; } bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { if (needle == NULL || haystack == NULL) return needle == haystack; return wcsstr(haystack, needle) != NULL; } // StringType here can be either ::std::string or ::std::wstring. template <typename StringType> bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } // This function implements either IsSubstring() or IsNotSubstring(), // depending on the value of the expected_to_be_substring parameter. // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template <typename StringType> AssertionResult IsSubstringImpl( bool expected_to_be_substring, const char* needle_expr, const char* haystack_expr, const StringType& needle, const StringType& haystack) { if (IsSubstringPred(needle, haystack) == expected_to_be_substring) return AssertionSuccess(); const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; return AssertionFailure() << "Value of: " << needle_expr << "\n" << " Actual: " << begin_string_quote << needle << "\"\n" << "Expected: " << (expected_to_be_substring ? "" : "not ") << "a substring of " << haystack_expr << "\n" << "Which is: " << begin_string_quote << haystack << "\""; } } // namespace // IsSubstring() and IsNotSubstring() check whether needle is a // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif // GTEST_HAS_STD_WSTRING namespace internal { #if GTEST_OS_WINDOWS namespace { // Helper function for IsHRESULT{SuccessFailure} predicates AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT # if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't support FormatMessage. const char error_text[] = ""; # else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. char error_text[kBufSize] = { '\0' }; DWORD message_length = ::FormatMessageA(kFlags, 0, // no source, we're asking system hr, // the error 0, // no line width restrictions error_text, // output buffer kBufSize, // buf size NULL); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing CR-LF) for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } # endif // GTEST_OS_WINDOWS_MOBILE const std::string error_hex("0x" + String::FormatHexInt(hr)); return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" << " Actual: " << error_hex << " " << error_text << "\n"; } } // namespace AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT if (SUCCEEDED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "succeeds", hr); } AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT if (FAILED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "fails", hr); } #endif // GTEST_OS_WINDOWS // Utility functions for encoding Unicode text (wide strings) in // UTF-8. // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 // like this: // // Code-point length Encoding // 0 - 7 bits 0xxxxxxx // 8 - 11 bits 110xxxxx 10xxxxxx // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be // shifted to the right by n bits. inline UInt32 ChopLowBits(UInt32* bits, int n) { const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1); *bits >>= n; return low_bits; } // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". std::string CodePointToUtf8(UInt32 code_point) { if (code_point > kMaxCodePoint4) { return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; } char str[5]; // Big enough for the largest valid code point. if (code_point <= kMaxCodePoint1) { str[1] = '\0'; str[0] = static_cast<char>(code_point); // 0xxxxxxx } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx } else if (code_point <= kMaxCodePoint3) { str[3] = '\0'; str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx } else { // code_point <= kMaxCodePoint4 str[4] = '\0'; str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx } return str; } -// The following two functions only make sense if the the system +// The following two functions only make sense if the system // uses UTF-16 for wide string encoding. All supported systems // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. // Determines if the arguments constitute UTF-16 surrogate pair // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; } // Creates a Unicode code point from UTF16 surrogate pair. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second) { const UInt32 mask = (1 << 10) - 1; return (sizeof(wchar_t) == 2) ? (((first & mask) << 10) | (second & mask)) + 0x10000 : // This function should not be called when the condition is // false, but we provide a sensible default in case it is. static_cast<UInt32>(first); } // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { UInt32 unicode_code_point; if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast<UInt32>(str[i]); } stream << CodePointToUtf8(unicode_code_point); } return StringStreamToString(&stream); } // Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". std::string String::ShowWideCString(const wchar_t * wide_c_str) { if (wide_c_str == NULL) return "(null)"; return internal::WideStringToUtf8(wide_c_str, -1); } // Compares two wide C strings. Returns true iff they have the same // content. // // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; return wcscmp(lhs, rhs) == 0; } // Helper function for *_STREQ on wide strings. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // Helper function for *_STRNE on wide strings. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2); } // Compares two C strings, ignoring case. Returns true iff they have // the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; return posix::StrCaseCmp(lhs, rhs) == 0; } // Compares two wide C strings, ignoring case. Returns true iff they // have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; #if GTEST_OS_WINDOWS return _wcsicmp(lhs, rhs) == 0; #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID return wcscasecmp(lhs, rhs) == 0; #else // Android, Mac OS X and Cygwin don't define wcscasecmp. // Other unknown OSes may not define it either. wint_t left, right; do { left = towlower(*lhs++); right = towlower(*rhs++); } while (left && left == right); return left == right; #endif // OS selector } // Returns true iff str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. bool String::EndsWithCaseInsensitive( const std::string& str, const std::string& suffix) { const size_t str_len = str.length(); const size_t suffix_len = suffix.length(); return (str_len >= suffix_len) && CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, suffix.c_str()); } // Formats an int value as "%02d". std::string String::FormatIntWidth2(int value) { std::stringstream ss; ss << std::setfill('0') << std::setw(2) << value; return ss.str(); } // Formats an int value as "%X". std::string String::FormatHexInt(int value) { std::stringstream ss; ss << std::hex << std::uppercase << value; return ss.str(); } // Formats a byte as "%02X". std::string String::FormatByte(unsigned char value) { std::stringstream ss; ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase << static_cast<unsigned int>(value); return ss.str(); } // Converts the buffer in a stringstream to an std::string, converting NUL // bytes to "\\0" along the way. std::string StringStreamToString(::std::stringstream* ss) { const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); std::string result; result.reserve(2 * (end - start)); for (const char* ch = start; ch != end; ++ch) { if (*ch == '\0') { result += "\\0"; // Replaces NUL with "\\0"; } else { result += *ch; } } return result; } // Appends the user-supplied message to the Google-Test-generated message. std::string AppendUserMessage(const std::string& gtest_msg, const Message& user_msg) { // Appends the user message if it's non-empty. const std::string user_msg_string = user_msg.GetString(); if (user_msg_string.empty()) { return gtest_msg; } return gtest_msg + "\n" + user_msg_string; } } // namespace internal // class TestResult // Creates an empty TestResult. TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) { } // D'tor. TestResult::~TestResult() { } // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(i); } // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(i); } // Clears the test part results. void TestResult::ClearTestPartResults() { test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { test_part_results_.push_back(test_part_result); } // Adds a test property to the list. If a property with the same key as the // supplied property is already represented, the value of this test_property // replaces the old value for that key. void TestResult::RecordProperty(const std::string& xml_element, const TestProperty& test_property) { if (!ValidateTestProperty(xml_element, test_property)) { return; } internal::MutexLock lock(&test_properites_mutex_); const std::vector<TestProperty>::iterator property_with_matching_key = std::find_if(test_properties_.begin(), test_properties_.end(), internal::TestPropertyKeyIs(test_property.key())); if (property_with_matching_key == test_properties_.end()) { test_properties_.push_back(test_property); return; } property_with_matching_key->SetValue(test_property.value()); } // The list of reserved attributes used in the <testsuites> element of XML // output. static const char* const kReservedTestSuitesAttributes[] = { "disabled", "errors", "failures", "name", "random_seed", "tests", "time", "timestamp" }; // The list of reserved attributes used in the <testsuite> element of XML // output. static const char* const kReservedTestSuiteAttributes[] = { "disabled", "errors", "failures", "name", "tests", "time" }; // The list of reserved attributes used in the <testcase> element of XML output. static const char* const kReservedTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param" }; template <int kSize> std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { return std::vector<std::string>(array, array + kSize); } static std::vector<std::string> GetReservedAttributesForElement( const std::string& xml_element) { if (xml_element == "testsuites") { return ArrayAsVector(kReservedTestSuitesAttributes); } else if (xml_element == "testsuite") { return ArrayAsVector(kReservedTestSuiteAttributes); } else if (xml_element == "testcase") { return ArrayAsVector(kReservedTestCaseAttributes); } else { GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; } // This code is unreachable but some compilers may not realizes that. return std::vector<std::string>(); } static std::string FormatWordList(const std::vector<std::string>& words) { Message word_list; for (size_t i = 0; i < words.size(); ++i) { if (i > 0 && words.size() > 2) { word_list << ", "; } if (i == words.size() - 1) { word_list << "and "; } word_list << "'" << words[i] << "'"; } return word_list.GetString(); } bool ValidateTestPropertyName(const std::string& property_name, const std::vector<std::string>& reserved_names) { if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != reserved_names.end()) { ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name << " (" << FormatWordList(reserved_names) << " are reserved by " << GTEST_NAME_ << ")"; return false; } return true; } // Adds a failure if the key is a reserved attribute of the element named // xml_element. Returns true if the property is valid. bool TestResult::ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property) { return ValidateTestPropertyName(test_property.key(), GetReservedAttributesForElement(xml_element)); } // Clears the object. void TestResult::Clear() { test_part_results_.clear(); test_properties_.clear(); death_test_count_ = 0; elapsed_time_ = 0; } // Returns true iff the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { if (GetTestPartResult(i).failed()) return true; } return false; } // Returns true iff the test part fatally failed. static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } // Returns true iff the test fatally failed. bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } // Returns true iff the test part non-fatally failed. static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } // Returns true iff the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int TestResult::total_part_count() const { return static_cast<int>(test_part_results_.size()); } // Returns the number of the test properties. int TestResult::test_property_count() const { return static_cast<int>(test_properties_.size()); } // class Test // Creates a Test object. // The c'tor saves the states of all flags. Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { } // The d'tor restores the states of all flags. The actual work is // done by the d'tor of the gtest_flag_saver_ field, and thus not // visible here. Test::~Test() { } // Sets up the test fixture. // // A sub-class may override this. void Test::SetUp() { } // Tears down the test fixture. // // A sub-class may override this. void Test::TearDown() { } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, const std::string& value) { UnitTest::GetInstance()->RecordProperty(key, value); } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, int value) { Message value_message; value_message << value; RecordProperty(key, value_message.GetString().c_str()); } namespace internal { void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message) { // This function is a friend of UnitTest and as such has access to // AddTestPartResult. UnitTest::GetInstance()->AddTestPartResult( result_type, NULL, // No info about the source file where the exception occurred. -1, // We have no info on which line caused the exception. message, ""); // No stack trace, either. } } // namespace internal // Google Test requires all tests in the same test case to use the same test // fixture class. This function checks if the current test has the // same fixture class as the first test in the current test case. If // yes, it returns true; otherwise it generates a Google Test failure and // returns false. bool Test::HasSameFixtureClass() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); const TestCase* const test_case = impl->current_test_case(); // Info about the first test in the current test case. const TestInfo* const first_test_info = test_case->test_info_list()[0]; const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; const char* const first_test_name = first_test_info->name(); // Info about the current test. const TestInfo* const this_test_info = impl->current_test_info(); const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; const char* const this_test_name = this_test_info->name(); if (this_fixture_id != first_fixture_id) { // Is the first test defined using TEST? const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); // Is this test defined using TEST? const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); if (first_is_TEST || this_is_TEST) { // Both TEST and TEST_F appear in same test case, which is incorrect. // Tell the user how to fix this. // Gets the name of the TEST and the name of the TEST_F. Note // that first_is_TEST and this_is_TEST cannot both be true, as // the fixture IDs are different for the two tests. const char* const TEST_name = first_is_TEST ? first_test_name : this_test_name; const char* const TEST_F_name = first_is_TEST ? this_test_name : first_test_name; ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" << "class, so mixing TEST_F and TEST in the same test case is\n" << "illegal. In test case " << this_test_info->test_case_name() << ",\n" << "test " << TEST_F_name << " is defined using TEST_F but\n" << "test " << TEST_name << " is defined using TEST. You probably\n" << "want to change the TEST to TEST_F or move it to another test\n" << "case."; } else { // Two fixture classes with the same name appear in two different // namespaces, which is not allowed. Tell the user how to fix this. ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" << "class. However, in test case " << this_test_info->test_case_name() << ",\n" << "you defined test " << first_test_name << " and test " << this_test_name << "\n" << "using two different test fixture classes. This can happen if\n" << "the two classes are from different namespaces or translation\n" << "units and have the same name. You should probably rename one\n" << "of the classes to put the tests into different test cases."; } return false; } return true; } #if GTEST_HAS_SEH // Adds an "exception thrown" fatal failure to the current test. This // function returns its result via an output parameter pointer because VC++ // prohibits creation of objects with destructors on stack in functions // using __try (see error C2712). static std::string* FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; message << "SEH exception with code 0x" << std::setbase(16) << exception_code << std::setbase(10) << " thrown in " << location << "."; return new std::string(message.GetString()); } #endif // GTEST_HAS_SEH namespace internal { #if GTEST_HAS_EXCEPTIONS // Adds an "exception thrown" fatal failure to the current test. static std::string FormatCxxExceptionMessage(const char* description, const char* location) { Message message; if (description != NULL) { message << "C++ exception with description \"" << description << "\""; } else { message << "Unknown C++ exception"; } message << " thrown in " << location << "."; return message.GetString(); } static std::string PrintTestPartResultToString( const TestPartResult& test_part_result); GoogleTestFailureException::GoogleTestFailureException( const TestPartResult& failure) : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} #endif // GTEST_HAS_EXCEPTIONS // We put these helper functions in the internal namespace as IBM's xlC // compiler rejects the code if they were declared static. // Runs the given method and handles SEH exceptions it throws, when // SEH is supported; returns the 0-value for type Result in case of an // SEH exception. (Microsoft compilers cannot handle SEH and C++ // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template <class T, typename Result> Result HandleSehExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { #if GTEST_HAS_SEH __try { return (object->*method)(); } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT GetExceptionCode())) { // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). std::string* exception_message = FormatSehExceptionMessage( GetExceptionCode(), location); internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); delete exception_message; return static_cast<Result>(0); } #else (void)location; return (object->*method)(); #endif // GTEST_HAS_SEH } // Runs the given method and catches and reports C++ and/or SEH-style // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template <class T, typename Result> Result HandleExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { // NOTE: The user code can affect the way in which Google Test handles // exceptions by setting GTEST_FLAG(catch_exceptions), but only before // RUN_ALL_TESTS() starts. It is technically possible to check the flag // after the exception is caught and either report or re-throw the // exception based on the flag's value: // // try { // // Perform the test method. // } catch (...) { // if (GTEST_FLAG(catch_exceptions)) // // Report the exception as failure. // else // throw; // Re-throws the original exception. // } // // However, the purpose of this flag is to allow the program to drop into // the debugger when the exception is thrown. On most platforms, once the // control enters the catch block, the exception origin information is // lost and the debugger will stop the program at the point of the // re-throw in this function -- instead of at the point of the original // throw statement in the code under test. For this reason, we perform // the check early, sacrificing the ability to affect Google Test's // exception handling in the method where the exception is thrown. if (internal::GetUnitTestImpl()->catch_exceptions()) { #if GTEST_HAS_EXCEPTIONS try { return HandleSehExceptionsInMethodIfSupported(object, method, location); } catch (const internal::GoogleTestFailureException&) { // NOLINT // This exception type can only be thrown by a failed Google // Test assertion with the intention of letting another testing // framework catch it. Therefore we just re-throw it. throw; } catch (const std::exception& e) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(e.what(), location)); } catch (...) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(NULL, location)); } return static_cast<Result>(0); #else return HandleSehExceptionsInMethodIfSupported(object, method, location); #endif // GTEST_HAS_EXCEPTIONS } else { return (object->*method)(); } } } // namespace internal // Runs the test and updates the test result. void Test::Run() { if (!HasSameFixtureClass()) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); // We will run the test only if SetUp() was successful. if (!HasFatalFailure()) { impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TestBody, "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TearDown, "TearDown()"); } // Returns true iff the current test has a fatal failure. bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); } // Returns true iff the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { return internal::GetUnitTestImpl()->current_test_result()-> HasNonfatalFailure(); } // class TestInfo // Constructs a TestInfo object. It assumes ownership of the test factory // object. TestInfo::TestInfo(const std::string& a_test_case_name, const std::string& a_name, const char* a_type_param, const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : test_case_name_(a_test_case_name), name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), value_param_(a_value_param ? new std::string(a_value_param) : NULL), location_(a_code_location), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), matches_filter_(false), factory_(factory), result_() {} // Destructs a TestInfo object. TestInfo::~TestInfo() { delete factory_; } namespace internal { // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_case_name: name of the test case // name: name of the test // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, // or NULL if this is not a value-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = new TestInfo(test_case_name, name, type_param, value_param, code_location, fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } #if GTEST_HAS_PARAM_TEST void ReportInvalidTestCaseType(const char* test_case_name, CodeLocation code_location) { Message errors; errors << "Attempted redefinition of test case " << test_case_name << ".\n" << "All tests in the same test case must use the same test fixture\n" << "class. However, in test case " << test_case_name << ", you tried\n" << "to define a test using a fixture class different from the one\n" << "used earlier. This can happen if the two fixture classes are\n" << "from different namespaces and have the same name. You should\n" << "probably rename one of the classes to put the tests into different\n" << "test cases."; fprintf(stderr, "%s %s", FormatFileLocation(code_location.file.c_str(), code_location.line).c_str(), errors.GetString().c_str()); } #endif // GTEST_HAS_PARAM_TEST } // namespace internal namespace { // A predicate that checks the test name of a TestInfo against a known // value. // // This is used for implementation of the TestCase class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestNameIs is copyable. class TestNameIs { public: // Constructor. // // TestNameIs has NO default constructor. explicit TestNameIs(const char* name) : name_(name) {} // Returns true iff the test name of test_info matches name_. bool operator()(const TestInfo * test_info) const { return test_info && test_info->name() == name_; } private: std::string name_; }; } // namespace namespace internal { // This method expands all parameterized tests registered with macros TEST_P // and INSTANTIATE_TEST_CASE_P into regular tests and registers those. // This will be done just once during the program runtime. void UnitTestImpl::RegisterParameterizedTests() { #if GTEST_HAS_PARAM_TEST if (!parameterized_tests_registered_) { parameterized_test_registry_.RegisterTests(); parameterized_tests_registered_ = true; } #endif } } // namespace internal // Creates the test object, runs it, records its result, and then // deletes it. void TestInfo::Run() { if (!should_run_) return; // Tells UnitTest where to store test result. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); // Notifies the unit test event listeners that a test is about to start. repeater->OnTestStart(*this); const TimeInMillis start = internal::GetTimeInMillis(); impl->os_stack_trace_getter()->UponLeavingGTest(); // Creates the test object. Test* const test = internal::HandleExceptionsInMethodIfSupported( factory_, &internal::TestFactoryBase::CreateTest, "the test fixture's constructor"); // Runs the test only if the test object was created and its // constructor didn't generate a fatal failure. if ((test != NULL) && !Test::HasFatalFailure()) { // This doesn't throw as all user code that can throw are wrapped into // exception handling code. test->Run(); } // Deletes the test object. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); result_.set_elapsed_time(internal::GetTimeInMillis() - start); // Notifies the unit test event listener that a test has just finished. repeater->OnTestEnd(*this); // Tells UnitTest to stop associating assertion results to this // test. impl->set_current_test_info(NULL); } // class TestCase // Gets the number of successful tests in this test case. int TestCase::successful_test_count() const { return CountIf(test_info_list_, TestPassed); } // Gets the number of failed tests in this test case. int TestCase::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } // Gets the number of disabled tests that will be reported in the XML report. int TestCase::reportable_disabled_test_count() const { return CountIf(test_info_list_, TestReportableDisabled); } // Gets the number of disabled tests in this test case. int TestCase::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } // Gets the number of tests to be printed in the XML report. int TestCase::reportable_test_count() const { return CountIf(test_info_list_, TestReportable); } // Get the number of tests in this test case that should run. int TestCase::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); } // Gets the number of all tests. int TestCase::total_test_count() const { return static_cast<int>(test_info_list_.size()); } // Creates a TestCase with the given name. // // Arguments: // // name: name of the test case // a_type_param: the name of the test case's type parameter, or NULL if // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase::TestCase(const char* a_name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) : name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), set_up_tc_(set_up_tc), tear_down_tc_(tear_down_tc), should_run_(false), elapsed_time_(0) { } // Destructor of TestCase. TestCase::~TestCase() { // Deletes every Test in the collection. ForEach(test_info_list_, internal::Delete<TestInfo>); } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* TestCase::GetTestInfo(int i) const { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? NULL : test_info_list_[index]; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* TestCase::GetMutableTestInfo(int i) { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? NULL : test_info_list_[index]; } // Adds a test to this test case. Will delete the test upon // destruction of the TestCase object. void TestCase::AddTestInfo(TestInfo * test_info) { test_info_list_.push_back(test_info); test_indices_.push_back(static_cast<int>(test_indices_.size())); } // Runs every test in this TestCase. void TestCase::Run() { if (!should_run_) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_case(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); repeater->OnTestCaseStart(*this); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); const internal::TimeInMillis start = internal::GetTimeInMillis(); for (int i = 0; i < total_test_count(); i++) { GetMutableTestInfo(i)->Run(); } elapsed_time_ = internal::GetTimeInMillis() - start; impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); repeater->OnTestCaseEnd(*this); impl->set_current_test_case(NULL); } // Clears the results of all tests in this test case. void TestCase::ClearResult() { ad_hoc_test_result_.Clear(); ForEach(test_info_list_, TestInfo::ClearTestResult); } // Shuffles the tests in this test case. void TestCase::ShuffleTests(internal::Random* random) { Shuffle(random, &test_indices_); } // Restores the test order to before the first shuffle. void TestCase::UnshuffleTests() { for (size_t i = 0; i < test_indices_.size(); i++) { test_indices_[i] = static_cast<int>(i); } } // Formats a countable noun. Depending on its quantity, either the // singular form or the plural form is used. e.g. // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". static std::string FormatCountableNoun(int count, const char * singular_form, const char * plural_form) { return internal::StreamableToString(count) + " " + (count == 1 ? singular_form : plural_form); } // Formats the count of tests. static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } // Formats the count of test cases. static std::string FormatTestCaseCount(int test_case_count) { return FormatCountableNoun(test_case_count, "test case", "test cases"); } // Converts a TestPartResult::Type enum to human-friendly string // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. static const char * TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSuccess: return "Success"; case TestPartResult::kNonFatalFailure: case TestPartResult::kFatalFailure: #ifdef _MSC_VER return "error: "; #else return "Failure\n"; #endif default: return "Unknown result type"; } } namespace internal { // Prints a TestPartResult to an std::string. static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { return (Message() << internal::FormatFileLocation(test_part_result.file_name(), test_part_result.line_number()) << " " << TestPartResultTypeToString(test_part_result.type()) << test_part_result.message()).GetString(); } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); // If the test program runs in Visual Studio or a debugger, the // following statements add the test part result message to the Output // window such that the user can double-click on it to jump to the // corresponding source code location; otherwise they do nothing. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // We don't call OutputDebugString*() on Windows Mobile, as printing // to stdout is done by OutputDebugString() there already - we don't // want the same message printed twice. ::OutputDebugStringA(result.c_str()); ::OutputDebugStringA("\n"); #endif } // class PrettyUnitTestResultPrinter enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Returns the character attribute for the given color. WORD GetColorAttribute(GTestColor color) { switch (color) { case COLOR_RED: return FOREGROUND_RED; case COLOR_GREEN: return FOREGROUND_GREEN; case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; default: return 0; } } +int GetBitOffset(WORD color_mask) { + if (color_mask == 0) return 0; + + int bitOffset = 0; + while((color_mask & 1) == 0) { + color_mask >>= 1; + ++bitOffset; + } + return bitOffset; +} + +WORD GetNewColor(GTestColor color, WORD old_color_attrs) { + // Let's reuse the BG + static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY; + static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; + const WORD existing_bg = old_color_attrs & background_mask; + + WORD new_color = GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY; + static const int bg_bitOffset = GetBitOffset(background_mask); + static const int fg_bitOffset = GetBitOffset(foreground_mask); + + if (((new_color & background_mask) >> bg_bitOffset) == ((new_color & foreground_mask) >> fg_bitOffset)) { + new_color ^= FOREGROUND_INTENSITY; //invert intensity + } + return new_color; +} + #else // Returns the ANSI color code for the given color. COLOR_DEFAULT is // an invalid input. const char* GetAnsiColorCode(GTestColor color) { switch (color) { case COLOR_RED: return "1"; case COLOR_GREEN: return "2"; case COLOR_YELLOW: return "3"; default: return NULL; }; } #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // Returns true iff Google Test should use colors in the output. bool ShouldUseColor(bool stdout_is_tty) { const char* const gtest_color = GTEST_FLAG(color).c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { #if GTEST_OS_WINDOWS // On Windows the TERM variable is usually not set, but the // console there does support colors. return stdout_is_tty; #else // On non-Windows platforms, we rely on the TERM variable. const char* const term = posix::GetEnv("TERM"); const bool term_supports_color = String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "screen-256color") || String::CStringEquals(term, "tmux") || String::CStringEquals(term, "tmux-256color") || String::CStringEquals(term, "rxvt-unicode") || String::CStringEquals(term, "rxvt-unicode-256color") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; #endif // GTEST_OS_WINDOWS } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. } // Helpers for printing colored strings to stdout. Note that on Windows, we // cannot simply emit special characters and have the terminal change colors. // This routine must actually emit the characters rather than return a string // that would be colored when printed, as can be done on Linux. GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT const bool use_color = AlwaysFalse(); #else static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); const bool use_color = in_color_mode && (color != COLOR_DEFAULT); #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS // The '!= 0' comparison is necessary to satisfy MSVC 7.1. if (!use_color) { vprintf(fmt, args); va_end(args); return; } #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. CONSOLE_SCREEN_BUFFER_INFO buffer_info; GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); const WORD old_color_attrs = buffer_info.wAttributes; - + const WORD new_color = GetNewColor(color, old_color_attrs); + // We need to flush the stream buffers into the console before each // SetConsoleTextAttribute call lest it affect the text that is already // printed but has not yet reached the console. fflush(stdout); - SetConsoleTextAttribute(stdout_handle, - GetColorAttribute(color) | FOREGROUND_INTENSITY); + SetConsoleTextAttribute(stdout_handle, new_color); + vprintf(fmt, args); fflush(stdout); // Restores the text color. SetConsoleTextAttribute(stdout_handle, old_color_attrs); #else printf("\033[0;3%sm", GetAnsiColorCode(color)); vprintf(fmt, args); printf("\033[m"); // Resets the terminal to default. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE va_end(args); } // Text printed in Google Test's text output and --gunit_list_tests // output to label the type parameter and value parameter for a test. static const char kTypeParamLabel[] = "TypeParam"; static const char kValueParamLabel[] = "GetParam()"; void PrintFullTestCommentIfPresent(const TestInfo& test_info) { const char* const type_param = test_info.type_param(); const char* const value_param = test_info.value_param(); if (type_param != NULL || value_param != NULL) { printf(", where "); if (type_param != NULL) { printf("%s = %s", kTypeParamLabel, type_param); if (value_param != NULL) printf(" and "); } if (value_param != NULL) { printf("%s = %s", kValueParamLabel, value_param); } } } // This class implements the TestEventListener interface. // // Class PrettyUnitTestResultPrinter is copyable. class PrettyUnitTestResultPrinter : public TestEventListener { public: PrettyUnitTestResultPrinter() {} static void PrintTestName(const char * test_case, const char * test) { printf("%s.%s", test_case, test); } // The following methods override what's in the TestEventListener class. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestCaseStart(const TestCase& test_case); virtual void OnTestStart(const TestInfo& test_info); virtual void OnTestPartResult(const TestPartResult& result); virtual void OnTestEnd(const TestInfo& test_info); virtual void OnTestCaseEnd(const TestCase& test_case); virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} private: static void PrintFailedTests(const UnitTest& unit_test); }; // Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { if (GTEST_FLAG(repeat) != 1) printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); const char* const filter = GTEST_FLAG(filter).c_str(); // Prints the filter if it's not *. This reminds the user that some // tests may be skipped. if (!String::CStringEquals(filter, kUniversalFilter)) { ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter); } if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n", static_cast<int>(shard_index) + 1, internal::posix::GetEnv(kTestTotalShards)); } if (GTEST_FLAG(shuffle)) { ColoredPrintf(COLOR_YELLOW, "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); } ColoredPrintf(COLOR_GREEN, "[==========] "); printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment set-up.\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s", counts.c_str(), test_case.name()); if (test_case.type_param() == NULL) { printf("\n"); } else { printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(COLOR_GREEN, "[ RUN ] "); PrintTestName(test_info.test_case_name(), test_info.name()); printf("\n"); fflush(stdout); } // Called after an assertion failure. void PrettyUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { // If the test part succeeded, we don't need to do anything. if (result.type() == TestPartResult::kSuccess) return; // Print failure message from the assertion (e.g. expected this and got that). PrintTestPartResult(result); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { if (test_info.result()->Passed()) { ColoredPrintf(COLOR_GREEN, "[ OK ] "); } else { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } PrintTestName(test_info.test_case_name(), test_info.name()); if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG(print_time)) { printf(" (%s ms)\n", internal::StreamableToString( test_info.result()->elapsed_time()).c_str()); } else { printf("\n"); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { if (!GTEST_FLAG(print_time)) return; const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(), internal::StreamableToString(test_case.elapsed_time()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment tear-down\n"); fflush(stdout); } // Internal helper for printing the list of failed tests. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { const int failed_test_count = unit_test.failed_test_count(); if (failed_test_count == 0) { return; } for (int i = 0; i < unit_test.total_test_case_count(); ++i) { const TestCase& test_case = *unit_test.GetTestCase(i); if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { continue; } for (int j = 0; j < test_case.total_test_count(); ++j) { const TestInfo& test_info = *test_case.GetTestInfo(j); if (!test_info.should_run() || test_info.result()->Passed()) { continue; } ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s.%s", test_case.name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); printf("\n"); } } } void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { ColoredPrintf(COLOR_GREEN, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); if (GTEST_FLAG(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } printf("\n"); ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); int num_failures = unit_test.failed_test_count(); if (!unit_test.Passed()) { const int failed_test_count = unit_test.failed_test_count(); ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); PrintFailedTests(unit_test); printf("\n%2d FAILED %s\n", num_failures, num_failures == 1 ? "TEST" : "TESTS"); } int num_disabled = unit_test.reportable_disabled_test_count(); if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { if (!num_failures) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } ColoredPrintf(COLOR_YELLOW, " YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); } // Ensure that Google Test output is printed before, e.g., heapchecker output. fflush(stdout); } // End PrettyUnitTestResultPrinter // class TestEventRepeater // // This class forwards events to other event listeners. class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} virtual ~TestEventRepeater(); void Append(TestEventListener *listener); TestEventListener* Release(TestEventListener* listener); // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled() const { return forwarding_enabled_; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } virtual void OnTestProgramStart(const UnitTest& unit_test); virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); virtual void OnTestCaseStart(const TestCase& test_case); virtual void OnTestStart(const TestInfo& test_info); virtual void OnTestPartResult(const TestPartResult& result); virtual void OnTestEnd(const TestInfo& test_info); virtual void OnTestCaseEnd(const TestCase& test_case); virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); virtual void OnTestProgramEnd(const UnitTest& unit_test); private: // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled_; // The list of listeners that receive events. std::vector<TestEventListener*> listeners_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); }; TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete<TestEventListener>); } void TestEventRepeater::Append(TestEventListener *listener) { listeners_.push_back(listener); } // TODO(vladl@google.com): Factor the search functionality into Vector::Find. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { listeners_.erase(listeners_.begin() + i); return listener; } } return NULL; } // Since most methods are very similar, use macros to reduce boilerplate. // This defines a member that forwards the call to all listeners. #define GTEST_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (size_t i = 0; i < listeners_.size(); i++) { \ listeners_[i]->Name(parameter); \ } \ } \ } // This defines a member that forwards the call to all listeners in reverse // order. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ listeners_[i]->Name(parameter); \ } \ } \ } GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) #undef GTEST_REPEATER_METHOD_ #undef GTEST_REVERSE_REPEATER_METHOD_ void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (size_t i = 0; i < listeners_.size(); i++) { listeners_[i]->OnTestIterationStart(unit_test, iteration); } } } void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { listeners_[i]->OnTestIterationEnd(unit_test, iteration); } } } // End TestEventRepeater // This class generates an XML output file. class XmlUnitTestResultPrinter : public EmptyTestEventListener { public: explicit XmlUnitTestResultPrinter(const char* output_file); virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); private: // Is c a whitespace character that is normalized to a space character // when it appears in an XML attribute value? static bool IsNormalizableWhitespace(char c) { return c == 0x9 || c == 0xA || c == 0xD; } // May c appear in a well-formed XML document? static bool IsValidXmlCharacter(char c) { return IsNormalizableWhitespace(c) || c >= 0x20; } // Returns an XML-escaped copy of the input string str. If // is_attribute is true, the text is meant to appear as an attribute // value, and normalizable whitespace is preserved by replacing it // with character references. static std::string EscapeXml(const std::string& str, bool is_attribute); // Returns the given string with all characters invalid in XML removed. static std::string RemoveInvalidXmlCharacters(const std::string& str); // Convenience wrapper around EscapeXml when str is an attribute value. static std::string EscapeXmlAttribute(const std::string& str) { return EscapeXml(str, true); } // Convenience wrapper around EscapeXml when str is not an attribute value. static std::string EscapeXmlText(const char* str) { return EscapeXml(str, false); } // Verifies that the given attribute belongs to the given element and // streams the attribute as XML. static void OutputXmlAttribute(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value); // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. static void OutputXmlCDataSection(::std::ostream* stream, const char* data); // Streams an XML representation of a TestInfo object. static void OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info); // Prints an XML representation of a TestCase object static void PrintXmlTestCase(::std::ostream* stream, const TestCase& test_case); // Prints an XML summary of unit_test to output stream out. static void PrintXmlUnitTest(::std::ostream* stream, const UnitTest& unit_test); // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. // When the std::string is not empty, it includes a space at the beginning, // to delimit this attribute from prior attributes. static std::string TestPropertiesAsXmlAttributes(const TestResult& result); // The output file. const std::string output_file_; GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); }; // Creates a new XmlUnitTestResultPrinter. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.c_str() == NULL || output_file_.empty()) { fprintf(stderr, "XML output file may not be null\n"); fflush(stderr); exit(EXIT_FAILURE); } } // Called after the unit test ends. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { FILE* xmlout = NULL; FilePath output_file(output_file_); FilePath output_dir(output_file.RemoveFileName()); if (output_dir.CreateDirectoriesRecursively()) { xmlout = posix::FOpen(output_file_.c_str(), "w"); } if (xmlout == NULL) { // TODO(wan): report the reason of the failure. // // We don't do it for now as: // // 1. There is no urgent need for it. // 2. It's a bit involved to make the errno variable thread-safe on // all three operating systems (Linux, Windows, and Mac OS). // 3. To interpret the meaning of errno in a thread-safe way, // we need the strerror_r() function, which is not available on // Windows. fprintf(stderr, "Unable to open file \"%s\"\n", output_file_.c_str()); fflush(stderr); exit(EXIT_FAILURE); } std::stringstream stream; PrintXmlUnitTest(&stream, unit_test); fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } // Returns an XML-escaped copy of the input string str. If is_attribute // is true, the text is meant to appear as an attribute value, and // normalizable whitespace is preserved by replacing it with character // references. // // Invalid XML characters in str, if any, are stripped from the output. // It is expected that most, if not all, of the text processed by this // module will consist of ordinary English text. // If this module is ever modified to produce version 1.1 XML output, // most invalid characters can be retained using character references. // TODO(wan): It might be nice to have a minimally invasive, human-readable // escaping scheme for invalid characters, rather than dropping them. std::string XmlUnitTestResultPrinter::EscapeXml( const std::string& str, bool is_attribute) { Message m; for (size_t i = 0; i < str.size(); ++i) { const char ch = str[i]; switch (ch) { case '<': m << "<"; break; case '>': m << ">"; break; case '&': m << "&"; break; case '\'': if (is_attribute) m << "'"; else m << '\''; break; case '"': if (is_attribute) m << """; else m << '"'; break; default: if (IsValidXmlCharacter(ch)) { if (is_attribute && IsNormalizableWhitespace(ch)) m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch)) << ";"; else m << ch; } break; } } return m.GetString(); } // Returns the given string with all characters invalid in XML removed. // Currently invalid characters are dropped from the string. An // alternative is to replace them with certain characters such as . or ?. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( const std::string& str) { std::string output; output.reserve(str.size()); for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) if (IsValidXmlCharacter(*it)) output.push_back(*it); return output; } // The following routines generate an XML representation of a UnitTest // object. // // This is how Google Test concepts map to the DTD: // // <testsuites name="AllTests"> <-- corresponds to a UnitTest object // <testsuite name="testcase-name"> <-- corresponds to a TestCase object // <testcase name="test-name"> <-- corresponds to a TestInfo object // <failure message="...">...</failure> // <failure message="...">...</failure> // <failure message="...">...</failure> // <-- individual assertion failures // </testcase> // </testsuite> // </testsuites> // Formats the given time in milliseconds as seconds. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { ::std::stringstream ss; ss << (static_cast<double>(ms) * 1e-3); return ss.str(); } static bool PortableLocaltime(time_t seconds, struct tm* out) { #if defined(_MSC_VER) return localtime_s(out, &seconds) == 0; #elif defined(__MINGW32__) || defined(__MINGW64__) // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses // Windows' localtime(), which has a thread-local tm buffer. struct tm* tm_ptr = localtime(&seconds); // NOLINT if (tm_ptr == NULL) return false; *out = *tm_ptr; return true; #else return localtime_r(&seconds, out) != NULL; #endif } // Converts the given epoch time in milliseconds to a date string in the ISO // 8601 format, without the timezone information. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { struct tm time_struct; if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) return ""; // YYYY-MM-DDThh:mm:ss return StreamableToString(time_struct.tm_year + 1900) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_sec); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { const char* segment = data; *stream << "<![CDATA["; for (;;) { const char* const next_segment = strstr(segment, "]]>"); if (next_segment != NULL) { stream->write( segment, static_cast<std::streamsize>(next_segment - segment)); *stream << "]]>]]><![CDATA["; segment = next_segment + strlen("]]>"); } else { *stream << segment; break; } } *stream << "]]>"; } void XmlUnitTestResultPrinter::OutputXmlAttribute( std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value) { const std::vector<std::string>& allowed_names = GetReservedAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Attribute " << name << " is not allowed for element <" << element_name << ">."; *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; } // Prints an XML representation of a TestInfo object. // TODO(wan): There is also value in printing properties with the plain printer. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); const std::string kTestcase = "testcase"; *stream << " <testcase"; OutputXmlAttribute(stream, kTestcase, "name", test_info.name()); if (test_info.value_param() != NULL) { OutputXmlAttribute(stream, kTestcase, "value_param", test_info.value_param()); } if (test_info.type_param() != NULL) { OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param()); } OutputXmlAttribute(stream, kTestcase, "status", test_info.should_run() ? "run" : "notrun"); OutputXmlAttribute(stream, kTestcase, "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); OutputXmlAttribute(stream, kTestcase, "classname", test_case_name); *stream << TestPropertiesAsXmlAttributes(result); int failures = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.failed()) { if (++failures == 1) { *stream << ">\n"; } const std::string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const std::string summary = location + "\n" + part.summary(); *stream << " <failure message=\"" << EscapeXmlAttribute(summary.c_str()) << "\" type=\"\">"; const std::string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); *stream << "</failure>\n"; } } if (failures == 0) *stream << " />\n"; else *stream << " </testcase>\n"; } // Prints an XML representation of a TestCase object void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, const TestCase& test_case) { const std::string kTestsuite = "testsuite"; *stream << " <" << kTestsuite; OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); OutputXmlAttribute(stream, kTestsuite, "tests", StreamableToString(test_case.reportable_test_count())); OutputXmlAttribute(stream, kTestsuite, "failures", StreamableToString(test_case.failed_test_count())); OutputXmlAttribute( stream, kTestsuite, "disabled", StreamableToString(test_case.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuite, "errors", "0"); OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(test_case.elapsed_time())); *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) << ">\n"; for (int i = 0; i < test_case.total_test_count(); ++i) { if (test_case.GetTestInfo(i)->is_reportable()) OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); } *stream << " </" << kTestsuite << ">\n"; } // Prints an XML summary of unit_test to output stream out. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, const UnitTest& unit_test) { const std::string kTestsuites = "testsuites"; *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; *stream << "<" << kTestsuites; OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(unit_test.reportable_test_count())); OutputXmlAttribute(stream, kTestsuites, "failures", StreamableToString(unit_test.failed_test_count())); OutputXmlAttribute( stream, kTestsuites, "disabled", StreamableToString(unit_test.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuites, "errors", "0"); OutputXmlAttribute( stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); OutputXmlAttribute(stream, kTestsuites, "time", FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); if (GTEST_FLAG(shuffle)) { OutputXmlAttribute(stream, kTestsuites, "random_seed", StreamableToString(unit_test.random_seed())); } *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; for (int i = 0; i < unit_test.total_test_case_count(); ++i) { if (unit_test.GetTestCase(i)->reportable_test_count() > 0) PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); } *stream << "</" << kTestsuites << ">\n"; } // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( const TestResult& result) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << " " << property.key() << "=" << "\"" << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } // End XmlUnitTestResultPrinter #if GTEST_CAN_STREAM_RESULTS_ // Checks if str contains '=', '&', '%' or '\n' characters. If yes, // replaces them by "%xx" where xx is their hexadecimal value. For // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) // in both time and space -- important as the input str may contain an // arbitrarily long test failure message and stack trace. std::string StreamingListener::UrlEncode(const char* str) { std::string result; result.reserve(strlen(str) + 1); for (char ch = *str; ch != '\0'; ch = *++str) { switch (ch) { case '%': case '=': case '&': case '\n': result.append("%" + String::FormatByte(static_cast<unsigned char>(ch))); break; default: result.push_back(ch); break; } } return result; } void StreamingListener::SocketWriter::MakeConnection() { GTEST_CHECK_(sockfd_ == -1) << "MakeConnection() can't be called when there is already a connection."; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_socktype = SOCK_STREAM; addrinfo* servinfo = NULL; // Use the getaddrinfo() to get a linked list of IP addresses for // the given host name. const int error_num = getaddrinfo( host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); if (error_num != 0) { GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " << gai_strerror(error_num); } // Loop through all the results and connect to the first we can. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; cur_addr = cur_addr->ai_next) { sockfd_ = socket( cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); if (sockfd_ != -1) { // Connect the client socket to the server socket. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { close(sockfd_); sockfd_ = -1; } } } freeaddrinfo(servinfo); // all done with this structure if (sockfd_ == -1) { GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " << host_name_ << ":" << port_num_; } } // End of class Streaming Listener #endif // GTEST_CAN_STREAM_RESULTS__ // Class ScopedTrace // Pushes the given source file location and message onto a per-thread // trace stack maintained by Google Test. ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { TraceInfo trace; trace.file = file; trace.line = line; trace.message = message.GetString(); UnitTest::GetInstance()->PushGTestTrace(trace); } // Pops the info pushed by the c'tor. ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { UnitTest::GetInstance()->PopGTestTrace(); } // class OsStackTraceGetter const char* const OsStackTraceGetterInterface::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; std::string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, int /*skip_count*/) { return ""; } void OsStackTraceGetter::UponLeavingGTest() {} // A helper class that creates the premature-exit file in its // constructor and deletes the file in its destructor. class ScopedPrematureExitFile { public: explicit ScopedPrematureExitFile(const char* premature_exit_filepath) : premature_exit_filepath_(premature_exit_filepath) { // If a path to the premature-exit file is specified... if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') { // create the file with a single "0" character in it. I/O // errors are ignored as there's nothing better we can do and we // don't want to fail the test because of this. FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); fwrite("0", 1, 1, pfile); fclose(pfile); } } ~ScopedPrematureExitFile() { if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { remove(premature_exit_filepath_); } } private: const char* const premature_exit_filepath_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); }; } // namespace internal // class TestEventListeners TestEventListeners::TestEventListeners() : repeater_(new internal::TestEventRepeater()), default_result_printer_(NULL), default_xml_generator_(NULL) { } TestEventListeners::~TestEventListeners() { delete repeater_; } // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the user. void TestEventListeners::Append(TestEventListener* listener) { repeater_->Append(listener); } // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* TestEventListeners::Release(TestEventListener* listener) { if (listener == default_result_printer_) default_result_printer_ = NULL; else if (listener == default_xml_generator_) default_xml_generator_ = NULL; return repeater_->Release(listener); } // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* TestEventListeners::repeater() { return repeater_; } // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { if (default_result_printer_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_result_printer_); default_result_printer_ = listener; if (listener != NULL) Append(listener); } } // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { if (default_xml_generator_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_xml_generator_); default_xml_generator_ = listener; if (listener != NULL) Append(listener); } } // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } void TestEventListeners::SuppressEventForwarding() { repeater_->set_forwarding_enabled(false); } // class UnitTest // Gets the singleton UnitTest object. The first time this method is // called, a UnitTest object is constructed and returned. Consecutive // calls will return the same object. // // We don't protect this under mutex_ as a user is not supposed to // call this before main() starts, from which point on the return // value will never change. UnitTest* UnitTest::GetInstance() { // When compiled with MSVC 7.1 in optimized mode, destroying the // UnitTest object upon exiting the program messes up the exit code, // causing successful tests to appear failed. We have to use a // different implementation in this case to bypass the compiler bug. // This implementation makes the compiler happy, at the cost of // leaking the UnitTest object. // CodeGear C++Builder insists on a public destructor for the // default implementation. Use this implementation to keep good OO // design with private destructor. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) static UnitTest* const instance = new UnitTest; return instance; #else static UnitTest instance; return &instance; #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) } // Gets the number of successful test cases. int UnitTest::successful_test_case_count() const { return impl()->successful_test_case_count(); } // Gets the number of failed test cases. int UnitTest::failed_test_case_count() const { return impl()->failed_test_case_count(); } // Gets the number of all test cases. int UnitTest::total_test_case_count() const { return impl()->total_test_case_count(); } // Gets the number of all test cases that contain at least one test // that should run. int UnitTest::test_case_to_run_count() const { return impl()->test_case_to_run_count(); } // Gets the number of successful tests. int UnitTest::successful_test_count() const { return impl()->successful_test_count(); } // Gets the number of failed tests. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTest::reportable_disabled_test_count() const { return impl()->reportable_disabled_test_count(); } // Gets the number of disabled tests. int UnitTest::disabled_test_count() const { return impl()->disabled_test_count(); } // Gets the number of tests to be printed in the XML report. int UnitTest::reportable_test_count() const { return impl()->reportable_test_count(); } // Gets the number of all tests. int UnitTest::total_test_count() const { return impl()->total_test_count(); } // Gets the number of tests that should run. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } // Gets the time of the test program start, in ms from the start of the // UNIX epoch. internal::TimeInMillis UnitTest::start_timestamp() const { return impl()->start_timestamp(); } // Gets the elapsed time, in milliseconds. internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } // Returns true iff the unit test passed (i.e. all test cases passed). bool UnitTest::Passed() const { return impl()->Passed(); } // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool UnitTest::Failed() const { return impl()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } // Returns the TestResult containing information on test failures and // properties logged outside of individual test cases. const TestResult& UnitTest::ad_hoc_test_result() const { return *impl()->ad_hoc_test_result(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* UnitTest::GetMutableTestCase(int i) { return impl()->GetMutableTestCase(i); } // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in the // order they were registered. After all tests in the program have // finished, all global test environments will be torn-down in the // *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // We don't protect this under mutex_, as we only support calling it // from the main thread. Environment* UnitTest::AddEnvironment(Environment* env) { if (env == NULL) { return NULL; } impl_->environments().push_back(env); return env; } // Adds a TestPartResult to the current TestResult object. All Google Test // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. void UnitTest::AddTestPartResult( TestPartResult::Type result_type, const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; internal::MutexLock lock(&mutex_); if (impl_->gtest_trace_stack().size() > 0) { msg << "\n" << GTEST_NAME_ << " trace:"; for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) << " " << trace.message; } } if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { msg << internal::kStackTraceMarker << os_stack_trace; } const TestPartResult result = TestPartResult(result_type, file_name, line_number, msg.GetString().c_str()); impl_->GetTestPartResultReporterForCurrentThread()-> ReportTestPartResult(result); if (result_type != TestPartResult::kSuccess) { // gtest_break_on_failure takes precedence over // gtest_throw_on_failure. This allows a user to set the latter // in the code (perhaps in order to use Google Test assertions // with another testing framework) and specify the former on the // command line for debugging. if (GTEST_FLAG(break_on_failure)) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Using DebugBreak on Windows allows gtest to still break into a debugger // when a failure happens and both the --gtest_break_on_failure and // the --gtest_catch_exceptions flags are specified. DebugBreak(); #else // Dereference NULL through a volatile pointer to prevent the compiler // from removing. We use this rather than abort() or __builtin_trap() for // portability: Symbian doesn't implement abort() well, and some debuggers // don't correctly trap abort(). *static_cast<volatile int*>(NULL) = 1; #endif // GTEST_OS_WINDOWS } else if (GTEST_FLAG(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS throw internal::GoogleTestFailureException(result); #else // We cannot call abort() as it generates a pop-up in debug mode // that cannot be suppressed in VC 7.1 or below. exit(1); #endif } } } // Adds a TestProperty to the current TestResult object when invoked from // inside a test, to current TestCase's ad_hoc_test_result_ when invoked // from SetUpTestCase or TearDownTestCase, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void UnitTest::RecordProperty(const std::string& key, const std::string& value) { impl_->RecordProperty(TestProperty(key, value)); } // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { const bool in_death_test_child_process = internal::GTEST_FLAG(internal_run_death_test).length() > 0; // Google Test implements this protocol for catching that a test // program exits before returning control to Google Test: // // 1. Upon start, Google Test creates a file whose absolute path // is specified by the environment variable // TEST_PREMATURE_EXIT_FILE. // 2. When Google Test has finished its work, it deletes the file. // // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before // running a Google-Test-based test program and check the existence // of the file at the end of the test execution to see if it has // exited prematurely. // If we are in the child process of a death test, don't // create/delete the premature exit file, as doing so is unnecessary // and will confuse the parent process. Otherwise, create/delete // the file upon entering/leaving this function. If the program // somehow exits before this function has a chance to return, the // premature-exit file will be left undeleted, causing a test runner // that understands the premature-exit-file protocol to report the // test as having failed. const internal::ScopedPrematureExitFile premature_exit_file( in_death_test_child_process ? NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); #if GTEST_HAS_SEH // Either the user wants Google Test to catch exceptions thrown by the // tests or this is executing in the context of death test child // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); # endif // !GTEST_OS_WINDOWS_MOBILE # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); # endif # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // executed. Google Test will notify the user of any unexpected // failure via stderr. // // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. // Users of prior VC versions shall suffer the agony and pain of // clicking through the countless debug dialogs. // TODO(vladl@google.com): find a way to suppress the abort dialog() in the // debug mode when compiled with VC 7.1 or lower. if (!GTEST_FLAG(break_on_failure)) _set_abort_behavior( 0x0, // Clear the following flags: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. # endif } #endif // GTEST_HAS_SEH return internal::HandleExceptionsInMethodIfSupported( impl(), &internal::UnitTestImpl::RunAllTests, "auxiliary test code (environments or event listeners)") ? 0 : 1; } // Returns the working directory when the first TEST() or TEST_F() was // executed. const char* UnitTest::original_working_dir() const { return impl_->original_working_dir_.c_str(); } // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. const TestCase* UnitTest::current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_case(); } // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. const TestInfo* UnitTest::current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_info(); } // Returns the random seed used at the start of the current test run. int UnitTest::random_seed() const { return impl_->random_seed(); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestCaseRegistry& UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { return impl_->parameterized_test_registry(); } #endif // GTEST_HAS_PARAM_TEST // Creates an empty UnitTest. UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); } // Destructor of UnitTest. UnitTest::~UnitTest() { delete impl_; } // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().push_back(trace); } // Pops a trace from the per-thread Google Test trace stack. void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : parent_(parent), GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_( &default_global_test_part_result_reporter_), per_thread_test_part_result_reporter_( &default_per_thread_test_part_result_reporter_), #if GTEST_HAS_PARAM_TEST parameterized_test_registry_(), parameterized_tests_registered_(false), #endif // GTEST_HAS_PARAM_TEST last_death_test_case_(-1), current_test_case_(NULL), current_test_info_(NULL), ad_hoc_test_result_(), os_stack_trace_getter_(NULL), post_flag_parse_init_performed_(false), random_seed_(0), // Will be overridden by the flag before first use. random_(0), // Will be reseeded before first use. start_timestamp_(0), elapsed_time_(0), #if GTEST_HAS_DEATH_TEST death_test_factory_(new DefaultDeathTestFactory), #endif // Will be overridden by the flag before first use. catch_exceptions_(false) { listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); } UnitTestImpl::~UnitTestImpl() { // Deletes every TestCase. ForEach(test_cases_, internal::Delete<TestCase>); // Deletes every Environment. ForEach(environments_, internal::Delete<Environment>); delete os_stack_trace_getter_; } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test, to current test case's ad_hoc_test_result when invoke // from SetUpTestCase/TearDownTestCase, or to the global property set // otherwise. If the result already contains a property with the same key, // the value will be updated. void UnitTestImpl::RecordProperty(const TestProperty& test_property) { std::string xml_element; TestResult* test_result; // TestResult appropriate for property recording. if (current_test_info_ != NULL) { xml_element = "testcase"; test_result = &(current_test_info_->result_); } else if (current_test_case_ != NULL) { xml_element = "testsuite"; test_result = &(current_test_case_->ad_hoc_test_result_); } else { xml_element = "testsuites"; test_result = &ad_hoc_test_result_; } test_result->RecordProperty(xml_element, test_property); } #if GTEST_HAS_DEATH_TEST // Disables event forwarding if the control is currently in a death test // subprocess. Must not be called before InitGoogleTest. void UnitTestImpl::SuppressTestEventsIfInSubprocess() { if (internal_run_death_test_flag_.get() != NULL) listeners()->SuppressEventForwarding(); } #endif // GTEST_HAS_DEATH_TEST // Initializes event listeners performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureXmlOutput() { const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml") { listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (output_format != "") { printf("WARNING: unrecognized output format \"%s\" ignored.\n", output_format.c_str()); fflush(stdout); } } #if GTEST_CAN_STREAM_RESULTS_ // Initializes event listeners for streaming test results in string form. // Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureStreamingOutput() { const std::string& target = GTEST_FLAG(stream_result_to); if (!target.empty()) { const size_t pos = target.find(':'); if (pos != std::string::npos) { listeners()->Append(new StreamingListener(target.substr(0, pos), target.substr(pos+1))); } else { printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", target.c_str()); fflush(stdout); } } } #endif // GTEST_CAN_STREAM_RESULTS_ // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void UnitTestImpl::PostFlagParsingInit() { // Ensures that this function does not execute more than once. if (!post_flag_parse_init_performed_) { post_flag_parse_init_performed_ = true; #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) // Register to send notifications about key process state changes. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) #if GTEST_HAS_DEATH_TEST InitDeathTestSubprocessControlInfo(); SuppressTestEventsIfInSubprocess(); #endif // GTEST_HAS_DEATH_TEST // Registers parameterized tests. This makes parameterized tests // available to the UnitTest reflection API without running // RUN_ALL_TESTS. RegisterParameterizedTests(); // Configures listeners for XML output. This makes it possible for users // to shut down the default XML output before invoking RUN_ALL_TESTS. ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Configures listeners for streaming test results to the specified server. ConfigureStreamingOutput(); #endif // GTEST_CAN_STREAM_RESULTS_ } } // A predicate that checks the name of a TestCase against a known // value. // // This is used for implementation of the UnitTest class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestCaseNameIs is copyable. class TestCaseNameIs { public: // Constructor. explicit TestCaseNameIs(const std::string& name) : name_(name) {} // Returns true iff the name of test_case matches name_. bool operator()(const TestCase* test_case) const { return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; } private: std::string name_; }; // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. It's the CALLER'S // RESPONSIBILITY to ensure that this function is only called WHEN THE // TESTS ARE NOT SHUFFLED. // // Arguments: // // test_case_name: name of the test case // type_param: the name of the test case's type parameter, or NULL if // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) { // Can we find a TestCase with the given name? const std::vector<TestCase*>::const_iterator test_case = std::find_if(test_cases_.begin(), test_cases_.end(), TestCaseNameIs(test_case_name)); if (test_case != test_cases_.end()) return *test_case; // No. Let's create one. TestCase* const new_test_case = new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); // Is this a death test case? if (internal::UnitTestOptions::MatchesFilter(test_case_name, kDeathTestCaseFilter)) { // Yes. Inserts the test case after the last death test case // defined so far. This only works when the test cases haven't // been shuffled. Otherwise we may end up running a death test // after a non-death test. ++last_death_test_case_; test_cases_.insert(test_cases_.begin() + last_death_test_case_, new_test_case); } else { // No. Appends to the end of the list. test_cases_.push_back(new_test_case); } test_case_indices_.push_back(static_cast<int>(test_case_indices_.size())); return new_test_case; } // Helpers for setting up / tearing down the given environment. They // are for use in the ForEach() function. static void SetUpEnvironment(Environment* env) { env->SetUp(); } static void TearDownEnvironment(Environment* env) { env->TearDown(); } // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, the test is considered to be failed, but the // rest of the tests will still be run. // // When parameterized tests are enabled, it expands and registers // parameterized tests first in RegisterParameterizedTests(). // All other functions called from RunAllTests() may safely assume that // parameterized tests are ready to be counted and run. bool UnitTestImpl::RunAllTests() { // Makes sure InitGoogleTest() was called. if (!GTestIsInitialized()) { printf("%s", "\nThis test program did NOT call ::testing::InitGoogleTest " "before calling RUN_ALL_TESTS(). Please fix it.\n"); return false; } // Do not run any test if the --help flag was specified. if (g_help_flag) return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. PostFlagParsingInit(); // Even if sharding is not on, test runners may want to use the // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding // protocol. internal::WriteToShardStatusFileIfNeeded(); // True iff we are in a subprocess for running a thread-safe-style // death test. bool in_subprocess_for_death_test = false; #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); } # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // GTEST_HAS_DEATH_TEST const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, in_subprocess_for_death_test); // Compares the full test names with the filter to decide which // tests to run. const bool has_tests_to_run = FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL : IGNORE_SHARDING_PROTOCOL) > 0; // Lists the tests and exits if the --gtest_list_tests flag was specified. if (GTEST_FLAG(list_tests)) { // This must be called *after* FilterTests() has been called. ListTestsMatchingFilter(); return true; } random_seed_ = GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; // True iff at least one test has failed. bool failed = false; TestEventListener* repeater = listeners()->repeater(); start_timestamp_ = GetTimeInMillis(); repeater->OnTestProgramStart(*parent_); // How many times to repeat the tests? We don't want to repeat them // when we are inside the subprocess of a death test. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); // Repeats forever if the repeat count is negative. const bool forever = repeat < 0; for (int i = 0; forever || i != repeat; i++) { // We want to preserve failures generated by ad-hoc test // assertions executed before RUN_ALL_TESTS(). ClearNonAdHocTestResult(); const TimeInMillis start = GetTimeInMillis(); // Shuffles test cases and tests if requested. if (has_tests_to_run && GTEST_FLAG(shuffle)) { random()->Reseed(random_seed_); // This should be done before calling OnTestIterationStart(), // such that a test event listener can see the actual test order // in the event. ShuffleTests(); } // Tells the unit test event listeners that the tests are about to start. repeater->OnTestIterationStart(*parent_, i); // Runs each test case if there is at least one test to run. if (has_tests_to_run) { // Sets up all environments beforehand. repeater->OnEnvironmentsSetUpStart(*parent_); ForEach(environments_, SetUpEnvironment); repeater->OnEnvironmentsSetUpEnd(*parent_); // Runs the tests only if there was no fatal failure during global // set-up. if (!Test::HasFatalFailure()) { for (int test_index = 0; test_index < total_test_case_count(); test_index++) { GetMutableTestCase(test_index)->Run(); } } // Tears down all environments in reverse order afterwards. repeater->OnEnvironmentsTearDownStart(*parent_); std::for_each(environments_.rbegin(), environments_.rend(), TearDownEnvironment); repeater->OnEnvironmentsTearDownEnd(*parent_); } elapsed_time_ = GetTimeInMillis() - start; // Tells the unit test event listener that the tests have just finished. repeater->OnTestIterationEnd(*parent_, i); // Gets the result and clears it. if (!Passed()) { failed = true; } // Restores the original test order after the iteration. This // allows the user to quickly repro a failure that happens in the // N-th iteration without repeating the first (N - 1) iterations. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in // case the user somehow changes the value of the flag somewhere // (it's always safe to unshuffle the tests). UnshuffleTests(); if (GTEST_FLAG(shuffle)) { // Picks a new random seed for each iteration. random_seed_ = GetNextRandomSeed(random_seed_); } } repeater->OnTestProgramEnd(*parent_); return !failed; } // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded() { const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); if (test_shard_file != NULL) { FILE* const file = posix::FOpen(test_shard_file, "w"); if (file == NULL) { ColoredPrintf(COLOR_RED, "Could not write to the test shard status file \"%s\" " "specified by the %s environment variable.\n", test_shard_file, kTestShardStatusFile); fflush(stdout); exit(EXIT_FAILURE); } fclose(file); } } // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (i.e., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; } const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards << " unset.\n"; ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards << " = " << total_shards << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { const Message msg = Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < " << kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } return total_shards > 1; } // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error // and aborts. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { const char* str_val = posix::GetEnv(var); if (str_val == NULL) { return default_val; } Int32 result; if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); } return result; } // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { return (test_id % total_shards) == shard_index; } // Compares the name of each test with the user-specified filter to // decide whether the test should be run, then records the result in // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. // Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestTotalShards, -1) : -1; const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestShardIndex, -1) : -1; // num_runnable_tests are the number of tests that will // run across all shards (i.e., match filter and are not disabled). // num_selected_tests are the number of tests to be run on // this shard. int num_runnable_tests = 0; int num_selected_tests = 0; for (size_t i = 0; i < test_cases_.size(); i++) { TestCase* const test_case = test_cases_[i]; const std::string &test_case_name = test_case->name(); test_case->set_should_run(false); for (size_t j = 0; j < test_case->test_info_list().size(); j++) { TestInfo* const test_info = test_case->test_info_list()[j]; const std::string test_name(test_info->name()); // A test is disabled if test case name or test name matches // kDisableTestFilter. const bool is_disabled = internal::UnitTestOptions::MatchesFilter(test_case_name, kDisableTestFilter) || internal::UnitTestOptions::MatchesFilter(test_name, kDisableTestFilter); test_info->is_disabled_ = is_disabled; const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(test_case_name, test_name); test_info->matches_filter_ = matches_filter; const bool is_runnable = (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && matches_filter; const bool is_selected = is_runnable && (shard_tests == IGNORE_SHARDING_PROTOCOL || ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests)); num_runnable_tests += is_runnable; num_selected_tests += is_selected; test_info->should_run_ = is_selected; test_case->set_should_run(test_case->should_run() || is_selected); } } return num_selected_tests; } // Prints the given C-string on a single line by replacing all '\n' // characters with string "\\n". If the output takes more than // max_length characters, only prints the first max_length characters // and "...". static void PrintOnOneLine(const char* str, int max_length) { if (str != NULL) { for (int i = 0; *str != '\0'; ++str) { if (i >= max_length) { printf("..."); break; } if (*str == '\n') { printf("\\n"); i += 2; } else { printf("%c", *str); ++i; } } } } // Prints the names of the tests matching the user-specified filter flag. void UnitTestImpl::ListTestsMatchingFilter() { // Print at most this many characters for each type/value parameter. const int kMaxParamLength = 250; for (size_t i = 0; i < test_cases_.size(); i++) { const TestCase* const test_case = test_cases_[i]; bool printed_test_case_name = false; for (size_t j = 0; j < test_case->test_info_list().size(); j++) { const TestInfo* const test_info = test_case->test_info_list()[j]; if (test_info->matches_filter_) { if (!printed_test_case_name) { printed_test_case_name = true; printf("%s.", test_case->name()); if (test_case->type_param() != NULL) { printf(" # %s = ", kTypeParamLabel); // We print the type parameter on a single line to make // the output easy to parse by a program. PrintOnOneLine(test_case->type_param(), kMaxParamLength); } printf("\n"); } printf(" %s", test_info->name()); if (test_info->value_param() != NULL) { printf(" # %s = ", kValueParamLabel); // We print the value parameter on a single line to make the // output easy to parse by a program. PrintOnOneLine(test_info->value_param(), kMaxParamLength); } printf("\n"); } } } fflush(stdout); } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter are // the same; otherwise, deletes the old getter and makes the input the // current getter. void UnitTestImpl::set_os_stack_trace_getter( OsStackTraceGetterInterface* getter) { if (os_stack_trace_getter_ != getter) { delete os_stack_trace_getter_; os_stack_trace_getter_ = getter; } } // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { if (os_stack_trace_getter_ == NULL) { #ifdef GTEST_OS_STACK_TRACE_GETTER_ os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; #else os_stack_trace_getter_ = new OsStackTraceGetter; #endif // GTEST_OS_STACK_TRACE_GETTER_ } return os_stack_trace_getter_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* UnitTestImpl::current_test_result() { return current_test_info_ ? &(current_test_info_->result_) : &ad_hoc_test_result_; } // Shuffles all test cases, and the tests within each test case, // making sure that death tests are still run first. void UnitTestImpl::ShuffleTests() { // Shuffles the death test cases. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); // Shuffles the non-death test cases. ShuffleRange(random(), last_death_test_case_ + 1, static_cast<int>(test_cases_.size()), &test_case_indices_); // Shuffles the tests inside each test case. for (size_t i = 0; i < test_cases_.size(); i++) { test_cases_[i]->ShuffleTests(random()); } } // Restores the test cases and tests to their order before the first shuffle. void UnitTestImpl::UnshuffleTests() { for (size_t i = 0; i < test_cases_.size(); i++) { // Unshuffles the tests in each test case. test_cases_[i]->UnshuffleTests(); // Resets the index of each test case. test_case_indices_[i] = static_cast<int>(i); } } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { // We pass skip_count + 1 to skip this wrapper function in addition // to what the user really wants to skip. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); } // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; } bool IsTrue(bool condition) { return condition; } bool AlwaysTrue() { #if GTEST_HAS_EXCEPTIONS // This condition is always false so AlwaysTrue() never actually throws, // but it makes the compiler think that it may throw. if (IsTrue(false)) throw ClassUniqueToAlwaysTrue(); #endif // GTEST_HAS_EXCEPTIONS return true; } // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. bool SkipPrefix(const char* prefix, const char** pstr) { const size_t prefix_len = strlen(prefix); if (strncmp(*pstr, prefix, prefix_len) == 0) { *pstr += prefix_len; return true; } return false; } // Parses a string as a command line flag. The string should have // the format "--flag=value". When def_optional is true, the "=value" // part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. const char* ParseFlagValue(const char* str, const char* flag, bool def_optional) { // str and flag must not be NULL. if (str == NULL || flag == NULL) return NULL; // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; const size_t flag_len = flag_str.length(); if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; // Skips the flag name. const char* flag_end = str + flag_len; // When def_optional is true, it's OK to not have a "=value" part. if (def_optional && (flag_end[0] == '\0')) { return flag_end; } // If def_optional is true and there are more characters after the // flag name, or if def_optional is false, there must be a '=' after // the flag name. if (flag_end[0] != '=') return NULL; // Returns the string after "=". return flag_end + 1; } // Parses a string for a bool flag, in the form of either // "--flag=value" or "--flag". // // In the former case, the value is taken as true as long as it does // not start with '0', 'f', or 'F'. // // In the latter case, the value is taken as true. // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseBoolFlag(const char* str, const char* flag, bool* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, true); // Aborts if the parsing failed. if (value_str == NULL) return false; // Converts the string value to a bool. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } // Parses a string for an Int32 flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == NULL) return false; // Sets *value to the value of the flag. return ParseInt32(Message() << "The value of flag --" << flag, value_str, value); } // Parses a string for a string flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseStringFlag(const char* str, const char* flag, std::string* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == NULL) return false; // Sets *value to the value of the flag. *value = value_str; return true; } // Determines whether a string has a prefix that Google Test uses for its // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. // If Google Test detects that a command line flag has its prefix but is not // recognized, it will print its help message. Flags starting with // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // internal flags and do not trigger the help message. static bool HasGoogleTestFlagPrefix(const char* str) { return (SkipPrefix("--", &str) || SkipPrefix("-", &str) || SkipPrefix("/", &str)) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); } // Prints a string containing code-encoded text. The following escape // sequences can be used in the string to control the text color: // // @@ prints a single '@' character. // @R changes the color to red. // @G changes the color to green. // @Y changes the color to yellow. // @D changes to the default terminal text color. // // TODO(wan@google.com): Write tests for this once we add stdout // capturing to Google Test. static void PrintColorEncoded(const char* str) { GTestColor color = COLOR_DEFAULT; // The current color. // Conceptually, we split the string into segments divided by escape // sequences. Then we print one segment at a time. At the end of // each iteration, the str pointer advances to the beginning of the // next segment. for (;;) { const char* p = strchr(str, '@'); if (p == NULL) { ColoredPrintf(color, "%s", str); return; } ColoredPrintf(color, "%s", std::string(str, p).c_str()); const char ch = p[1]; str = p + 2; if (ch == '@') { ColoredPrintf(color, "@"); } else if (ch == 'D') { color = COLOR_DEFAULT; } else if (ch == 'R') { color = COLOR_RED; } else if (ch == 'G') { color = COLOR_GREEN; } else if (ch == 'Y') { color = COLOR_YELLOW; } else { --str; } } } static const char kColorEncodedHelpMessage[] = "This program contains tests written using " GTEST_NAME_ ". You can use the\n" "following command line flags to control its behavior:\n" "\n" "Test Selection:\n" " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" " List the names of all tests instead of running them. The name of\n" " TEST(Foo, Bar) is \"Foo.Bar\".\n" " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" "[@G-@YNEGATIVE_PATTERNS]@D\n" " Run only the tests whose name matches one of the positive patterns but\n" " none of the negative patterns. '?' matches any single character; '*'\n" " matches any substring; ':' separates two patterns.\n" " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" " Run all disabled tests too.\n" "\n" "Test Execution:\n" " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" " Run the tests repeatedly; use a negative count to repeat forever.\n" " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" " Randomize tests' orders on every iteration.\n" " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" " Random number seed to use for shuffling test orders (between 1 and\n" " 99999, or 0 to use a seed based on the current time).\n" "\n" "Test Output:\n" " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" " Enable/disable colored output. The default is @Gauto@D.\n" " @G--" GTEST_FLAG_PREFIX_ "print_time=0@D\n" " Don't print the elapsed time of each test.\n" " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" " Generate an XML report in the given directory or with the given file\n" -" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" +" name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" #if GTEST_CAN_STREAM_RESULTS_ " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " Stream test results to the given server.\n" #endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " Turn assertion failures into debugger break-points.\n" " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" " Turn assertion failures into C++ exceptions.\n" " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" " Do not report exceptions as test failures. Instead, allow them\n" " to crash the program or throw a pop-up (on Windows).\n" "\n" "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " "the corresponding\n" "environment variable of a flag (all letters in upper-case). For example, to\n" "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ "color=no@D or set\n" "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" "\n" "For more information, please read the " GTEST_NAME_ " documentation at\n" "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" "(not one in your own code or tests), please report it to\n" "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; bool ParseGoogleTestFlag(const char* const arg) { return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, >EST_FLAG(also_run_disabled_tests)) || ParseBoolFlag(arg, kBreakOnFailureFlag, >EST_FLAG(break_on_failure)) || ParseBoolFlag(arg, kCatchExceptionsFlag, >EST_FLAG(catch_exceptions)) || ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || ParseStringFlag(arg, kDeathTestStyleFlag, >EST_FLAG(death_test_style)) || ParseBoolFlag(arg, kDeathTestUseFork, >EST_FLAG(death_test_use_fork)) || ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || ParseStringFlag(arg, kInternalRunDeathTestFlag, >EST_FLAG(internal_run_death_test)) || ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || ParseInt32Flag(arg, kStackTraceDepthFlag, >EST_FLAG(stack_trace_depth)) || ParseStringFlag(arg, kStreamResultToFlag, >EST_FLAG(stream_result_to)) || ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)); } #if GTEST_USE_OWN_FLAGFILE_FLAG_ void LoadFlagsFromFile(const std::string& path) { FILE* flagfile = posix::FOpen(path.c_str(), "r"); if (!flagfile) { fprintf(stderr, "Unable to open file \"%s\"\n", GTEST_FLAG(flagfile).c_str()); fflush(stderr); exit(EXIT_FAILURE); } std::string contents(ReadEntireFile(flagfile)); posix::FClose(flagfile); std::vector<std::string> lines; SplitString(contents, '\n', &lines); for (size_t i = 0; i < lines.size(); ++i) { if (lines[i].empty()) continue; if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true; } } #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ // Parses the command line for Google Test flags, without initializing // other parts of Google Test. The type parameter CharType can be // instantiated to either char or wchar_t. template <typename CharType> void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { for (int i = 1; i < *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); using internal::ParseBoolFlag; using internal::ParseInt32Flag; using internal::ParseStringFlag; bool remove_flag = false; if (ParseGoogleTestFlag(arg)) { remove_flag = true; #if GTEST_USE_OWN_FLAGFILE_FLAG_ } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) { LoadFlagsFromFile(GTEST_FLAG(flagfile)); remove_flag = true; #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ } else if (arg_string == "--help" || arg_string == "-h" || arg_string == "-?" || arg_string == "/?" || HasGoogleTestFlagPrefix(arg)) { // Both help flag and unrecognized Google Test flags (excluding // internal ones) trigger help display. g_help_flag = true; } if (remove_flag) { // Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being // NULL. The following loop moves the trailing NULL element as // well. for (int j = i; j != *argc; j++) { argv[j] = argv[j + 1]; } // Decrements the argument count. (*argc)--; // We also need to decrement the iterator as we just removed // an element. i--; } } if (g_help_flag) { // We print the help here instead of in RUN_ALL_TESTS(), as the // latter may not be called at all if the user is using Google // Test with another testing framework. PrintColorEncoded(kColorEncodedHelpMessage); } } // Parses the command line for Google Test flags, without initializing // other parts of Google Test. void ParseGoogleTestFlagsOnly(int* argc, char** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } // The internal implementation of InitGoogleTest(). // // The type parameter CharType can be instantiated to either char or // wchar_t. template <typename CharType> void InitGoogleTestImpl(int* argc, CharType** argv) { // We don't want to run the initialization code twice. if (GTestIsInitialized()) return; if (*argc <= 0) return; g_argvs.clear(); for (int i = 0; i != *argc; i++) { g_argvs.push_back(StreamableToString(argv[i])); } ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } } // namespace internal // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. void InitGoogleTest(int* argc, char** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } // This overloaded version can be used in Windows programs compiled in // UNICODE mode. void InitGoogleTest(int* argc, wchar_t** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } std::string TempDir() { #if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) return GTEST_CUSTOM_TEMPDIR_FUNCTION_(); #endif #if GTEST_OS_WINDOWS_MOBILE return "\\temp\\"; #elif GTEST_OS_WINDOWS const char* temp_dir = internal::posix::GetEnv("TEMP"); if (temp_dir == NULL || temp_dir[0] == '\0') return "\\temp\\"; else if (temp_dir[strlen(temp_dir) - 1] == '\\') return temp_dir; else return std::string(temp_dir) + "\\"; #elif GTEST_OS_LINUX_ANDROID return "/sdcard/"; #else return "/tmp/"; #endif // GTEST_OS_WINDOWS_MOBILE } } // namespace testing diff --git a/googletest/test/BUILD.bazel b/googletest/test/BUILD.bazel new file mode 100644 index 00000000..5daa1544 --- /dev/null +++ b/googletest/test/BUILD.bazel @@ -0,0 +1,118 @@ +# Copyright 2017 Google Inc. +# All Rights Reserved. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# Author: misterg@google.com (Gennadiy Civil) +# +# Bazel BUILD for The Google C++ Testing Framework (Google Test) + +licenses(["notice"]) + +""" gtest own tests """ + +#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({ + "//:win": [], + "//conditions:default": [ + "gtest-tuple_test.cc", + ], + }), + copts = select({ + "//:win": ["-DGTEST_USE_OWN_TR1_TUPLE=0"], + "//conditions:default": ["-DGTEST_USE_OWN_TR1_TUPLE=1"], + }), + includes = [ + "googletest", + "googletest/include", + "googletest/include/internal", + "googletest/test", + ], + linkopts = select({ + "//:win": [], + "//conditions:default": [ + "-pthread", + ], + }), + deps = ["//:gtest_main"], +) + +#These googletest tests have their own main() +cc_test( + name = "gtest-listener_test", + size = "small", + srcs = [ + "gtest-listener_test.cc", + ], + deps = [ + "//:gtest", + ], +) + +cc_test( + name = "gtest-unittest-api_test", + size = "small", + srcs = [ + "gtest-unittest-api_test.cc", + ], + deps = [ + "//:gtest", + ], +) + +cc_test( + name = "gtest-param-test_test", + size = "small", + srcs = [ + "gtest-param-test2_test.cc", + "gtest-param-test_test.cc", + "gtest-param-test_test.h", + ], + deps = [ + "//:gtest", + ], +) diff --git a/googletest/test/gtest-port_test.cc b/googletest/test/gtest-port_test.cc index c5067a40..1d25ee6b 100644 --- a/googletest/test/gtest-port_test.cc +++ b/googletest/test/gtest-port_test.cc @@ -1,1311 +1,1311 @@ // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan) // // This file tests the internal cross-platform support utilities. #include "gtest/internal/gtest-port.h" #include <stdio.h> #if GTEST_OS_MAC # include <time.h> #endif // GTEST_OS_MAC #include <list> #include <utility> // For std::pair and std::make_pair. #include <vector> #include "gtest/gtest.h" #include "gtest/gtest-spi.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ using std::make_pair; using std::pair; namespace testing { namespace internal { TEST(IsXDigitTest, WorksForNarrowAscii) { EXPECT_TRUE(IsXDigit('0')); EXPECT_TRUE(IsXDigit('9')); EXPECT_TRUE(IsXDigit('A')); EXPECT_TRUE(IsXDigit('F')); EXPECT_TRUE(IsXDigit('a')); EXPECT_TRUE(IsXDigit('f')); EXPECT_FALSE(IsXDigit('-')); EXPECT_FALSE(IsXDigit('g')); EXPECT_FALSE(IsXDigit('G')); } TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) { EXPECT_FALSE(IsXDigit('\x80')); EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\x80'))); } TEST(IsXDigitTest, WorksForWideAscii) { EXPECT_TRUE(IsXDigit(L'0')); EXPECT_TRUE(IsXDigit(L'9')); EXPECT_TRUE(IsXDigit(L'A')); EXPECT_TRUE(IsXDigit(L'F')); EXPECT_TRUE(IsXDigit(L'a')); EXPECT_TRUE(IsXDigit(L'f')); EXPECT_FALSE(IsXDigit(L'-')); EXPECT_FALSE(IsXDigit(L'g')); EXPECT_FALSE(IsXDigit(L'G')); } TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) { EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80))); EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80))); EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100))); } class Base { public: // Copy constructor and assignment operator do exactly what we need, so we // use them. Base() : member_(0) {} explicit Base(int n) : member_(n) {} virtual ~Base() {} int member() { return member_; } private: int member_; }; class Derived : public Base { public: explicit Derived(int n) : Base(n) {} }; TEST(ImplicitCastTest, ConvertsPointers) { Derived derived(0); EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived)); } TEST(ImplicitCastTest, CanUseInheritance) { Derived derived(1); Base base = ::testing::internal::ImplicitCast_<Base>(derived); EXPECT_EQ(derived.member(), base.member()); } class Castable { public: explicit Castable(bool* converted) : converted_(converted) {} operator Base() { *converted_ = true; return Base(); } private: bool* converted_; }; TEST(ImplicitCastTest, CanUseNonConstCastOperator) { bool converted = false; Castable castable(&converted); Base base = ::testing::internal::ImplicitCast_<Base>(castable); EXPECT_TRUE(converted); } class ConstCastable { public: explicit ConstCastable(bool* converted) : converted_(converted) {} operator Base() const { *converted_ = true; return Base(); } private: bool* converted_; }; TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) { bool converted = false; const ConstCastable const_castable(&converted); Base base = ::testing::internal::ImplicitCast_<Base>(const_castable); EXPECT_TRUE(converted); } class ConstAndNonConstCastable { public: ConstAndNonConstCastable(bool* converted, bool* const_converted) : converted_(converted), const_converted_(const_converted) {} operator Base() { *converted_ = true; return Base(); } operator Base() const { *const_converted_ = true; return Base(); } private: bool* converted_; bool* const_converted_; }; TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) { bool converted = false; bool const_converted = false; ConstAndNonConstCastable castable(&converted, &const_converted); Base base = ::testing::internal::ImplicitCast_<Base>(castable); EXPECT_TRUE(converted); EXPECT_FALSE(const_converted); converted = false; const_converted = false; const ConstAndNonConstCastable const_castable(&converted, &const_converted); base = ::testing::internal::ImplicitCast_<Base>(const_castable); EXPECT_FALSE(converted); EXPECT_TRUE(const_converted); } class To { public: To(bool* converted) { *converted = true; } // NOLINT }; TEST(ImplicitCastTest, CanUseImplicitConstructor) { bool converted = false; To to = ::testing::internal::ImplicitCast_<To>(&converted); (void)to; EXPECT_TRUE(converted); } TEST(IteratorTraitsTest, WorksForSTLContainerIterators) { StaticAssertTypeEq<int, IteratorTraits< ::std::vector<int>::const_iterator>::value_type>(); StaticAssertTypeEq<bool, IteratorTraits< ::std::list<bool>::iterator>::value_type>(); } TEST(IteratorTraitsTest, WorksForPointerToNonConst) { StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>(); StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>(); } TEST(IteratorTraitsTest, WorksForPointerToConst) { StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>(); StaticAssertTypeEq<const void*, IteratorTraits<const void* const*>::value_type>(); } // Tests that the element_type typedef is available in scoped_ptr and refers // to the parameter type. TEST(ScopedPtrTest, DefinesElementType) { StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>(); } // TODO(vladl@google.com): Implement THE REST of scoped_ptr tests. TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) { if (AlwaysFalse()) GTEST_CHECK_(false) << "This should never be executed; " "It's a compilation test only."; if (AlwaysTrue()) GTEST_CHECK_(true); else ; // NOLINT if (AlwaysFalse()) ; // NOLINT else GTEST_CHECK_(true) << ""; } TEST(GtestCheckSyntaxTest, WorksWithSwitch) { switch (0) { case 1: break; default: GTEST_CHECK_(true); } switch (0) case 0: GTEST_CHECK_(true) << "Check failed in switch case"; } // Verifies behavior of FormatFileLocation. TEST(FormatFileLocationTest, FormatsFileLocation) { EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42)); EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42)); } TEST(FormatFileLocationTest, FormatsUnknownFile) { EXPECT_PRED_FORMAT2( IsSubstring, "unknown file", FormatFileLocation(NULL, 42)); EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42)); } TEST(FormatFileLocationTest, FormatsUknownLine) { EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1)); } TEST(FormatFileLocationTest, FormatsUknownFileAndLine) { EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1)); } // Verifies behavior of FormatCompilerIndependentFileLocation. TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) { EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42)); } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) { EXPECT_EQ("unknown file:42", FormatCompilerIndependentFileLocation(NULL, 42)); } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) { EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1)); } TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) { EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1)); } #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX void* ThreadFunc(void* data) { internal::Mutex* mutex = static_cast<internal::Mutex*>(data); mutex->Lock(); mutex->Unlock(); return NULL; } TEST(GetThreadCountTest, ReturnsCorrectValue) { const size_t starting_count = GetThreadCount(); pthread_t thread_id; internal::Mutex mutex; { internal::MutexLock lock(&mutex); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex); ASSERT_EQ(0, pthread_attr_destroy(&attr)); ASSERT_EQ(0, status); EXPECT_EQ(starting_count + 1, GetThreadCount()); } void* dummy; ASSERT_EQ(0, pthread_join(thread_id, &dummy)); // The OS may not immediately report the updated thread count after // joining a thread, causing flakiness in this test. To counter that, we // wait for up to .5 seconds for the OS to report the correct value. for (int i = 0; i < 5; ++i) { if (GetThreadCount() == starting_count) break; SleepMilliseconds(100); } EXPECT_EQ(starting_count, GetThreadCount()); } #else TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) { EXPECT_EQ(0U, GetThreadCount()); } #endif // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { const bool a_false_condition = false; const char regex[] = #ifdef _MSC_VER "gtest-port_test\\.cc\\(\\d+\\):" #elif GTEST_USES_POSIX_RE "gtest-port_test\\.cc:[0-9]+" #else "gtest-port_test\\.cc:\\d+" #endif // _MSC_VER ".*a_false_condition.*Extra info.*"; EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info", regex); } #if GTEST_HAS_DEATH_TEST TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) { EXPECT_EXIT({ GTEST_CHECK_(true) << "Extra info"; ::std::cerr << "Success\n"; exit(0); }, ::testing::ExitedWithCode(0), "Success"); } #endif // GTEST_HAS_DEATH_TEST // Verifies that Google Test choose regular expression engine appropriate to // the platform. The test will produce compiler errors in case of failure. // For simplicity, we only cover the most important platforms here. TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) { #if !GTEST_USES_PCRE # if GTEST_HAS_POSIX_RE EXPECT_TRUE(GTEST_USES_POSIX_RE); # else EXPECT_TRUE(GTEST_USES_SIMPLE_RE); # endif #endif // !GTEST_USES_PCRE } #if GTEST_USES_POSIX_RE # if GTEST_HAS_TYPED_TEST template <typename Str> class RETest : public ::testing::Test {}; // Defines StringTypes as the list of all string types that class RE // supports. typedef testing::Types< ::std::string, # if GTEST_HAS_GLOBAL_STRING ::string, # endif // GTEST_HAS_GLOBAL_STRING const char*> StringTypes; TYPED_TEST_CASE(RETest, StringTypes); // Tests RE's implicit constructors. TYPED_TEST(RETest, ImplicitConstructorWorks) { const RE empty(TypeParam("")); EXPECT_STREQ("", empty.pattern()); const RE simple(TypeParam("hello")); EXPECT_STREQ("hello", simple.pattern()); const RE normal(TypeParam(".*(\\w+)")); EXPECT_STREQ(".*(\\w+)", normal.pattern()); } // Tests that RE's constructors reject invalid regular expressions. TYPED_TEST(RETest, RejectsInvalidRegex) { EXPECT_NONFATAL_FAILURE({ const RE invalid(TypeParam("?")); }, "\"?\" is not a valid POSIX Extended regular expression."); } // Tests RE::FullMatch(). TYPED_TEST(RETest, FullMatchWorks) { const RE empty(TypeParam("")); EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty)); EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty)); const RE re(TypeParam("a.*z")); EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re)); EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re)); EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re)); EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re)); } // Tests RE::PartialMatch(). TYPED_TEST(RETest, PartialMatchWorks) { const RE empty(TypeParam("")); EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty)); EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty)); const RE re(TypeParam("a.*z")); EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re)); EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re)); EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re)); EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re)); EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re)); } # endif // GTEST_HAS_TYPED_TEST #elif GTEST_USES_SIMPLE_RE TEST(IsInSetTest, NulCharIsNotInAnySet) { EXPECT_FALSE(IsInSet('\0', "")); EXPECT_FALSE(IsInSet('\0', "\0")); EXPECT_FALSE(IsInSet('\0', "a")); } TEST(IsInSetTest, WorksForNonNulChars) { EXPECT_FALSE(IsInSet('a', "Ab")); EXPECT_FALSE(IsInSet('c', "")); EXPECT_TRUE(IsInSet('b', "bcd")); EXPECT_TRUE(IsInSet('b', "ab")); } TEST(IsAsciiDigitTest, IsFalseForNonDigit) { EXPECT_FALSE(IsAsciiDigit('\0')); EXPECT_FALSE(IsAsciiDigit(' ')); EXPECT_FALSE(IsAsciiDigit('+')); EXPECT_FALSE(IsAsciiDigit('-')); EXPECT_FALSE(IsAsciiDigit('.')); EXPECT_FALSE(IsAsciiDigit('a')); } TEST(IsAsciiDigitTest, IsTrueForDigit) { EXPECT_TRUE(IsAsciiDigit('0')); EXPECT_TRUE(IsAsciiDigit('1')); EXPECT_TRUE(IsAsciiDigit('5')); EXPECT_TRUE(IsAsciiDigit('9')); } TEST(IsAsciiPunctTest, IsFalseForNonPunct) { EXPECT_FALSE(IsAsciiPunct('\0')); EXPECT_FALSE(IsAsciiPunct(' ')); EXPECT_FALSE(IsAsciiPunct('\n')); EXPECT_FALSE(IsAsciiPunct('a')); EXPECT_FALSE(IsAsciiPunct('0')); } TEST(IsAsciiPunctTest, IsTrueForPunct) { for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) { EXPECT_PRED1(IsAsciiPunct, *p); } } TEST(IsRepeatTest, IsFalseForNonRepeatChar) { EXPECT_FALSE(IsRepeat('\0')); EXPECT_FALSE(IsRepeat(' ')); EXPECT_FALSE(IsRepeat('a')); EXPECT_FALSE(IsRepeat('1')); EXPECT_FALSE(IsRepeat('-')); } TEST(IsRepeatTest, IsTrueForRepeatChar) { EXPECT_TRUE(IsRepeat('?')); EXPECT_TRUE(IsRepeat('*')); EXPECT_TRUE(IsRepeat('+')); } TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) { EXPECT_FALSE(IsAsciiWhiteSpace('\0')); EXPECT_FALSE(IsAsciiWhiteSpace('a')); EXPECT_FALSE(IsAsciiWhiteSpace('1')); EXPECT_FALSE(IsAsciiWhiteSpace('+')); EXPECT_FALSE(IsAsciiWhiteSpace('_')); } TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) { EXPECT_TRUE(IsAsciiWhiteSpace(' ')); EXPECT_TRUE(IsAsciiWhiteSpace('\n')); EXPECT_TRUE(IsAsciiWhiteSpace('\r')); EXPECT_TRUE(IsAsciiWhiteSpace('\t')); EXPECT_TRUE(IsAsciiWhiteSpace('\v')); EXPECT_TRUE(IsAsciiWhiteSpace('\f')); } TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) { EXPECT_FALSE(IsAsciiWordChar('\0')); EXPECT_FALSE(IsAsciiWordChar('+')); EXPECT_FALSE(IsAsciiWordChar('.')); EXPECT_FALSE(IsAsciiWordChar(' ')); EXPECT_FALSE(IsAsciiWordChar('\n')); } TEST(IsAsciiWordCharTest, IsTrueForLetter) { EXPECT_TRUE(IsAsciiWordChar('a')); EXPECT_TRUE(IsAsciiWordChar('b')); EXPECT_TRUE(IsAsciiWordChar('A')); EXPECT_TRUE(IsAsciiWordChar('Z')); } TEST(IsAsciiWordCharTest, IsTrueForDigit) { EXPECT_TRUE(IsAsciiWordChar('0')); EXPECT_TRUE(IsAsciiWordChar('1')); EXPECT_TRUE(IsAsciiWordChar('7')); EXPECT_TRUE(IsAsciiWordChar('9')); } TEST(IsAsciiWordCharTest, IsTrueForUnderscore) { EXPECT_TRUE(IsAsciiWordChar('_')); } TEST(IsValidEscapeTest, IsFalseForNonPrintable) { EXPECT_FALSE(IsValidEscape('\0')); EXPECT_FALSE(IsValidEscape('\007')); } TEST(IsValidEscapeTest, IsFalseForDigit) { EXPECT_FALSE(IsValidEscape('0')); EXPECT_FALSE(IsValidEscape('9')); } TEST(IsValidEscapeTest, IsFalseForWhiteSpace) { EXPECT_FALSE(IsValidEscape(' ')); EXPECT_FALSE(IsValidEscape('\n')); } TEST(IsValidEscapeTest, IsFalseForSomeLetter) { EXPECT_FALSE(IsValidEscape('a')); EXPECT_FALSE(IsValidEscape('Z')); } TEST(IsValidEscapeTest, IsTrueForPunct) { EXPECT_TRUE(IsValidEscape('.')); EXPECT_TRUE(IsValidEscape('-')); EXPECT_TRUE(IsValidEscape('^')); EXPECT_TRUE(IsValidEscape('$')); EXPECT_TRUE(IsValidEscape('(')); EXPECT_TRUE(IsValidEscape(']')); EXPECT_TRUE(IsValidEscape('{')); EXPECT_TRUE(IsValidEscape('|')); } TEST(IsValidEscapeTest, IsTrueForSomeLetter) { EXPECT_TRUE(IsValidEscape('d')); EXPECT_TRUE(IsValidEscape('D')); EXPECT_TRUE(IsValidEscape('s')); EXPECT_TRUE(IsValidEscape('S')); EXPECT_TRUE(IsValidEscape('w')); EXPECT_TRUE(IsValidEscape('W')); } TEST(AtomMatchesCharTest, EscapedPunct) { EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0')); EXPECT_FALSE(AtomMatchesChar(true, '\\', ' ')); EXPECT_FALSE(AtomMatchesChar(true, '_', '.')); EXPECT_FALSE(AtomMatchesChar(true, '.', 'a')); EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\')); EXPECT_TRUE(AtomMatchesChar(true, '_', '_')); EXPECT_TRUE(AtomMatchesChar(true, '+', '+')); EXPECT_TRUE(AtomMatchesChar(true, '.', '.')); } TEST(AtomMatchesCharTest, Escaped_d) { EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a')); EXPECT_FALSE(AtomMatchesChar(true, 'd', '.')); EXPECT_TRUE(AtomMatchesChar(true, 'd', '0')); EXPECT_TRUE(AtomMatchesChar(true, 'd', '9')); } TEST(AtomMatchesCharTest, Escaped_D) { EXPECT_FALSE(AtomMatchesChar(true, 'D', '0')); EXPECT_FALSE(AtomMatchesChar(true, 'D', '9')); EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0')); EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a')); EXPECT_TRUE(AtomMatchesChar(true, 'D', '-')); } TEST(AtomMatchesCharTest, Escaped_s) { EXPECT_FALSE(AtomMatchesChar(true, 's', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 's', 'a')); EXPECT_FALSE(AtomMatchesChar(true, 's', '.')); EXPECT_FALSE(AtomMatchesChar(true, 's', '9')); EXPECT_TRUE(AtomMatchesChar(true, 's', ' ')); EXPECT_TRUE(AtomMatchesChar(true, 's', '\n')); EXPECT_TRUE(AtomMatchesChar(true, 's', '\t')); } TEST(AtomMatchesCharTest, Escaped_S) { EXPECT_FALSE(AtomMatchesChar(true, 'S', ' ')); EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r')); EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0')); EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a')); EXPECT_TRUE(AtomMatchesChar(true, 'S', '9')); } TEST(AtomMatchesCharTest, Escaped_w) { EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'w', '+')); EXPECT_FALSE(AtomMatchesChar(true, 'w', ' ')); EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n')); EXPECT_TRUE(AtomMatchesChar(true, 'w', '0')); EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b')); EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C')); EXPECT_TRUE(AtomMatchesChar(true, 'w', '_')); } TEST(AtomMatchesCharTest, Escaped_W) { EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A')); EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b')); EXPECT_FALSE(AtomMatchesChar(true, 'W', '9')); EXPECT_FALSE(AtomMatchesChar(true, 'W', '_')); EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0')); EXPECT_TRUE(AtomMatchesChar(true, 'W', '*')); EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n')); } TEST(AtomMatchesCharTest, EscapedWhiteSpace) { EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n')); EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r')); EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a')); EXPECT_FALSE(AtomMatchesChar(true, 't', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 't', 't')); EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0')); EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f')); EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f')); EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n')); EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r')); EXPECT_TRUE(AtomMatchesChar(true, 't', '\t')); EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v')); } TEST(AtomMatchesCharTest, UnescapedDot) { EXPECT_FALSE(AtomMatchesChar(false, '.', '\n')); EXPECT_TRUE(AtomMatchesChar(false, '.', '\0')); EXPECT_TRUE(AtomMatchesChar(false, '.', '.')); EXPECT_TRUE(AtomMatchesChar(false, '.', 'a')); EXPECT_TRUE(AtomMatchesChar(false, '.', ' ')); } TEST(AtomMatchesCharTest, UnescapedChar) { EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0')); EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b')); EXPECT_FALSE(AtomMatchesChar(false, '$', 'a')); EXPECT_TRUE(AtomMatchesChar(false, '$', '$')); EXPECT_TRUE(AtomMatchesChar(false, '5', '5')); EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z')); } TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) { EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)), "NULL is not a valid simple regular expression"); EXPECT_NONFATAL_FAILURE( ASSERT_FALSE(ValidateRegex("a\\")), "Syntax error at index 1 in simple regular expression \"a\\\": "); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")), "'\\' cannot appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")), "'\\' cannot appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")), "invalid escape sequence \"\\h\""); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")), "'^' can only appear at the beginning"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")), "'^' can only appear at the beginning"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")), "'$' can only appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")), "'$' can only appear at the end"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")), "'(' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")), "')' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")), "'[' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")), "'{' is unsupported"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")), "'?' can only follow a repeatable token"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")), "'*' can only follow a repeatable token"); EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")), "'+' can only follow a repeatable token"); } TEST(ValidateRegexTest, ReturnsTrueForValid) { EXPECT_TRUE(ValidateRegex("")); EXPECT_TRUE(ValidateRegex("a")); EXPECT_TRUE(ValidateRegex(".*")); EXPECT_TRUE(ValidateRegex("^a_+")); EXPECT_TRUE(ValidateRegex("^a\\t\\&?")); EXPECT_TRUE(ValidateRegex("09*$")); EXPECT_TRUE(ValidateRegex("^Z$")); EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}")); } TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) { EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba")); // Repeating more than once. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab")); // Repeating zero times. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba")); // Repeating once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab")); EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##")); } TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) { EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab")); // Repeating zero times. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc")); // Repeating once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc")); // Repeating more than once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g")); } TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) { EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab")); // Repeating zero times. EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc")); // Repeating once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc")); // Repeating more than once. EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g")); } TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) { EXPECT_TRUE(MatchRegexAtHead("", "")); EXPECT_TRUE(MatchRegexAtHead("", "ab")); } TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) { EXPECT_FALSE(MatchRegexAtHead("$", "a")); EXPECT_TRUE(MatchRegexAtHead("$", "")); EXPECT_TRUE(MatchRegexAtHead("a$", "a")); } TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) { EXPECT_FALSE(MatchRegexAtHead("\\w", "+")); EXPECT_FALSE(MatchRegexAtHead("\\W", "ab")); EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab")); EXPECT_TRUE(MatchRegexAtHead("\\d", "1a")); } TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) { EXPECT_FALSE(MatchRegexAtHead(".+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("a?b", "aab")); EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab")); EXPECT_TRUE(MatchRegexAtHead("a?b", "b")); EXPECT_TRUE(MatchRegexAtHead("a?b", "ab")); } TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) { EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc")); EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b")); EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab")); EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b")); EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b")); EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b")); } TEST(MatchRegexAtHeadTest, MatchesSequentially) { EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc")); EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc")); } TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) { EXPECT_FALSE(MatchRegexAnywhere("", NULL)); } TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) { EXPECT_FALSE(MatchRegexAnywhere("^a", "ba")); EXPECT_FALSE(MatchRegexAnywhere("^$", "a")); EXPECT_TRUE(MatchRegexAnywhere("^a", "ab")); EXPECT_TRUE(MatchRegexAnywhere("^", "ab")); EXPECT_TRUE(MatchRegexAnywhere("^$", "")); } TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) { EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123")); EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888")); } TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) { EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5")); EXPECT_TRUE(MatchRegexAnywhere(".*=", "=")); EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc")); } TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) { EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5")); EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...=")); } // Tests RE's implicit constructors. TEST(RETest, ImplicitConstructorWorks) { const RE empty(""); EXPECT_STREQ("", empty.pattern()); const RE simple("hello"); EXPECT_STREQ("hello", simple.pattern()); } // Tests that RE's constructors reject invalid regular expressions. TEST(RETest, RejectsInvalidRegex) { EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); }, "NULL is not a valid simple regular expression"); EXPECT_NONFATAL_FAILURE({ const RE normal(".*(\\w+"); }, "'(' is unsupported"); EXPECT_NONFATAL_FAILURE({ const RE invalid("^?"); }, "'?' can only follow a repeatable token"); } // Tests RE::FullMatch(). TEST(RETest, FullMatchWorks) { const RE empty(""); EXPECT_TRUE(RE::FullMatch("", empty)); EXPECT_FALSE(RE::FullMatch("a", empty)); const RE re1("a"); EXPECT_TRUE(RE::FullMatch("a", re1)); const RE re("a.*z"); EXPECT_TRUE(RE::FullMatch("az", re)); EXPECT_TRUE(RE::FullMatch("axyz", re)); EXPECT_FALSE(RE::FullMatch("baz", re)); EXPECT_FALSE(RE::FullMatch("azy", re)); } // Tests RE::PartialMatch(). TEST(RETest, PartialMatchWorks) { const RE empty(""); EXPECT_TRUE(RE::PartialMatch("", empty)); EXPECT_TRUE(RE::PartialMatch("a", empty)); const RE re("a.*z"); EXPECT_TRUE(RE::PartialMatch("az", re)); EXPECT_TRUE(RE::PartialMatch("axyz", re)); EXPECT_TRUE(RE::PartialMatch("baz", re)); EXPECT_TRUE(RE::PartialMatch("azy", re)); EXPECT_FALSE(RE::PartialMatch("zza", re)); } #endif // GTEST_USES_POSIX_RE #if !GTEST_OS_WINDOWS_MOBILE TEST(CaptureTest, CapturesStdout) { CaptureStdout(); fprintf(stdout, "abc"); EXPECT_STREQ("abc", GetCapturedStdout().c_str()); CaptureStdout(); fprintf(stdout, "def%cghi", '\0'); EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout())); } TEST(CaptureTest, CapturesStderr) { CaptureStderr(); fprintf(stderr, "jkl"); EXPECT_STREQ("jkl", GetCapturedStderr().c_str()); CaptureStderr(); fprintf(stderr, "jkl%cmno", '\0'); EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr())); } // Tests that stdout and stderr capture don't interfere with each other. TEST(CaptureTest, CapturesStdoutAndStderr) { CaptureStdout(); CaptureStderr(); fprintf(stdout, "pqr"); fprintf(stderr, "stu"); EXPECT_STREQ("pqr", GetCapturedStdout().c_str()); EXPECT_STREQ("stu", GetCapturedStderr().c_str()); } TEST(CaptureDeathTest, CannotReenterStdoutCapture) { CaptureStdout(); EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(), "Only one stdout capturer can exist at a time"); GetCapturedStdout(); // We cannot test stderr capturing using death tests as they use it // themselves. } #endif // !GTEST_OS_WINDOWS_MOBILE TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) { ThreadLocal<int> t1; EXPECT_EQ(0, t1.get()); ThreadLocal<void*> t2; EXPECT_TRUE(t2.get() == NULL); } TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) { ThreadLocal<int> t1(123); EXPECT_EQ(123, t1.get()); int i = 0; ThreadLocal<int*> t2(&i); EXPECT_EQ(&i, t2.get()); } class NoDefaultContructor { public: explicit NoDefaultContructor(const char*) {} NoDefaultContructor(const NoDefaultContructor&) {} }; TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) { ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo")); bar.pointer(); } TEST(ThreadLocalTest, GetAndPointerReturnSameValue) { ThreadLocal<std::string> thread_local_string; EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); // Verifies the condition still holds after calling set. thread_local_string.set("foo"); EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get())); } TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) { ThreadLocal<std::string> thread_local_string; const ThreadLocal<std::string>& const_thread_local_string = thread_local_string; EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); thread_local_string.set("foo"); EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer()); } #if GTEST_IS_THREADSAFE void AddTwo(int* param) { *param += 2; } TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) { int i = 40; ThreadWithParam<int*> thread(&AddTwo, &i, NULL); thread.Join(); EXPECT_EQ(42, i); } TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) { // AssertHeld() is flaky only in the presence of multiple threads accessing // the lock. In this case, the test is robust. EXPECT_DEATH_IF_SUPPORTED({ Mutex m; { MutexLock lock(&m); } m.AssertHeld(); }, "thread .*hold"); } TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) { Mutex m; MutexLock lock(&m); m.AssertHeld(); } class AtomicCounterWithMutex { public: explicit AtomicCounterWithMutex(Mutex* mutex) : value_(0), mutex_(mutex), random_(42) {} void Increment() { MutexLock lock(mutex_); int temp = value_; { // We need to put up a memory barrier to prevent reads and writes to // value_ rearranged with the call to SleepMilliseconds when observed // from other threads. #if GTEST_HAS_PTHREAD // On POSIX, locking a mutex puts up a memory barrier. We cannot use // Mutex and MutexLock here or rely on their memory barrier // functionality as we are testing them here. pthread_mutex_t memory_barrier_mutex; GTEST_CHECK_POSIX_SUCCESS_( pthread_mutex_init(&memory_barrier_mutex, NULL)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex)); SleepMilliseconds(random_.Generate(30)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex)); GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex)); #elif GTEST_OS_WINDOWS // On Windows, performing an interlocked access puts up a memory barrier. volatile LONG dummy = 0; ::InterlockedIncrement(&dummy); SleepMilliseconds(random_.Generate(30)); ::InterlockedIncrement(&dummy); #else # error "Memory barrier not implemented on this platform." #endif // GTEST_HAS_PTHREAD } value_ = temp + 1; } int value() const { return value_; } private: volatile int value_; Mutex* const mutex_; // Protects value_. Random random_; }; void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) { for (int i = 0; i < param.second; ++i) param.first->Increment(); } // Tests that the mutex only lets one thread at a time to lock it. TEST(MutexTest, OnlyOneThreadCanLockAtATime) { Mutex mutex; AtomicCounterWithMutex locked_counter(&mutex); typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType; const int kCycleCount = 20; const int kThreadCount = 7; scoped_ptr<ThreadType> counting_threads[kThreadCount]; Notification threads_can_start; // Creates and runs kThreadCount threads that increment locked_counter // kCycleCount times each. for (int i = 0; i < kThreadCount; ++i) { counting_threads[i].reset(new ThreadType(&CountingThreadFunc, make_pair(&locked_counter, kCycleCount), &threads_can_start)); } threads_can_start.Notify(); for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join(); // If the mutex lets more than one thread to increment the counter at a // time, they are likely to encounter a race condition and have some // increments overwritten, resulting in the lower then expected counter // value. EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value()); } template <typename T> void RunFromThread(void (func)(T), T param) { ThreadWithParam<T> thread(func, param, NULL); thread.Join(); } void RetrieveThreadLocalValue( pair<ThreadLocal<std::string>*, std::string*> param) { *param.second = param.first->get(); } TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) { ThreadLocal<std::string> thread_local_string("foo"); EXPECT_STREQ("foo", thread_local_string.get().c_str()); thread_local_string.set("bar"); EXPECT_STREQ("bar", thread_local_string.get().c_str()); std::string result; RunFromThread(&RetrieveThreadLocalValue, make_pair(&thread_local_string, &result)); EXPECT_STREQ("foo", result.c_str()); } // Keeps track of whether of destructors being called on instances of // DestructorTracker. On Windows, waits for the destructor call reports. class DestructorCall { public: DestructorCall() { invoked_ = false; #if GTEST_OS_WINDOWS wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL)); GTEST_CHECK_(wait_event_.Get() != NULL); #endif } bool CheckDestroyed() const { #if GTEST_OS_WINDOWS if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0) return false; #endif return invoked_; } void ReportDestroyed() { invoked_ = true; #if GTEST_OS_WINDOWS ::SetEvent(wait_event_.Get()); #endif } static std::vector<DestructorCall*>& List() { return *list_; } static void ResetList() { for (size_t i = 0; i < list_->size(); ++i) { delete list_->at(i); } list_->clear(); } private: bool invoked_; #if GTEST_OS_WINDOWS AutoHandle wait_event_; #endif static std::vector<DestructorCall*>* const list_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DestructorCall); }; std::vector<DestructorCall*>* const DestructorCall::list_ = new std::vector<DestructorCall*>; // DestructorTracker keeps track of whether its instances have been // destroyed. class DestructorTracker { public: DestructorTracker() : index_(GetNewIndex()) {} DestructorTracker(const DestructorTracker& /* rhs */) : index_(GetNewIndex()) {} ~DestructorTracker() { // We never access DestructorCall::List() concurrently, so we don't need - // to protect this acccess with a mutex. + // to protect this access with a mutex. DestructorCall::List()[index_]->ReportDestroyed(); } private: static size_t GetNewIndex() { DestructorCall::List().push_back(new DestructorCall); return DestructorCall::List().size() - 1; } const size_t index_; GTEST_DISALLOW_ASSIGN_(DestructorTracker); }; typedef ThreadLocal<DestructorTracker>* ThreadParam; void CallThreadLocalGet(ThreadParam thread_local_param) { thread_local_param->get(); } // Tests that when a ThreadLocal object dies in a thread, it destroys // the managed object for that thread. TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) { DestructorCall::ResetList(); { ThreadLocal<DestructorTracker> thread_local_tracker; ASSERT_EQ(0U, DestructorCall::List().size()); // This creates another DestructorTracker object for the main thread. thread_local_tracker.get(); ASSERT_EQ(1U, DestructorCall::List().size()); ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed()); } // Now thread_local_tracker has died. ASSERT_EQ(1U, DestructorCall::List().size()); EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); DestructorCall::ResetList(); } // Tests that when a thread exits, the thread-local object for that // thread is destroyed. TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) { DestructorCall::ResetList(); { ThreadLocal<DestructorTracker> thread_local_tracker; ASSERT_EQ(0U, DestructorCall::List().size()); // This creates another DestructorTracker object in the new thread. ThreadWithParam<ThreadParam> thread( &CallThreadLocalGet, &thread_local_tracker, NULL); thread.Join(); // The thread has exited, and we should have a DestroyedTracker // instance created for it. But it may not have been destroyed yet. ASSERT_EQ(1U, DestructorCall::List().size()); } // The thread has exited and thread_local_tracker has died. ASSERT_EQ(1U, DestructorCall::List().size()); EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed()); DestructorCall::ResetList(); } TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) { ThreadLocal<std::string> thread_local_string; thread_local_string.set("Foo"); EXPECT_STREQ("Foo", thread_local_string.get().c_str()); std::string result; RunFromThread(&RetrieveThreadLocalValue, make_pair(&thread_local_string, &result)); EXPECT_TRUE(result.empty()); } #endif // GTEST_IS_THREADSAFE #if GTEST_OS_WINDOWS TEST(WindowsTypesTest, HANDLEIsVoidStar) { StaticAssertTypeEq<HANDLE, void*>(); } #if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) TEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) { StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>(); } #else TEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) { StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>(); } #endif #endif // GTEST_OS_WINDOWS } // namespace internal } // namespace testing diff --git a/googletest/test/gtest_test_utils.py b/googletest/test/gtest_test_utils.py index 4acd36c9..d2b6748d 100755 --- a/googletest/test/gtest_test_utils.py +++ b/googletest/test/gtest_test_utils.py @@ -1,320 +1,320 @@ #!/usr/bin/env python # # Copyright 2006, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit test utilities for Google C++ Testing Framework.""" __author__ = 'wan@google.com (Zhanyong Wan)' import atexit import os import shutil import sys import tempfile import unittest _test_module = unittest # Suppresses the 'Import not at the top of the file' lint complaint. # pylint: disable-msg=C6204 try: import subprocess _SUBPROCESS_MODULE_AVAILABLE = True except: import popen2 _SUBPROCESS_MODULE_AVAILABLE = False # pylint: enable-msg=C6204 GTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT' IS_WINDOWS = os.name == 'nt' IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0] # The environment variable for specifying the path to the premature-exit file. PREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE' environ = os.environ.copy() def SetEnvVar(env_var, value): """Sets/unsets an environment variable to a given value.""" if value is not None: environ[env_var] = value elif env_var in environ: del environ[env_var] # Here we expose a class from a particular module, depending on the # environment. The comment suppresses the 'Invalid variable name' lint # complaint. TestCase = _test_module.TestCase # pylint: disable-msg=C6409 # Initially maps a flag to its default value. After # _ParseAndStripGTestFlags() is called, maps a flag to its actual value. _flag_map = {'source_dir': os.path.dirname(sys.argv[0]), 'build_dir': os.path.dirname(sys.argv[0])} _gtest_flags_are_parsed = False def _ParseAndStripGTestFlags(argv): """Parses and strips Google Test flags from argv. This is idempotent.""" # Suppresses the lint complaint about a global variable since we need it # here to maintain module-wide state. global _gtest_flags_are_parsed # pylint: disable-msg=W0603 if _gtest_flags_are_parsed: return _gtest_flags_are_parsed = True for flag in _flag_map: # The environment variable overrides the default value. if flag.upper() in os.environ: _flag_map[flag] = os.environ[flag.upper()] # The command line flag overrides the environment variable. i = 1 # Skips the program name. while i < len(argv): prefix = '--' + flag + '=' if argv[i].startswith(prefix): _flag_map[flag] = argv[i][len(prefix):] del argv[i] break else: # We don't increment i in case we just found a --gtest_* flag # and removed it from argv. i += 1 def GetFlag(flag): """Returns the value of the given flag.""" # In case GetFlag() is called before Main(), we always call # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags # are parsed. _ParseAndStripGTestFlags(sys.argv) return _flag_map[flag] def GetSourceDir(): """Returns the absolute path of the directory where the .py files are.""" return os.path.abspath(GetFlag('source_dir')) def GetBuildDir(): """Returns the absolute path of the directory where the test binaries are.""" return os.path.abspath(GetFlag('build_dir')) _temp_dir = None def _RemoveTempDir(): if _temp_dir: shutil.rmtree(_temp_dir, ignore_errors=True) atexit.register(_RemoveTempDir) def GetTempDir(): """Returns a directory for temporary files.""" global _temp_dir if not _temp_dir: _temp_dir = tempfile.mkdtemp() return _temp_dir def GetTestExecutablePath(executable_name, build_dir=None): """Returns the absolute path of the test binary given its name. The function will print a message and abort the program if the resulting file doesn't exist. Args: executable_name: name of the test binary that the test script runs. build_dir: directory where to look for executables, by default the result of GetBuildDir(). Returns: The absolute path of the test binary. """ path = os.path.abspath(os.path.join(build_dir or GetBuildDir(), executable_name)) if (IS_WINDOWS or IS_CYGWIN) and not path.endswith('.exe'): path += '.exe' if not os.path.exists(path): message = ( 'Unable to find the test binary "%s". Please make sure to provide\n' 'a path to the binary via the --build_dir flag or the BUILD_DIR\n' 'environment variable.' % path) sys.stdout.write(message) sys.exit(1) return path def GetExitStatus(exit_code): """Returns the argument to exit(), or -1 if exit() wasn't called. Args: exit_code: the result value of os.system(command). """ if os.name == 'nt': # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns # the argument to exit() directly. return exit_code else: # On Unix, os.WEXITSTATUS() must be used to extract the exit status # from the result of os.system(). if os.WIFEXITED(exit_code): return os.WEXITSTATUS(exit_code) else: return -1 class Subprocess: def __init__(self, command, working_dir=None, capture_stderr=True, env=None): """Changes into a specified directory, if provided, and executes a command. Restores the old directory afterwards. Args: command: The command to run, in the form of sys.argv. working_dir: The directory to change into. capture_stderr: Determines whether to capture stderr in the output member or to discard it. env: Dictionary with environment to pass to the subprocess. Returns: An object that represents outcome of the executed process. It has the following attributes: terminated_by_signal True iff the child process has been terminated by a signal. signal Sygnal that terminated the child process. exited True iff the child process exited normally. exit_code The code with which the child process exited. output Child process's stdout and stderr output combined in a string. """ # The subprocess module is the preferrable way of running programs # since it is available and behaves consistently on all platforms, # including Windows. But it is only available starting in python 2.4. # In earlier python versions, we revert to the popen2 module, which is # available in python 2.0 and later but doesn't provide required # functionality (Popen4) under Windows. This allows us to support Mac # OS X 10.4 Tiger, which has python 2.3 installed. if _SUBPROCESS_MODULE_AVAILABLE: if capture_stderr: stderr = subprocess.STDOUT else: stderr = subprocess.PIPE p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=stderr, cwd=working_dir, universal_newlines=True, env=env) - # communicate returns a tuple with the file obect for the child's + # communicate returns a tuple with the file object for the child's # output. self.output = p.communicate()[0] self._return_code = p.returncode else: old_dir = os.getcwd() def _ReplaceEnvDict(dest, src): # Changes made by os.environ.clear are not inheritable by child # processes until Python 2.6. To produce inheritable changes we have # to delete environment items with the del statement. for key in dest.keys(): del dest[key] dest.update(src) # When 'env' is not None, backup the environment variables and replace # them with the passed 'env'. When 'env' is None, we simply use the # current 'os.environ' for compatibility with the subprocess.Popen # semantics used above. if env is not None: old_environ = os.environ.copy() _ReplaceEnvDict(os.environ, env) try: if working_dir is not None: os.chdir(working_dir) if capture_stderr: p = popen2.Popen4(command) else: p = popen2.Popen3(command) p.tochild.close() self.output = p.fromchild.read() ret_code = p.wait() finally: os.chdir(old_dir) # Restore the old environment variables # if they were replaced. if env is not None: _ReplaceEnvDict(os.environ, old_environ) # Converts ret_code to match the semantics of # subprocess.Popen.returncode. if os.WIFSIGNALED(ret_code): self._return_code = -os.WTERMSIG(ret_code) else: # os.WIFEXITED(ret_code) should return True here. self._return_code = os.WEXITSTATUS(ret_code) if self._return_code < 0: self.terminated_by_signal = True self.exited = False self.signal = -self._return_code else: self.terminated_by_signal = False self.exited = True self.exit_code = self._return_code def Main(): """Runs the unit test.""" # We must call _ParseAndStripGTestFlags() before calling # unittest.main(). Otherwise the latter will be confused by the # --gtest_* flags. _ParseAndStripGTestFlags(sys.argv) # The tested binaries should not be writing XML output files unless the # script explicitly instructs them to. # TODO(vladl@google.com): Move this into Subprocess when we implement # passing environment into it as a parameter. if GTEST_OUTPUT_VAR_NAME in os.environ: del os.environ[GTEST_OUTPUT_VAR_NAME] _test_module.main() diff --git a/googletest/test/gtest_unittest.cc b/googletest/test/gtest_unittest.cc index 7627b880..1d3c7c7a 100644 --- a/googletest/test/gtest_unittest.cc +++ b/googletest/test/gtest_unittest.cc @@ -1,7705 +1,7705 @@ // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // Tests for Google Test itself. This verifies that the basic constructs of // Google Test work. #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 #includes. TEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) { bool dummy = testing::GTEST_FLAG(also_run_disabled_tests) || testing::GTEST_FLAG(break_on_failure) || testing::GTEST_FLAG(catch_exceptions) || testing::GTEST_FLAG(color) != "unknown" || testing::GTEST_FLAG(filter) != "unknown" || testing::GTEST_FLAG(list_tests) || testing::GTEST_FLAG(output) != "unknown" || testing::GTEST_FLAG(print_time) || testing::GTEST_FLAG(random_seed) || testing::GTEST_FLAG(repeat) > 0 || testing::GTEST_FLAG(show_internal_stack_frames) || testing::GTEST_FLAG(shuffle) || testing::GTEST_FLAG(stack_trace_depth) > 0 || testing::GTEST_FLAG(stream_result_to) != "unknown" || testing::GTEST_FLAG(throw_on_failure); EXPECT_TRUE(dummy || !dummy); // Suppresses warning that dummy is unused. } #include <limits.h> // For INT_MAX. #include <stdlib.h> #include <string.h> #include <time.h> #include <map> #include <vector> #include <ostream> #include "gtest/gtest-spi.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ namespace testing { namespace internal { #if GTEST_CAN_STREAM_RESULTS_ class StreamingListenerTest : public Test { public: class FakeSocketWriter : public StreamingListener::AbstractSocketWriter { public: // Sends a string to the socket. virtual void Send(const std::string& message) { output_ += message; } std::string output_; }; StreamingListenerTest() : fake_sock_writer_(new FakeSocketWriter), streamer_(fake_sock_writer_), test_info_obj_("FooTest", "Bar", NULL, NULL, CodeLocation(__FILE__, __LINE__), 0, NULL) {} protected: std::string* output() { return &(fake_sock_writer_->output_); } FakeSocketWriter* const fake_sock_writer_; StreamingListener streamer_; UnitTest unit_test_; TestInfo test_info_obj_; // The name test_info_ was taken by testing::Test. }; TEST_F(StreamingListenerTest, OnTestProgramEnd) { *output() = ""; streamer_.OnTestProgramEnd(unit_test_); EXPECT_EQ("event=TestProgramEnd&passed=1\n", *output()); } TEST_F(StreamingListenerTest, OnTestIterationEnd) { *output() = ""; streamer_.OnTestIterationEnd(unit_test_, 42); EXPECT_EQ("event=TestIterationEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestCaseStart) { *output() = ""; streamer_.OnTestCaseStart(TestCase("FooTest", "Bar", NULL, NULL)); EXPECT_EQ("event=TestCaseStart&name=FooTest\n", *output()); } TEST_F(StreamingListenerTest, OnTestCaseEnd) { *output() = ""; streamer_.OnTestCaseEnd(TestCase("FooTest", "Bar", NULL, NULL)); EXPECT_EQ("event=TestCaseEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestStart) { *output() = ""; streamer_.OnTestStart(test_info_obj_); EXPECT_EQ("event=TestStart&name=Bar\n", *output()); } TEST_F(StreamingListenerTest, OnTestEnd) { *output() = ""; streamer_.OnTestEnd(test_info_obj_); EXPECT_EQ("event=TestEnd&passed=1&elapsed_time=0ms\n", *output()); } TEST_F(StreamingListenerTest, OnTestPartResult) { *output() = ""; streamer_.OnTestPartResult(TestPartResult( TestPartResult::kFatalFailure, "foo.cc", 42, "failed=\n&%")); // Meta characters in the failure message should be properly escaped. EXPECT_EQ( "event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\n", *output()); } #endif // GTEST_CAN_STREAM_RESULTS_ // Provides access to otherwise private parts of the TestEventListeners class // that are needed to test it. class TestEventListenersAccessor { public: static TestEventListener* GetRepeater(TestEventListeners* listeners) { return listeners->repeater(); } static void SetDefaultResultPrinter(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultResultPrinter(listener); } static void SetDefaultXmlGenerator(TestEventListeners* listeners, TestEventListener* listener) { listeners->SetDefaultXmlGenerator(listener); } static bool EventForwardingEnabled(const TestEventListeners& listeners) { return listeners.EventForwardingEnabled(); } static void SuppressEventForwarding(TestEventListeners* listeners) { listeners->SuppressEventForwarding(); } }; class UnitTestRecordPropertyTestHelper : public Test { protected: UnitTestRecordPropertyTestHelper() {} // Forwards to UnitTest::RecordProperty() to bypass access controls. void UnitTestRecordProperty(const char* key, const std::string& value) { unit_test_.RecordProperty(key, value); } UnitTest unit_test_; }; } // namespace internal } // namespace testing using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; using testing::DoubleLE; using testing::EmptyTestEventListener; using testing::Environment; using testing::FloatLE; using testing::GTEST_FLAG(also_run_disabled_tests); using testing::GTEST_FLAG(break_on_failure); using testing::GTEST_FLAG(catch_exceptions); using testing::GTEST_FLAG(color); using testing::GTEST_FLAG(death_test_use_fork); using testing::GTEST_FLAG(filter); using testing::GTEST_FLAG(list_tests); using testing::GTEST_FLAG(output); using testing::GTEST_FLAG(print_time); using testing::GTEST_FLAG(random_seed); using testing::GTEST_FLAG(repeat); using testing::GTEST_FLAG(show_internal_stack_frames); using testing::GTEST_FLAG(shuffle); using testing::GTEST_FLAG(stack_trace_depth); using testing::GTEST_FLAG(stream_result_to); using testing::GTEST_FLAG(throw_on_failure); using testing::IsNotSubstring; using testing::IsSubstring; using testing::Message; using testing::ScopedFakeTestPartResultReporter; using testing::StaticAssertTypeEq; using testing::Test; using testing::TestCase; using testing::TestEventListeners; using testing::TestInfo; using testing::TestPartResult; using testing::TestPartResultArray; using testing::TestProperty; using testing::TestResult; using testing::TimeInMillis; using testing::UnitTest; using testing::internal::AddReference; using testing::internal::AlwaysFalse; using testing::internal::AlwaysTrue; using testing::internal::AppendUserMessage; using testing::internal::ArrayAwareFind; using testing::internal::ArrayEq; using testing::internal::CodePointToUtf8; using testing::internal::CompileAssertTypesEqual; using testing::internal::CopyArray; using testing::internal::CountIf; using testing::internal::EqFailure; using testing::internal::FloatingPoint; using testing::internal::ForEach; using testing::internal::FormatEpochTimeInMillisAsIso8601; using testing::internal::FormatTimeInMillisAsSeconds; using testing::internal::GTestFlagSaver; using testing::internal::GetCurrentOsStackTraceExceptTop; using testing::internal::GetElementOr; using testing::internal::GetNextRandomSeed; using testing::internal::GetRandomSeedFromFlag; using testing::internal::GetTestTypeId; using testing::internal::GetTimeInMillis; using testing::internal::GetTypeId; using testing::internal::GetUnitTestImpl; using testing::internal::ImplicitlyConvertible; using testing::internal::Int32; using testing::internal::Int32FromEnvOrDie; using testing::internal::IsAProtocolMessage; using testing::internal::IsContainer; using testing::internal::IsContainerTest; using testing::internal::IsNotContainer; using testing::internal::NativeArray; using testing::internal::ParseInt32Flag; using testing::internal::RelationToSourceCopy; using testing::internal::RelationToSourceReference; using testing::internal::RemoveConst; using testing::internal::RemoveReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; using testing::internal::Shuffle; using testing::internal::ShuffleRange; using testing::internal::SkipPrefix; using testing::internal::StreamableToString; using testing::internal::String; using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; using testing::internal::UInt32; using testing::internal::WideStringToUtf8; using testing::internal::edit_distance::CalculateOptimalEdits; using testing::internal::edit_distance::CreateUnifiedDiff; using testing::internal::edit_distance::EditType; using testing::internal::kMaxRandomSeed; using testing::internal::kTestTypeIdInGoogleTest; using testing::kMaxStackTraceDepth; #if GTEST_HAS_STREAM_REDIRECTION using testing::internal::CaptureStdout; using testing::internal::GetCapturedStdout; #endif #if GTEST_IS_THREADSAFE using testing::internal::ThreadWithParam; #endif class TestingVector : public std::vector<int> { }; ::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) { os << "{ "; for (size_t i = 0; i < vector.size(); i++) { os << vector[i] << " "; } os << "}"; return os; } // This line tests that we can define tests in an unnamed namespace. namespace { TEST(GetRandomSeedFromFlagTest, HandlesZero) { const int seed = GetRandomSeedFromFlag(0); EXPECT_LE(1, seed); EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, PreservesValidSeed) { EXPECT_EQ(1, GetRandomSeedFromFlag(1)); EXPECT_EQ(2, GetRandomSeedFromFlag(2)); EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetRandomSeedFromFlag(kMaxRandomSeed)); } TEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) { const int seed1 = GetRandomSeedFromFlag(-1); EXPECT_LE(1, seed1); EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed)); const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1); EXPECT_LE(1, seed2); EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed)); } TEST(GetNextRandomSeedTest, WorksForValidInput) { EXPECT_EQ(2, GetNextRandomSeed(1)); EXPECT_EQ(3, GetNextRandomSeed(2)); EXPECT_EQ(static_cast<int>(kMaxRandomSeed), GetNextRandomSeed(kMaxRandomSeed - 1)); EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed)); // We deliberately don't test GetNextRandomSeed() with invalid // inputs, as that requires death tests, which are expensive. This // is fine as GetNextRandomSeed() is internal and has a // straightforward definition. } static void ClearCurrentTestPartResults() { TestResultAccessor::ClearTestPartResults( GetUnitTestImpl()->current_test_result()); } // Tests GetTypeId. TEST(GetTypeIdTest, ReturnsSameValueForSameType) { EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>()); EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>()); } class SubClassOfTest : public Test {}; class AnotherSubClassOfTest : public Test {}; TEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) { EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>()); EXPECT_NE(GetTypeId<int>(), GetTypeId<char>()); EXPECT_NE(GetTypeId<int>(), GetTestTypeId()); EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId()); EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>()); } // Verifies that GetTestTypeId() returns the same value, no matter it // is called from inside Google Test or outside of it. TEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) { EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId()); } // Tests FormatTimeInMillisAsSeconds(). TEST(FormatTimeInMillisAsSecondsTest, FormatsZero) { EXPECT_EQ("0", FormatTimeInMillisAsSeconds(0)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) { EXPECT_EQ("0.003", FormatTimeInMillisAsSeconds(3)); EXPECT_EQ("0.01", FormatTimeInMillisAsSeconds(10)); EXPECT_EQ("0.2", FormatTimeInMillisAsSeconds(200)); EXPECT_EQ("1.2", FormatTimeInMillisAsSeconds(1200)); EXPECT_EQ("3", FormatTimeInMillisAsSeconds(3000)); } TEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) { EXPECT_EQ("-0.003", FormatTimeInMillisAsSeconds(-3)); EXPECT_EQ("-0.01", FormatTimeInMillisAsSeconds(-10)); EXPECT_EQ("-0.2", FormatTimeInMillisAsSeconds(-200)); EXPECT_EQ("-1.2", FormatTimeInMillisAsSeconds(-1200)); EXPECT_EQ("-3", FormatTimeInMillisAsSeconds(-3000)); } // Tests FormatEpochTimeInMillisAsIso8601(). The correctness of conversion // for particular dates below was verified in Python using // datetime.datetime.fromutctimestamp(<timetamp>/1000). // FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we // have to set up a particular timezone to obtain predictable results. class FormatEpochTimeInMillisAsIso8601Test : public Test { public: // On Cygwin, GCC doesn't allow unqualified integer literals to exceed // 32 bits, even when 64-bit integer types are available. We have to // force the constants to have a 64-bit type here. static const TimeInMillis kMillisPerSec = 1000; private: virtual void SetUp() { saved_tz_ = NULL; GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* getenv, strdup: deprecated */) if (getenv("TZ")) saved_tz_ = strdup(getenv("TZ")); GTEST_DISABLE_MSC_WARNINGS_POP_() // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use. We // cannot use the local time zone because the function's output depends // on the time zone. SetTimeZone("UTC+00"); } virtual void TearDown() { SetTimeZone(saved_tz_); free(const_cast<char*>(saved_tz_)); saved_tz_ = NULL; } static void SetTimeZone(const char* time_zone) { // tzset() distinguishes between the TZ variable being present and empty // and not being present, so we have to consider the case of time_zone // being NULL. #if _MSC_VER || GTEST_OS_WINDOWS_MINGW // ...Unless it's MSVC, whose standard library's _putenv doesn't // distinguish between an empty and a missing variable. const std::string env_var = std::string("TZ=") + (time_zone ? time_zone : ""); _putenv(env_var.c_str()); GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) tzset(); GTEST_DISABLE_MSC_WARNINGS_POP_() #else if (time_zone) { setenv(("TZ"), time_zone, 1); } else { unsetenv("TZ"); } tzset(); #endif } const char* saved_tz_; }; const TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec; TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) { EXPECT_EQ("2011-10-31T18:52:42", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, MillisecondsDoNotAffectResult) { EXPECT_EQ( "2011-10-31T18:52:42", FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) { EXPECT_EQ("2011-09-03T05:07:02", FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) { EXPECT_EQ("2011-09-28T17:08:22", FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec)); } TEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) { EXPECT_EQ("1970-01-01T00:00:00", FormatEpochTimeInMillisAsIso8601(0)); } #if GTEST_CAN_COMPARE_NULL # ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch # endif // Tests that GTEST_IS_NULL_LITERAL_(x) is true when x is a null // pointer literal. TEST(NullLiteralTest, IsTrueForNullLiterals) { EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(NULL)); EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0)); EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0U)); EXPECT_TRUE(GTEST_IS_NULL_LITERAL_(0L)); } // Tests that GTEST_IS_NULL_LITERAL_(x) is false when x is not a null // pointer literal. TEST(NullLiteralTest, IsFalseForNonNullLiterals) { EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(1)); EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(0.0)); EXPECT_FALSE(GTEST_IS_NULL_LITERAL_('a')); EXPECT_FALSE(GTEST_IS_NULL_LITERAL_(static_cast<void*>(NULL))); } # ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them. # pragma option pop # endif #endif // GTEST_CAN_COMPARE_NULL // // Tests CodePointToUtf8(). // Tests that the NUL character L'\0' is encoded correctly. TEST(CodePointToUtf8Test, CanEncodeNul) { EXPECT_EQ("", CodePointToUtf8(L'\0')); } // Tests that ASCII characters are encoded correctly. TEST(CodePointToUtf8Test, CanEncodeAscii) { EXPECT_EQ("a", CodePointToUtf8(L'a')); EXPECT_EQ("Z", CodePointToUtf8(L'Z')); EXPECT_EQ("&", CodePointToUtf8(L'&')); EXPECT_EQ("\x7F", CodePointToUtf8(L'\x7F')); } // Tests that Unicode code-points that have 8 to 11 bits are encoded // as 110xxxxx 10xxxxxx. TEST(CodePointToUtf8Test, CanEncode8To11Bits) { // 000 1101 0011 => 110-00011 10-010011 EXPECT_EQ("\xC3\x93", CodePointToUtf8(L'\xD3')); // 101 0111 0110 => 110-10101 10-110110 // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints // in wide strings and wide chars. In order to accomodate them, we have to // introduce such character constants as integers. EXPECT_EQ("\xD5\xB6", CodePointToUtf8(static_cast<wchar_t>(0x576))); } // Tests that Unicode code-points that have 12 to 16 bits are encoded // as 1110xxxx 10xxxxxx 10xxxxxx. TEST(CodePointToUtf8Test, CanEncode12To16Bits) { // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 EXPECT_EQ("\xE0\xA3\x93", CodePointToUtf8(static_cast<wchar_t>(0x8D3))); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 EXPECT_EQ("\xEC\x9D\x8D", CodePointToUtf8(static_cast<wchar_t>(0xC74D))); } #if !GTEST_WIDE_STRING_USES_UTF16_ // Tests in this group require a wchar_t to hold > 16 bits, and thus // are skipped on Windows, Cygwin, and Symbian, where a wchar_t is // 16-bit wide. This code may not compile on those systems. // Tests that Unicode code-points that have 17 to 21 bits are encoded // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. TEST(CodePointToUtf8Test, CanEncode17To21Bits) { // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 EXPECT_EQ("\xF0\x90\xA3\x93", CodePointToUtf8(L'\x108D3')); // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000 EXPECT_EQ("\xF0\x90\x90\x80", CodePointToUtf8(L'\x10400')); // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 EXPECT_EQ("\xF4\x88\x98\xB4", CodePointToUtf8(L'\x108634')); } // Tests that encoding an invalid code-point generates the expected result. TEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_EQ("(Invalid Unicode 0x1234ABCD)", CodePointToUtf8(L'\x1234ABCD')); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ // Tests WideStringToUtf8(). // Tests that the NUL character L'\0' is encoded correctly. TEST(WideStringToUtf8Test, CanEncodeNul) { EXPECT_STREQ("", WideStringToUtf8(L"", 0).c_str()); EXPECT_STREQ("", WideStringToUtf8(L"", -1).c_str()); } // Tests that ASCII strings are encoded correctly. TEST(WideStringToUtf8Test, CanEncodeAscii) { EXPECT_STREQ("a", WideStringToUtf8(L"a", 1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", 2).c_str()); EXPECT_STREQ("a", WideStringToUtf8(L"a", -1).c_str()); EXPECT_STREQ("ab", WideStringToUtf8(L"ab", -1).c_str()); } // Tests that Unicode code-points that have 8 to 11 bits are encoded // as 110xxxxx 10xxxxxx. TEST(WideStringToUtf8Test, CanEncode8To11Bits) { // 000 1101 0011 => 110-00011 10-010011 EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", 1).c_str()); EXPECT_STREQ("\xC3\x93", WideStringToUtf8(L"\xD3", -1).c_str()); // 101 0111 0110 => 110-10101 10-110110 const wchar_t s[] = { 0x576, '\0' }; EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, 1).c_str()); EXPECT_STREQ("\xD5\xB6", WideStringToUtf8(s, -1).c_str()); } // Tests that Unicode code-points that have 12 to 16 bits are encoded // as 1110xxxx 10xxxxxx 10xxxxxx. TEST(WideStringToUtf8Test, CanEncode12To16Bits) { // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011 const wchar_t s1[] = { 0x8D3, '\0' }; EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, 1).c_str()); EXPECT_STREQ("\xE0\xA3\x93", WideStringToUtf8(s1, -1).c_str()); // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101 const wchar_t s2[] = { 0xC74D, '\0' }; EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, 1).c_str()); EXPECT_STREQ("\xEC\x9D\x8D", WideStringToUtf8(s2, -1).c_str()); } // Tests that the conversion stops when the function encounters \0 character. TEST(WideStringToUtf8Test, StopsOnNulCharacter) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABC\0XYZ", 100).c_str()); } // Tests that the conversion stops when the function reaches the limit // specified by the 'length' parameter. TEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) { EXPECT_STREQ("ABC", WideStringToUtf8(L"ABCDEF", 3).c_str()); } #if !GTEST_WIDE_STRING_USES_UTF16_ // Tests that Unicode code-points that have 17 to 21 bits are encoded // as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile // on the systems using UTF-16 encoding. TEST(WideStringToUtf8Test, CanEncode17To21Bits) { // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011 EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", 1).c_str()); EXPECT_STREQ("\xF0\x90\xA3\x93", WideStringToUtf8(L"\x108D3", -1).c_str()); // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100 EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", 1).c_str()); EXPECT_STREQ("\xF4\x88\x98\xB4", WideStringToUtf8(L"\x108634", -1).c_str()); } // Tests that encoding an invalid code-point generates the expected result. TEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) { EXPECT_STREQ("(Invalid Unicode 0xABCDFF)", WideStringToUtf8(L"\xABCDFF", -1).c_str()); } #else // !GTEST_WIDE_STRING_USES_UTF16_ // Tests that surrogate pairs are encoded correctly on the systems using // UTF-16 encoding in the wide strings. TEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) { const wchar_t s[] = { 0xD801, 0xDC00, '\0' }; EXPECT_STREQ("\xF0\x90\x90\x80", WideStringToUtf8(s, -1).c_str()); } // Tests that encoding an invalid UTF-16 surrogate pair // generates the expected result. TEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) { // Leading surrogate is at the end of the string. const wchar_t s1[] = { 0xD800, '\0' }; EXPECT_STREQ("\xED\xA0\x80", WideStringToUtf8(s1, -1).c_str()); // Leading surrogate is not followed by the trailing surrogate. const wchar_t s2[] = { 0xD800, 'M', '\0' }; EXPECT_STREQ("\xED\xA0\x80M", WideStringToUtf8(s2, -1).c_str()); // Trailing surrogate appearas without a leading surrogate. const wchar_t s3[] = { 0xDC00, 'P', 'Q', 'R', '\0' }; EXPECT_STREQ("\xED\xB0\x80PQR", WideStringToUtf8(s3, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ // Tests that codepoint concatenation works correctly. #if !GTEST_WIDE_STRING_USES_UTF16_ TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = { 0x108634, 0xC74D, '\n', 0x576, 0x8D3, 0x108634, '\0'}; EXPECT_STREQ( "\xF4\x88\x98\xB4" "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93" "\xF4\x88\x98\xB4", WideStringToUtf8(s, -1).c_str()); } #else TEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) { const wchar_t s[] = { 0xC74D, '\n', 0x576, 0x8D3, '\0'}; EXPECT_STREQ( "\xEC\x9D\x8D" "\n" "\xD5\xB6" "\xE0\xA3\x93", WideStringToUtf8(s, -1).c_str()); } #endif // !GTEST_WIDE_STRING_USES_UTF16_ // Tests the Random class. TEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) { testing::internal::Random random(42); EXPECT_DEATH_IF_SUPPORTED( random.Generate(0), "Cannot generate a number in the range \\[0, 0\\)"); EXPECT_DEATH_IF_SUPPORTED( random.Generate(testing::internal::Random::kMaxRange + 1), "Generation of a number in \\[0, 2147483649\\) was requested, " "but this can only generate numbers in \\[0, 2147483648\\)"); } TEST(RandomTest, GeneratesNumbersWithinRange) { const UInt32 kRange = 10000; testing::internal::Random random(12345); for (int i = 0; i < 10; i++) { EXPECT_LT(random.Generate(kRange), kRange) << " for iteration " << i; } testing::internal::Random random2(testing::internal::Random::kMaxRange); for (int i = 0; i < 10; i++) { EXPECT_LT(random2.Generate(kRange), kRange) << " for iteration " << i; } } TEST(RandomTest, RepeatsWhenReseeded) { const int kSeed = 123; const int kArraySize = 10; const UInt32 kRange = 10000; UInt32 values[kArraySize]; testing::internal::Random random(kSeed); for (int i = 0; i < kArraySize; i++) { values[i] = random.Generate(kRange); } random.Reseed(kSeed); for (int i = 0; i < kArraySize; i++) { EXPECT_EQ(values[i], random.Generate(kRange)) << " for iteration " << i; } } // Tests STL container utilities. // Tests CountIf(). static bool IsPositive(int n) { return n > 0; } TEST(ContainerUtilityTest, CountIf) { std::vector<int> v; EXPECT_EQ(0, CountIf(v, IsPositive)); // Works for an empty container. v.push_back(-1); v.push_back(0); EXPECT_EQ(0, CountIf(v, IsPositive)); // Works when no value satisfies. v.push_back(2); v.push_back(-10); v.push_back(10); EXPECT_EQ(2, CountIf(v, IsPositive)); } // Tests ForEach(). static int g_sum = 0; static void Accumulate(int n) { g_sum += n; } TEST(ContainerUtilityTest, ForEach) { std::vector<int> v; g_sum = 0; ForEach(v, Accumulate); EXPECT_EQ(0, g_sum); // Works for an empty container; g_sum = 0; v.push_back(1); ForEach(v, Accumulate); EXPECT_EQ(1, g_sum); // Works for a container with one element. g_sum = 0; v.push_back(20); v.push_back(300); ForEach(v, Accumulate); EXPECT_EQ(321, g_sum); } // Tests GetElementOr(). TEST(ContainerUtilityTest, GetElementOr) { std::vector<char> a; EXPECT_EQ('x', GetElementOr(a, 0, 'x')); a.push_back('a'); a.push_back('b'); EXPECT_EQ('a', GetElementOr(a, 0, 'x')); EXPECT_EQ('b', GetElementOr(a, 1, 'x')); EXPECT_EQ('x', GetElementOr(a, -2, 'x')); EXPECT_EQ('x', GetElementOr(a, 2, 'x')); } TEST(ContainerUtilityDeathTest, ShuffleRange) { std::vector<int> a; a.push_back(0); a.push_back(1); a.push_back(2); testing::internal::Random random(1); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, -1, 1, &a), "Invalid shuffle range start -1: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 4, 4, &a), "Invalid shuffle range start 4: must be in range \\[0, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 2, &a), "Invalid shuffle range finish 2: must be in range \\[3, 3\\]"); EXPECT_DEATH_IF_SUPPORTED( ShuffleRange(&random, 3, 4, &a), "Invalid shuffle range finish 4: must be in range \\[3, 3\\]"); } class VectorShuffleTest : public Test { protected: static const int kVectorSize = 20; VectorShuffleTest() : random_(1) { for (int i = 0; i < kVectorSize; i++) { vector_.push_back(i); } } static bool VectorIsCorrupt(const TestingVector& vector) { if (kVectorSize != static_cast<int>(vector.size())) { return true; } bool found_in_vector[kVectorSize] = { false }; for (size_t i = 0; i < vector.size(); i++) { const int e = vector[i]; if (e < 0 || e >= kVectorSize || found_in_vector[e]) { return true; } found_in_vector[e] = true; } // Vector size is correct, elements' range is correct, no // duplicate elements. Therefore no corruption has occurred. return false; } static bool VectorIsNotCorrupt(const TestingVector& vector) { return !VectorIsCorrupt(vector); } static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) { for (int i = begin; i < end; i++) { if (i != vector[i]) { return true; } } return false; } static bool RangeIsUnshuffled( const TestingVector& vector, int begin, int end) { return !RangeIsShuffled(vector, begin, end); } static bool VectorIsShuffled(const TestingVector& vector) { return RangeIsShuffled(vector, 0, static_cast<int>(vector.size())); } static bool VectorIsUnshuffled(const TestingVector& vector) { return !VectorIsShuffled(vector); } testing::internal::Random random_; TestingVector vector_; }; // class VectorShuffleTest const int VectorShuffleTest::kVectorSize; TEST_F(VectorShuffleTest, HandlesEmptyRange) { // Tests an empty range at the beginning... ShuffleRange(&random_, 0, 0, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...in the middle... ShuffleRange(&random_, kVectorSize/2, kVectorSize/2, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...at the end... ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...and past the end. ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); } TEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) { // Tests a size one range at the beginning... ShuffleRange(&random_, 0, 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...in the middle... ShuffleRange(&random_, kVectorSize/2, kVectorSize/2 + 1, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); // ...and at the end. ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsUnshuffled, vector_); } // Because we use our own random number generator and a fixed seed, // we can guarantee that the following "random" tests will succeed. TEST_F(VectorShuffleTest, ShufflesEntireVector) { Shuffle(&random_, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_; // Tests the first and last elements in particular to ensure that // there are no off-by-one problems in our shuffle algorithm. EXPECT_NE(0, vector_[0]); EXPECT_NE(kVectorSize - 1, vector_[kVectorSize - 1]); } TEST_F(VectorShuffleTest, ShufflesStartOfVector) { const int kRangeSize = kVectorSize/2; ShuffleRange(&random_, 0, kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize, kVectorSize); } TEST_F(VectorShuffleTest, ShufflesEndOfVector) { const int kRangeSize = kVectorSize / 2; ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, kVectorSize); } TEST_F(VectorShuffleTest, ShufflesMiddleOfVector) { int kRangeSize = kVectorSize/3; ShuffleRange(&random_, kRangeSize, 2*kRangeSize, &vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector_); EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize); EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2*kRangeSize); EXPECT_PRED3(RangeIsUnshuffled, vector_, 2*kRangeSize, kVectorSize); } TEST_F(VectorShuffleTest, ShufflesRepeatably) { TestingVector vector2; for (int i = 0; i < kVectorSize; i++) { vector2.push_back(i); } random_.Reseed(1234); Shuffle(&random_, &vector_); random_.Reseed(1234); Shuffle(&random_, &vector2); ASSERT_PRED1(VectorIsNotCorrupt, vector_); ASSERT_PRED1(VectorIsNotCorrupt, vector2); for (int i = 0; i < kVectorSize; i++) { EXPECT_EQ(vector_[i], vector2[i]) << " where i is " << i; } } // Tests the size of the AssertHelper class. TEST(AssertHelperTest, AssertHelperIsSmall) { // To avoid breaking clients that use lots of assertions in one // function, we cannot grow the size of AssertHelper. EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*)); } // Tests String::EndsWithCaseInsensitive(). TEST(StringTest, EndsWithCaseInsensitive) { EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "BAR")); EXPECT_TRUE(String::EndsWithCaseInsensitive("foobaR", "bar")); EXPECT_TRUE(String::EndsWithCaseInsensitive("foobar", "")); EXPECT_TRUE(String::EndsWithCaseInsensitive("", "")); EXPECT_FALSE(String::EndsWithCaseInsensitive("Foobar", "foo")); EXPECT_FALSE(String::EndsWithCaseInsensitive("foobar", "Foo")); EXPECT_FALSE(String::EndsWithCaseInsensitive("", "foo")); } // C++Builder's preprocessor is buggy; it fails to expand macros that // appear in macro parameters after wide char literals. Provide an alias // for NULL as a workaround. static const wchar_t* const kNull = NULL; // Tests String::CaseInsensitiveWideCStringEquals TEST(StringTest, CaseInsensitiveWideCStringEquals) { EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(NULL, NULL)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"")); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"", kNull)); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L"foobar")); EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L"foobar", kNull)); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"foobar")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"foobar", L"FOOBAR")); EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L"FOOBAR", L"foobar")); } #if GTEST_OS_WINDOWS // Tests String::ShowWideCString(). TEST(StringTest, ShowWideCString) { EXPECT_STREQ("(null)", String::ShowWideCString(NULL).c_str()); EXPECT_STREQ("", String::ShowWideCString(L"").c_str()); EXPECT_STREQ("foo", String::ShowWideCString(L"foo").c_str()); } # if GTEST_OS_WINDOWS_MOBILE TEST(StringTest, AnsiAndUtf16Null) { EXPECT_EQ(NULL, String::AnsiToUtf16(NULL)); EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL)); } TEST(StringTest, AnsiAndUtf16ConvertBasic) { const char* ansi = String::Utf16ToAnsi(L"str"); EXPECT_STREQ("str", ansi); delete [] ansi; const WCHAR* utf16 = String::AnsiToUtf16("str"); EXPECT_EQ(0, wcsncmp(L"str", utf16, 3)); delete [] utf16; } TEST(StringTest, AnsiAndUtf16ConvertPathChars) { const char* ansi = String::Utf16ToAnsi(L".:\\ \"*?"); EXPECT_STREQ(".:\\ \"*?", ansi); delete [] ansi; const WCHAR* utf16 = String::AnsiToUtf16(".:\\ \"*?"); EXPECT_EQ(0, wcsncmp(L".:\\ \"*?", utf16, 3)); delete [] utf16; } # endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS // Tests TestProperty construction. TEST(TestPropertyTest, StringValue) { TestProperty property("key", "1"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("1", property.value()); } // Tests TestProperty replacing a value. TEST(TestPropertyTest, ReplaceStringValue) { TestProperty property("key", "1"); EXPECT_STREQ("1", property.value()); property.SetValue("2"); EXPECT_STREQ("2", property.value()); } // AddFatalFailure() and AddNonfatalFailure() must be stand-alone // functions (i.e. their definitions cannot be inlined at the call // sites), or C++Builder won't compile the code. static void AddFatalFailure() { FAIL() << "Expected fatal failure."; } static void AddNonfatalFailure() { ADD_FAILURE() << "Expected non-fatal failure."; } class ScopedFakeTestPartResultReporterTest : public Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE }; static void AddFailure(FailureMode failure) { if (failure == FATAL_FAILURE) { AddFatalFailure(); } else { AddNonfatalFailure(); } } }; // Tests that ScopedFakeTestPartResultReporter intercepts test // failures. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) { TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter( ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, &results); AddFailure(NONFATAL_FAILURE); AddFailure(FATAL_FAILURE); } EXPECT_EQ(2, results.size()); EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); } TEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) { TestPartResultArray results; { // Tests, that the deprecated constructor still works. ScopedFakeTestPartResultReporter reporter(&results); AddFailure(NONFATAL_FAILURE); } EXPECT_EQ(1, results.size()); } #if GTEST_IS_THREADSAFE class ScopedFakeTestPartResultReporterWithThreadsTest : public ScopedFakeTestPartResultReporterTest { protected: static void AddFailureInOtherThread(FailureMode failure) { ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL); thread.Join(); } }; TEST_F(ScopedFakeTestPartResultReporterWithThreadsTest, InterceptsTestFailuresInAllThreads) { TestPartResultArray results; { ScopedFakeTestPartResultReporter reporter( ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results); AddFailure(NONFATAL_FAILURE); AddFailure(FATAL_FAILURE); AddFailureInOtherThread(NONFATAL_FAILURE); AddFailureInOtherThread(FATAL_FAILURE); } EXPECT_EQ(4, results.size()); EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed()); EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed()); EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed()); } #endif // GTEST_IS_THREADSAFE // Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}. Makes sure that they // work even if the failure is generated in a called function rather than // the current context. typedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest; TEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) { EXPECT_FATAL_FAILURE(AddFatalFailure(), "Expected fatal failure."); } #if GTEST_HAS_GLOBAL_STRING TEST_F(ExpectFatalFailureTest, AcceptsStringObject) { EXPECT_FATAL_FAILURE(AddFatalFailure(), ::string("Expected fatal failure.")); } #endif TEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) { EXPECT_FATAL_FAILURE(AddFatalFailure(), ::std::string("Expected fatal failure.")); } TEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) { // We have another test below to verify that the macro catches fatal // failures generated on another thread. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(), "Expected fatal failure."); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true" # pragma option push -w-ccc #endif // Tests that EXPECT_FATAL_FAILURE() can be used in a non-void // function even when the statement in it contains ASSERT_*. int NonVoidFunction() { EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); return 0; } TEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) { NonVoidFunction(); } // Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the // current function even though 'statement' generates a fatal failure. void DoesNotAbortHelper(bool* aborted) { EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), ""); EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), ""); *aborted = false; } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" suppressed them. # pragma option pop #endif TEST_F(ExpectFatalFailureTest, DoesNotAbort) { bool aborted = true; DoesNotAbortHelper(&aborted); EXPECT_FALSE(aborted); } // Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a // statement that contains a macro which expands to code containing an // unprotected comma. static int global_var = 0; #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE({ GTEST_USE_UNPROTECTED_COMMA_; AddFatalFailure(); }, ""); #endif EXPECT_FATAL_FAILURE_ON_ALL_THREADS({ GTEST_USE_UNPROTECTED_COMMA_; AddFatalFailure(); }, ""); } // Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}. typedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest; TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), "Expected non-fatal failure."); } #if GTEST_HAS_GLOBAL_STRING TEST_F(ExpectNonfatalFailureTest, AcceptsStringObject) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), ::string("Expected non-fatal failure.")); } #endif TEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) { EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), ::std::string("Expected non-fatal failure.")); } TEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) { // We have another test below to verify that the macro catches // non-fatal failures generated on another thread. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(), "Expected non-fatal failure."); } // Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a // statement that contains a macro which expands to code containing an // unprotected comma. TEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { EXPECT_NONFATAL_FAILURE({ GTEST_USE_UNPROTECTED_COMMA_; AddNonfatalFailure(); }, ""); EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS({ GTEST_USE_UNPROTECTED_COMMA_; AddNonfatalFailure(); }, ""); } #if GTEST_IS_THREADSAFE typedef ScopedFakeTestPartResultReporterWithThreadsTest ExpectFailureWithThreadsTest; TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) { EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE), "Expected fatal failure."); } TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) { EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS( AddFailureInOtherThread(NONFATAL_FAILURE), "Expected non-fatal failure."); } #endif // GTEST_IS_THREADSAFE // Tests the TestProperty class. TEST(TestPropertyTest, ConstructorWorks) { const TestProperty property("key", "value"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("value", property.value()); } TEST(TestPropertyTest, SetValue) { TestProperty property("key", "value_1"); EXPECT_STREQ("key", property.key()); property.SetValue("value_2"); EXPECT_STREQ("key", property.key()); EXPECT_STREQ("value_2", property.value()); } // Tests the TestResult class // The test fixture for testing TestResult. class TestResultTest : public Test { protected: typedef std::vector<TestPartResult> TPRVector; // We make use of 2 TestPartResult objects, TestPartResult * pr1, * pr2; // ... and 3 TestResult objects. TestResult * r0, * r1, * r2; virtual void SetUp() { // pr1 is for success. pr1 = new TestPartResult(TestPartResult::kSuccess, "foo/bar.cc", 10, "Success!"); // pr2 is for fatal failure. pr2 = new TestPartResult(TestPartResult::kFatalFailure, "foo/bar.cc", -1, // This line number means "unknown" "Failure!"); // Creates the TestResult objects. r0 = new TestResult(); r1 = new TestResult(); r2 = new TestResult(); // In order to test TestResult, we need to modify its internal // state, in particular the TestPartResult vector it holds. // test_part_results() returns a const reference to this vector. // We cast it to a non-const object s.t. it can be modified (yes, // this is a hack). TPRVector* results1 = const_cast<TPRVector*>( &TestResultAccessor::test_part_results(*r1)); TPRVector* results2 = const_cast<TPRVector*>( &TestResultAccessor::test_part_results(*r2)); // r0 is an empty TestResult. // r1 contains a single SUCCESS TestPartResult. results1->push_back(*pr1); // r2 contains a SUCCESS, and a FAILURE. results2->push_back(*pr1); results2->push_back(*pr2); } virtual void TearDown() { delete pr1; delete pr2; delete r0; delete r1; delete r2; } - // Helper that compares two two TestPartResults. + // Helper that compares two TestPartResults. static void CompareTestPartResult(const TestPartResult& expected, const TestPartResult& actual) { EXPECT_EQ(expected.type(), actual.type()); EXPECT_STREQ(expected.file_name(), actual.file_name()); EXPECT_EQ(expected.line_number(), actual.line_number()); EXPECT_STREQ(expected.summary(), actual.summary()); EXPECT_STREQ(expected.message(), actual.message()); EXPECT_EQ(expected.passed(), actual.passed()); EXPECT_EQ(expected.failed(), actual.failed()); EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed()); EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed()); } }; // Tests TestResult::total_part_count(). TEST_F(TestResultTest, total_part_count) { ASSERT_EQ(0, r0->total_part_count()); ASSERT_EQ(1, r1->total_part_count()); ASSERT_EQ(2, r2->total_part_count()); } // Tests TestResult::Passed(). TEST_F(TestResultTest, Passed) { ASSERT_TRUE(r0->Passed()); ASSERT_TRUE(r1->Passed()); ASSERT_FALSE(r2->Passed()); } // Tests TestResult::Failed(). TEST_F(TestResultTest, Failed) { ASSERT_FALSE(r0->Failed()); ASSERT_FALSE(r1->Failed()); ASSERT_TRUE(r2->Failed()); } // Tests TestResult::GetTestPartResult(). typedef TestResultTest TestResultDeathTest; TEST_F(TestResultDeathTest, GetTestPartResult) { CompareTestPartResult(*pr1, r2->GetTestPartResult(0)); CompareTestPartResult(*pr2, r2->GetTestPartResult(1)); EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), ""); EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), ""); } // Tests TestResult has no properties when none are added. TEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) { TestResult test_result; ASSERT_EQ(0, test_result.test_property_count()); } // Tests TestResult has the expected property when added. TEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) { TestResult test_result; TestProperty property("key_1", "1"); TestResultAccessor::RecordProperty(&test_result, "testcase", property); ASSERT_EQ(1, test_result.test_property_count()); const TestProperty& actual_property = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property.key()); EXPECT_STREQ("1", actual_property.value()); } // Tests TestResult has multiple properties when added. TEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) { TestResult test_result; TestProperty property_1("key_1", "1"); TestProperty property_2("key_2", "2"); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2); ASSERT_EQ(2, test_result.test_property_count()); const TestProperty& actual_property_1 = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property_1.key()); EXPECT_STREQ("1", actual_property_1.value()); const TestProperty& actual_property_2 = test_result.GetTestProperty(1); EXPECT_STREQ("key_2", actual_property_2.key()); EXPECT_STREQ("2", actual_property_2.value()); } // Tests TestResult::RecordProperty() overrides values for duplicate keys. TEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) { TestResult test_result; TestProperty property_1_1("key_1", "1"); TestProperty property_2_1("key_2", "2"); TestProperty property_1_2("key_1", "12"); TestProperty property_2_2("key_2", "22"); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1_2); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2_2); ASSERT_EQ(2, test_result.test_property_count()); const TestProperty& actual_property_1 = test_result.GetTestProperty(0); EXPECT_STREQ("key_1", actual_property_1.key()); EXPECT_STREQ("12", actual_property_1.value()); const TestProperty& actual_property_2 = test_result.GetTestProperty(1); EXPECT_STREQ("key_2", actual_property_2.key()); EXPECT_STREQ("22", actual_property_2.value()); } // Tests TestResult::GetTestProperty(). TEST(TestResultPropertyTest, GetTestProperty) { TestResult test_result; TestProperty property_1("key_1", "1"); TestProperty property_2("key_2", "2"); TestProperty property_3("key_3", "3"); TestResultAccessor::RecordProperty(&test_result, "testcase", property_1); TestResultAccessor::RecordProperty(&test_result, "testcase", property_2); TestResultAccessor::RecordProperty(&test_result, "testcase", property_3); const TestProperty& fetched_property_1 = test_result.GetTestProperty(0); const TestProperty& fetched_property_2 = test_result.GetTestProperty(1); const TestProperty& fetched_property_3 = test_result.GetTestProperty(2); EXPECT_STREQ("key_1", fetched_property_1.key()); EXPECT_STREQ("1", fetched_property_1.value()); EXPECT_STREQ("key_2", fetched_property_2.key()); EXPECT_STREQ("2", fetched_property_2.value()); EXPECT_STREQ("key_3", fetched_property_3.key()); EXPECT_STREQ("3", fetched_property_3.value()); EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), ""); EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), ""); } // Tests the Test class. // // It's difficult to test every public method of this class (we are // already stretching the limit of Google Test by using it to test itself!). // Fortunately, we don't have to do that, as we are already testing // the functionalities of the Test class extensively by using Google Test // alone. // // Therefore, this section only contains one test. // Tests that GTestFlagSaver works on Windows and Mac. class GTestFlagSaverTest : public Test { protected: // Saves the Google Test flags such that we can restore them later, and // then sets them to their default values. This will be called // before the first test in this test case is run. static void SetUpTestCase() { saver_ = new GTestFlagSaver; GTEST_FLAG(also_run_disabled_tests) = false; GTEST_FLAG(break_on_failure) = false; GTEST_FLAG(catch_exceptions) = false; GTEST_FLAG(death_test_use_fork) = false; GTEST_FLAG(color) = "auto"; GTEST_FLAG(filter) = ""; GTEST_FLAG(list_tests) = false; GTEST_FLAG(output) = ""; GTEST_FLAG(print_time) = true; GTEST_FLAG(random_seed) = 0; GTEST_FLAG(repeat) = 1; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG(throw_on_failure) = false; } // Restores the Google Test flags that the tests have modified. This will // be called after the last test in this test case is run. static void TearDownTestCase() { delete saver_; saver_ = NULL; } // Verifies that the Google Test flags have their default values, and then // modifies each of them. void VerifyAndModifyFlags() { EXPECT_FALSE(GTEST_FLAG(also_run_disabled_tests)); EXPECT_FALSE(GTEST_FLAG(break_on_failure)); EXPECT_FALSE(GTEST_FLAG(catch_exceptions)); EXPECT_STREQ("auto", GTEST_FLAG(color).c_str()); EXPECT_FALSE(GTEST_FLAG(death_test_use_fork)); EXPECT_STREQ("", GTEST_FLAG(filter).c_str()); EXPECT_FALSE(GTEST_FLAG(list_tests)); EXPECT_STREQ("", GTEST_FLAG(output).c_str()); EXPECT_TRUE(GTEST_FLAG(print_time)); EXPECT_EQ(0, GTEST_FLAG(random_seed)); EXPECT_EQ(1, GTEST_FLAG(repeat)); EXPECT_FALSE(GTEST_FLAG(shuffle)); EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG(stack_trace_depth)); EXPECT_STREQ("", GTEST_FLAG(stream_result_to).c_str()); EXPECT_FALSE(GTEST_FLAG(throw_on_failure)); GTEST_FLAG(also_run_disabled_tests) = true; GTEST_FLAG(break_on_failure) = true; GTEST_FLAG(catch_exceptions) = true; GTEST_FLAG(color) = "no"; GTEST_FLAG(death_test_use_fork) = true; GTEST_FLAG(filter) = "abc"; GTEST_FLAG(list_tests) = true; GTEST_FLAG(output) = "xml:foo.xml"; GTEST_FLAG(print_time) = false; GTEST_FLAG(random_seed) = 1; GTEST_FLAG(repeat) = 100; GTEST_FLAG(shuffle) = true; GTEST_FLAG(stack_trace_depth) = 1; GTEST_FLAG(stream_result_to) = "localhost:1234"; GTEST_FLAG(throw_on_failure) = true; } private: // For saving Google Test flags during this test case. static GTestFlagSaver* saver_; }; GTestFlagSaver* GTestFlagSaverTest::saver_ = NULL; // Google Test doesn't guarantee the order of tests. The following two // tests are designed to work regardless of their order. // Modifies the Google Test flags in the test body. TEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); } // Verifies that the Google Test flags in the body of the previous test were // restored to their original values. TEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); } // Sets an environment variable with the given name to the given // value. If the value argument is "", unsets the environment // variable. The caller must ensure that both arguments are not NULL. static void SetEnv(const char* name, const char* value) { #if GTEST_OS_WINDOWS_MOBILE // Environment variables are not supported on Windows CE. return; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // C++Builder's putenv only stores a pointer to its parameter; we have to // ensure that the string remains valid as long as it might be needed. // We use an std::map to do so. static std::map<std::string, std::string*> added_env; // Because putenv stores a pointer to the string buffer, we can't delete the // previous string (if present) until after it's replaced. std::string *prev_env = NULL; if (added_env.find(name) != added_env.end()) { prev_env = added_env[name]; } added_env[name] = new std::string( (Message() << name << "=" << value).GetString()); // The standard signature of putenv accepts a 'char*' argument. Other // implementations, like C++Builder's, accept a 'const char*'. // We cast away the 'const' since that would work for both variants. putenv(const_cast<char*>(added_env[name]->c_str())); delete prev_env; #elif GTEST_OS_WINDOWS // If we are on Windows proper. _putenv((Message() << name << "=" << value).GetString().c_str()); #else if (*value == '\0') { unsetenv(name); } else { setenv(name, value, 1); } #endif // GTEST_OS_WINDOWS_MOBILE } #if !GTEST_OS_WINDOWS_MOBILE // Environment variables are not supported on Windows CE. using testing::internal::Int32FromGTestEnv; // Tests Int32FromGTestEnv(). // Tests that Int32FromGTestEnv() returns the default value when the // environment variable is not set. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", ""); EXPECT_EQ(10, Int32FromGTestEnv("temp", 10)); } # if !defined(GTEST_GET_INT32_FROM_ENV_) // Tests that Int32FromGTestEnv() returns the default value when the // environment variable overflows as an Int32. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12345678987654321"); EXPECT_EQ(20, Int32FromGTestEnv("temp", 20)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-12345678987654321"); EXPECT_EQ(30, Int32FromGTestEnv("temp", 30)); } // Tests that Int32FromGTestEnv() returns the default value when the // environment variable does not represent a valid decimal integer. TEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "A1"); EXPECT_EQ(40, Int32FromGTestEnv("temp", 40)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "12X"); EXPECT_EQ(50, Int32FromGTestEnv("temp", 50)); } # endif // !defined(GTEST_GET_INT32_FROM_ENV_) // Tests that Int32FromGTestEnv() parses and returns the value of the // environment variable when it represents a valid decimal integer in // the range of an Int32. TEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "123"); EXPECT_EQ(123, Int32FromGTestEnv("temp", 0)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "TEMP", "-321"); EXPECT_EQ(-321, Int32FromGTestEnv("temp", 0)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests ParseInt32Flag(). // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag has wrong format TEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) { Int32 value = 123; EXPECT_FALSE(ParseInt32Flag("--a=100", "b", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseInt32Flag("a=100", "a", &value)); EXPECT_EQ(123, value); } // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag overflows as an Int32. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) { printf("(expecting 2 warnings)\n"); Int32 value = 123; EXPECT_FALSE(ParseInt32Flag("--abc=12345678987654321", "abc", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseInt32Flag("--abc=-12345678987654321", "abc", &value)); EXPECT_EQ(123, value); } // Tests that ParseInt32Flag() returns false and doesn't change the // output value when the flag does not represent a valid decimal // integer. TEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) { printf("(expecting 2 warnings)\n"); Int32 value = 123; EXPECT_FALSE(ParseInt32Flag("--abc=A1", "abc", &value)); EXPECT_EQ(123, value); EXPECT_FALSE(ParseInt32Flag("--abc=12X", "abc", &value)); EXPECT_EQ(123, value); } // Tests that ParseInt32Flag() parses the value of the flag and // returns true when the flag represents a valid decimal integer in // the range of an Int32. TEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) { Int32 value = 123; EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=456", "abc", &value)); EXPECT_EQ(456, value); EXPECT_TRUE(ParseInt32Flag("--" GTEST_FLAG_PREFIX_ "abc=-789", "abc", &value)); EXPECT_EQ(-789, value); } // Tests that Int32FromEnvOrDie() parses the value of the var or // returns the correct default. // Environment variables are not supported on Windows CE. #if !GTEST_OS_WINDOWS_MOBILE TEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) { EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "123"); EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); SetEnv(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", "-123"); EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "UnsetVar", 333)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests that Int32FromEnvOrDie() aborts with an error message // if the variable is not an Int32. TEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "xxx"); EXPECT_DEATH_IF_SUPPORTED( Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that Int32FromEnvOrDie() aborts with an error message // if the variable cannot be represnted by an Int32. TEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) { SetEnv(GTEST_FLAG_PREFIX_UPPER_ "VAR", "1234567891234567891234"); EXPECT_DEATH_IF_SUPPORTED( Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ "VAR", 123), ".*"); } // Tests that ShouldRunTestOnShard() selects all tests // where there is 1 shard. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) { EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3)); EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4)); } class ShouldShardTest : public testing::Test { protected: virtual void SetUp() { index_var_ = GTEST_FLAG_PREFIX_UPPER_ "INDEX"; total_var_ = GTEST_FLAG_PREFIX_UPPER_ "TOTAL"; } virtual void TearDown() { SetEnv(index_var_, ""); SetEnv(total_var_, ""); } const char* index_var_; const char* total_var_; }; // Tests that sharding is disabled if neither of the environment variables // are set. TEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) { SetEnv(index_var_, ""); SetEnv(total_var_, ""); EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } // Tests that sharding is not enabled if total_shards == 1. TEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) { SetEnv(index_var_, "0"); SetEnv(total_var_, "1"); EXPECT_FALSE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } // Tests that sharding is enabled if total_shards > 1 and // we are not in a death test subprocess. // Environment variables are not supported on Windows CE. #if !GTEST_OS_WINDOWS_MOBILE TEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) { SetEnv(index_var_, "4"); SetEnv(total_var_, "22"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); SetEnv(index_var_, "8"); SetEnv(total_var_, "9"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); SetEnv(index_var_, "0"); SetEnv(total_var_, "9"); EXPECT_TRUE(ShouldShard(total_var_, index_var_, false)); EXPECT_FALSE(ShouldShard(total_var_, index_var_, true)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Tests that we exit in error if the sharding values are not valid. typedef ShouldShardTest ShouldShardDeathTest; TEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) { SetEnv(index_var_, "4"); SetEnv(total_var_, "4"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, "4"); SetEnv(total_var_, "-2"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, "5"); SetEnv(total_var_, ""); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); SetEnv(index_var_, ""); SetEnv(total_var_, "5"); EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), ".*"); } // Tests that ShouldRunTestOnShard is a partition when 5 // shards are used. TEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) { // Choose an arbitrary number of tests and shards. const int num_tests = 17; const int num_shards = 5; // Check partitioning: each test should be on exactly 1 shard. for (int test_id = 0; test_id < num_tests; test_id++) { int prev_selected_shard_index = -1; for (int shard_index = 0; shard_index < num_shards; shard_index++) { if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) { if (prev_selected_shard_index < 0) { prev_selected_shard_index = shard_index; } else { ADD_FAILURE() << "Shard " << prev_selected_shard_index << " and " << shard_index << " are both selected to run test " << test_id; } } } } // Check balance: This is not required by the sharding protocol, but is a // desirable property for performance. for (int shard_index = 0; shard_index < num_shards; shard_index++) { int num_tests_on_shard = 0; for (int test_id = 0; test_id < num_tests; test_id++) { num_tests_on_shard += ShouldRunTestOnShard(num_shards, shard_index, test_id); } EXPECT_GE(num_tests_on_shard, num_tests / num_shards); } } // For the same reason we are not explicitly testing everything in the // Test class, there are no separate tests for the following classes // (except for some trivial cases): // // TestCase, UnitTest, UnitTestResultPrinter. // // Similarly, there are no separate tests for the following macros: // // TEST, TEST_F, RUN_ALL_TESTS TEST(UnitTestTest, CanGetOriginalWorkingDir) { ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != NULL); EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), ""); } TEST(UnitTestTest, ReturnsPlausibleTimestamp) { EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp()); EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis()); } // When a property using a reserved key is supplied to this function, it // tests that a non-fatal failure is added, a fatal failure is not added, // and that the property is not recorded. void ExpectNonFatalFailureRecordingPropertyWithReservedKey( const TestResult& test_result, const char* key) { EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, "1"), "Reserved key"); ASSERT_EQ(0, test_result.test_property_count()) << "Property for key '" << key << "' recorded unexpectedly."; } void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( const char* key) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(test_info != NULL); ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(), key); } void ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( const char* key) { const TestCase* test_case = UnitTest::GetInstance()->current_test_case(); ASSERT_TRUE(test_case != NULL); ExpectNonFatalFailureRecordingPropertyWithReservedKey( test_case->ad_hoc_test_result(), key); } void ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( const char* key) { ExpectNonFatalFailureRecordingPropertyWithReservedKey( UnitTest::GetInstance()->ad_hoc_test_result(), key); } // Tests that property recording functions in UnitTest outside of tests // functions correcly. Creating a separate instance of UnitTest ensures it // is in a state similar to the UnitTest's singleton's between tests. class UnitTestRecordPropertyTest : public testing::internal::UnitTestRecordPropertyTestHelper { public: static void SetUpTestCase() { ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( "disabled"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( "errors"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( "failures"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( "name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( "tests"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestCase( "time"); Test::RecordProperty("test_case_key_1", "1"); const TestCase* test_case = UnitTest::GetInstance()->current_test_case(); ASSERT_TRUE(test_case != NULL); ASSERT_EQ(1, test_case->ad_hoc_test_result().test_property_count()); EXPECT_STREQ("test_case_key_1", test_case->ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("1", test_case->ad_hoc_test_result().GetTestProperty(0).value()); } }; // Tests TestResult has the expected property when added. TEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) { UnitTestRecordProperty("key_1", "1"); ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count()); EXPECT_STREQ("key_1", unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); } // Tests TestResult has multiple properties when added. TEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) { UnitTestRecordProperty("key_1", "1"); UnitTestRecordProperty("key_2", "2"); ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count()); EXPECT_STREQ("key_1", unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("1", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); EXPECT_STREQ("key_2", unit_test_.ad_hoc_test_result().GetTestProperty(1).key()); EXPECT_STREQ("2", unit_test_.ad_hoc_test_result().GetTestProperty(1).value()); } // Tests TestResult::RecordProperty() overrides values for duplicate keys. TEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) { UnitTestRecordProperty("key_1", "1"); UnitTestRecordProperty("key_2", "2"); UnitTestRecordProperty("key_1", "12"); UnitTestRecordProperty("key_2", "22"); ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count()); EXPECT_STREQ("key_1", unit_test_.ad_hoc_test_result().GetTestProperty(0).key()); EXPECT_STREQ("12", unit_test_.ad_hoc_test_result().GetTestProperty(0).value()); EXPECT_STREQ("key_2", unit_test_.ad_hoc_test_result().GetTestProperty(1).key()); EXPECT_STREQ("22", unit_test_.ad_hoc_test_result().GetTestProperty(1).value()); } TEST_F(UnitTestRecordPropertyTest, AddFailureInsideTestsWhenUsingTestCaseReservedKeys) { ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "value_param"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "type_param"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "status"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "time"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest( "classname"); } TEST_F(UnitTestRecordPropertyTest, AddRecordWithReservedKeysGeneratesCorrectPropertyList) { EXPECT_NONFATAL_FAILURE( Test::RecordProperty("name", "1"), "'classname', 'name', 'status', 'time', 'type_param', and 'value_param'" " are reserved"); } class UnitTestRecordPropertyTestEnvironment : public Environment { public: virtual void TearDown() { ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "tests"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "failures"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "disabled"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "errors"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "name"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "timestamp"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "time"); ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestCase( "random_seed"); } }; // This will test property recording outside of any test or test case. static Environment* record_property_env = AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment); // This group of tests is for predicate assertions (ASSERT_PRED*, etc) // of various arities. They do not attempt to be exhaustive. Rather, // view them as smoke tests that can be easily reviewed and verified. // A more complete set of tests for predicate assertions can be found // in gtest_pred_impl_unittest.cc. // First, some predicates and predicate-formatters needed by the tests. // Returns true iff the argument is an even number. bool IsEven(int n) { return (n % 2) == 0; } // A functor that returns true iff the argument is an even number. struct IsEvenFunctor { bool operator()(int n) { return IsEven(n); } }; // A predicate-formatter function that asserts the argument is an even // number. AssertionResult AssertIsEven(const char* expr, int n) { if (IsEven(n)) { return AssertionSuccess(); } Message msg; msg << expr << " evaluates to " << n << ", which is not even."; return AssertionFailure(msg); } // A predicate function that returns AssertionResult for use in // EXPECT/ASSERT_TRUE/FALSE. AssertionResult ResultIsEven(int n) { if (IsEven(n)) return AssertionSuccess() << n << " is even"; else return AssertionFailure() << n << " is odd"; } // A predicate function that returns AssertionResult but gives no // explanation why it succeeds. Needed for testing that // EXPECT/ASSERT_FALSE handles such functions correctly. AssertionResult ResultIsEvenNoExplanation(int n) { if (IsEven(n)) return AssertionSuccess(); else return AssertionFailure() << n << " is odd"; } // A predicate-formatter functor that asserts the argument is an even // number. struct AssertIsEvenFunctor { AssertionResult operator()(const char* expr, int n) { return AssertIsEven(expr, n); } }; // Returns true iff the sum of the arguments is an even number. bool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); } // A functor that returns true iff the sum of the arguments is an even // number. struct SumIsEven3Functor { bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); } }; // A predicate-formatter function that asserts the sum of the // arguments is an even number. AssertionResult AssertSumIsEven4( const char* e1, const char* e2, const char* e3, const char* e4, int n1, int n2, int n3, int n4) { const int sum = n1 + n2 + n3 + n4; if (IsEven(sum)) { return AssertionSuccess(); } Message msg; msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << ") evaluates to " << sum << ", which is not even."; return AssertionFailure(msg); } // A predicate-formatter functor that asserts the sum of the arguments // is an even number. struct AssertSumIsEven5Functor { AssertionResult operator()( const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, int n1, int n2, int n3, int n4, int n5) { const int sum = n1 + n2 + n3 + n4 + n5; if (IsEven(sum)) { return AssertionSuccess(); } Message msg; msg << e1 << " + " << e2 << " + " << e3 << " + " << e4 << " + " << e5 << " (" << n1 << " + " << n2 << " + " << n3 << " + " << n4 << " + " << n5 << ") evaluates to " << sum << ", which is not even."; return AssertionFailure(msg); } }; // Tests unary predicate assertions. // Tests unary predicate assertions that don't use a custom formatter. TEST(Pred1Test, WithoutFormat) { // Success cases. EXPECT_PRED1(IsEvenFunctor(), 2) << "This failure is UNEXPECTED!"; ASSERT_PRED1(IsEven, 4); // Failure cases. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED1(IsEven, 5) << "This failure is expected."; }, "This failure is expected."); EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), "evaluates to false"); } // Tests unary predicate assertions that use a custom formatter. TEST(Pred1Test, WithFormat) { // Success cases. EXPECT_PRED_FORMAT1(AssertIsEven, 2); ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4) << "This failure is UNEXPECTED!"; // Failure cases. const int n = 5; EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n), "n evaluates to 5, which is not even."); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT1(AssertIsEven, 5) << "This failure is expected."; }, "This failure is expected."); } // Tests that unary predicate assertions evaluates their arguments // exactly once. TEST(Pred1Test, SingleEvaluationOnFailure) { // A success case. static int n = 0; EXPECT_PRED1(IsEven, n++); EXPECT_EQ(1, n) << "The argument is not evaluated exactly once."; // A failure case. EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++) << "This failure is expected."; }, "This failure is expected."); EXPECT_EQ(2, n) << "The argument is not evaluated exactly once."; } // Tests predicate assertions whose arity is >= 2. // Tests predicate assertions that don't use a custom formatter. TEST(PredTest, WithoutFormat) { // Success cases. ASSERT_PRED2(SumIsEven2, 2, 4) << "This failure is UNEXPECTED!"; EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8); // Failure cases. const int n1 = 1; const int n2 = 2; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED2(SumIsEven2, n1, n2) << "This failure is expected."; }, "This failure is expected."); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4); }, "evaluates to false"); } // Tests predicate assertions that use a custom formatter. TEST(PredTest, WithFormat) { // Success cases. ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10) << "This failure is UNEXPECTED!"; EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10); // Failure cases. const int n1 = 1; const int n2 = 2; const int n3 = 4; const int n4 = 6; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4); }, "evaluates to 13, which is not even."); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8) << "This failure is expected."; }, "This failure is expected."); } // Tests that predicate assertions evaluates their arguments // exactly once. TEST(PredTest, SingleEvaluationOnFailure) { // A success case. int n1 = 0; int n2 = 0; EXPECT_PRED2(SumIsEven2, n1++, n2++); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; // Another success case. n1 = n2 = 0; int n3 = 0; int n4 = 0; int n5 = 0; ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++) << "This failure is UNEXPECTED!"; EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; EXPECT_EQ(1, n5) << "Argument 5 is not evaluated exactly once."; // A failure case. n1 = n2 = n3 = 0; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++) << "This failure is expected."; }, "This failure is expected."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; // Another failure case. n1 = n2 = n3 = n4 = 0; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++); }, "evaluates to 1, which is not even."); EXPECT_EQ(1, n1) << "Argument 1 is not evaluated exactly once."; EXPECT_EQ(1, n2) << "Argument 2 is not evaluated exactly once."; EXPECT_EQ(1, n3) << "Argument 3 is not evaluated exactly once."; EXPECT_EQ(1, n4) << "Argument 4 is not evaluated exactly once."; } // Some helper functions for testing using overloaded/template // functions with ASSERT_PREDn and EXPECT_PREDn. bool IsPositive(double x) { return x > 0; } template <typename T> bool IsNegative(T x) { return x < 0; } template <typename T1, typename T2> bool GreaterThan(T1 x1, T2 x2) { return x1 > x2; } // Tests that overloaded functions can be used in *_PRED* as long as // their types are explicitly specified. TEST(PredicateAssertionTest, AcceptsOverloadedFunction) { // C++Builder requires C-style casts rather than static_cast. EXPECT_PRED1((bool (*)(int))(IsPositive), 5); // NOLINT ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0); // NOLINT } // Tests that template functions can be used in *_PRED* as long as // their types are explicitly specified. TEST(PredicateAssertionTest, AcceptsTemplateFunction) { EXPECT_PRED1(IsNegative<int>, -5); // Makes sure that we can handle templates with more than one // parameter. ASSERT_PRED2((GreaterThan<int, int>), 5, 0); } // Some helper functions for testing using overloaded/template // functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn. AssertionResult IsPositiveFormat(const char* /* expr */, int n) { return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } AssertionResult IsPositiveFormat(const char* /* expr */, double x) { return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template <typename T> AssertionResult IsNegativeFormat(const char* /* expr */, T x) { return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } template <typename T1, typename T2> AssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */, const T1& x1, const T2& x2) { return x1 == x2 ? AssertionSuccess() : AssertionFailure(Message() << "Failure"); } // Tests that overloaded functions can be used in *_PRED_FORMAT* // without explicitly specifying their types. TEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) { EXPECT_PRED_FORMAT1(IsPositiveFormat, 5); ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0); } // Tests that template functions can be used in *_PRED_FORMAT* without // explicitly specifying their types. TEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) { EXPECT_PRED_FORMAT1(IsNegativeFormat, -5); ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3); } // Tests string assertions. // Tests ASSERT_STREQ with non-NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ) { const char * const p1 = "good"; ASSERT_STREQ(p1, p1); // Let p2 have the same content as p1, but be at a different address. const char p2[] = "good"; ASSERT_STREQ(p1, p2); EXPECT_FATAL_FAILURE(ASSERT_STREQ("bad", "good"), "Expected: \"bad\""); } // Tests ASSERT_STREQ with NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ_Null) { ASSERT_STREQ(static_cast<const char *>(NULL), NULL); EXPECT_FATAL_FAILURE(ASSERT_STREQ(NULL, "non-null"), "non-null"); } // Tests ASSERT_STREQ with NULL arguments. TEST(StringAssertionTest, ASSERT_STREQ_Null2) { EXPECT_FATAL_FAILURE(ASSERT_STREQ("non-null", NULL), "non-null"); } // Tests ASSERT_STRNE. TEST(StringAssertionTest, ASSERT_STRNE) { ASSERT_STRNE("hi", "Hi"); ASSERT_STRNE("Hi", NULL); ASSERT_STRNE(NULL, "Hi"); ASSERT_STRNE("", NULL); ASSERT_STRNE(NULL, ""); ASSERT_STRNE("", "Hi"); ASSERT_STRNE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRNE("Hi", "Hi"), "\"Hi\" vs \"Hi\""); } // Tests ASSERT_STRCASEEQ. TEST(StringAssertionTest, ASSERT_STRCASEEQ) { ASSERT_STRCASEEQ("hi", "Hi"); ASSERT_STRCASEEQ(static_cast<const char *>(NULL), NULL); ASSERT_STRCASEEQ("", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("Hi", "hi2"), "Ignoring case"); } // Tests ASSERT_STRCASENE. TEST(StringAssertionTest, ASSERT_STRCASENE) { ASSERT_STRCASENE("hi1", "Hi2"); ASSERT_STRCASENE("Hi", NULL); ASSERT_STRCASENE(NULL, "Hi"); ASSERT_STRCASENE("", NULL); ASSERT_STRCASENE(NULL, ""); ASSERT_STRCASENE("", "Hi"); ASSERT_STRCASENE("Hi", ""); EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("Hi", "hi"), "(ignoring case)"); } // Tests *_STREQ on wide strings. TEST(StringAssertionTest, STREQ_Wide) { // NULL strings. ASSERT_STREQ(static_cast<const wchar_t *>(NULL), NULL); // Empty strings. ASSERT_STREQ(L"", L""); // Non-null vs NULL. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"non-null", NULL), "non-null"); // Equal strings. EXPECT_STREQ(L"Hi", L"Hi"); // Unequal strings. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc", L"Abc"), "Abc"); // Strings containing wide characters. EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L"abc\x8119", L"abc\x8120"), "abc"); // The streaming variation. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_STREQ(L"abc\x8119", L"abc\x8121") << "Expected failure"; }, "Expected failure"); } // Tests *_STRNE on wide strings. TEST(StringAssertionTest, STRNE_Wide) { // NULL strings. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_STRNE(static_cast<const wchar_t *>(NULL), NULL); }, ""); // Empty strings. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"", L""), "L\"\""); // Non-null vs NULL. ASSERT_STRNE(L"non-null", NULL); // Equal strings. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"Hi", L"Hi"), "L\"Hi\""); // Unequal strings. EXPECT_STRNE(L"abc", L"Abc"); // Strings containing wide characters. EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L"abc\x8119", L"abc\x8119"), "abc"); // The streaming variation. ASSERT_STRNE(L"abc\x8119", L"abc\x8120") << "This shouldn't happen"; } // Tests for ::testing::IsSubstring(). // Tests that IsSubstring() returns the correct result when the input // argument type is const char*. TEST(IsSubstringTest, ReturnsCorrectResultForCString) { EXPECT_FALSE(IsSubstring("", "", NULL, "a")); EXPECT_FALSE(IsSubstring("", "", "b", NULL)); EXPECT_FALSE(IsSubstring("", "", "needle", "haystack")); EXPECT_TRUE(IsSubstring("", "", static_cast<const char*>(NULL), NULL)); EXPECT_TRUE(IsSubstring("", "", "needle", "two needles")); } // Tests that IsSubstring() returns the correct result when the input // argument type is const wchar_t*. TEST(IsSubstringTest, ReturnsCorrectResultForWideCString) { EXPECT_FALSE(IsSubstring("", "", kNull, L"a")); EXPECT_FALSE(IsSubstring("", "", L"b", kNull)); EXPECT_FALSE(IsSubstring("", "", L"needle", L"haystack")); EXPECT_TRUE(IsSubstring("", "", static_cast<const wchar_t*>(NULL), NULL)); EXPECT_TRUE(IsSubstring("", "", L"needle", L"two needles")); } // Tests that IsSubstring() generates the correct message when the input // argument type is const char*. TEST(IsSubstringTest, GeneratesCorrectMessageForCString) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: \"needle\"\n" "Expected: a substring of haystack_expr\n" "Which is: \"haystack\"", IsSubstring("needle_expr", "haystack_expr", "needle", "haystack").failure_message()); } // Tests that IsSubstring returns the correct result when the input // argument type is ::std::string. TEST(IsSubstringTest, ReturnsCorrectResultsForStdString) { EXPECT_TRUE(IsSubstring("", "", std::string("hello"), "ahellob")); EXPECT_FALSE(IsSubstring("", "", "hello", std::string("world"))); } #if GTEST_HAS_STD_WSTRING // Tests that IsSubstring returns the correct result when the input // argument type is ::std::wstring. TEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) { EXPECT_TRUE(IsSubstring("", "", ::std::wstring(L"needle"), L"two needles")); EXPECT_FALSE(IsSubstring("", "", L"needle", ::std::wstring(L"haystack"))); } // Tests that IsSubstring() generates the correct message when the input // argument type is ::std::wstring. TEST(IsSubstringTest, GeneratesCorrectMessageForWstring) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: L\"needle\"\n" "Expected: a substring of haystack_expr\n" "Which is: L\"haystack\"", IsSubstring( "needle_expr", "haystack_expr", ::std::wstring(L"needle"), L"haystack").failure_message()); } #endif // GTEST_HAS_STD_WSTRING // Tests for ::testing::IsNotSubstring(). // Tests that IsNotSubstring() returns the correct result when the input // argument type is const char*. TEST(IsNotSubstringTest, ReturnsCorrectResultForCString) { EXPECT_TRUE(IsNotSubstring("", "", "needle", "haystack")); EXPECT_FALSE(IsNotSubstring("", "", "needle", "two needles")); } // Tests that IsNotSubstring() returns the correct result when the input // argument type is const wchar_t*. TEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) { EXPECT_TRUE(IsNotSubstring("", "", L"needle", L"haystack")); EXPECT_FALSE(IsNotSubstring("", "", L"needle", L"two needles")); } // Tests that IsNotSubstring() generates the correct message when the input // argument type is const wchar_t*. TEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: L\"needle\"\n" "Expected: not a substring of haystack_expr\n" "Which is: L\"two needles\"", IsNotSubstring( "needle_expr", "haystack_expr", L"needle", L"two needles").failure_message()); } // Tests that IsNotSubstring returns the correct result when the input // argument type is ::std::string. TEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) { EXPECT_FALSE(IsNotSubstring("", "", std::string("hello"), "ahellob")); EXPECT_TRUE(IsNotSubstring("", "", "hello", std::string("world"))); } // Tests that IsNotSubstring() generates the correct message when the input // argument type is ::std::string. TEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) { EXPECT_STREQ("Value of: needle_expr\n" " Actual: \"needle\"\n" "Expected: not a substring of haystack_expr\n" "Which is: \"two needles\"", IsNotSubstring( "needle_expr", "haystack_expr", ::std::string("needle"), "two needles").failure_message()); } #if GTEST_HAS_STD_WSTRING // Tests that IsNotSubstring returns the correct result when the input // argument type is ::std::wstring. TEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) { EXPECT_FALSE( IsNotSubstring("", "", ::std::wstring(L"needle"), L"two needles")); EXPECT_TRUE(IsNotSubstring("", "", L"needle", ::std::wstring(L"haystack"))); } #endif // GTEST_HAS_STD_WSTRING // Tests floating-point assertions. template <typename RawType> class FloatingPointTest : public Test { protected: // Pre-calculated numbers to be used by the tests. struct TestValues { RawType close_to_positive_zero; RawType close_to_negative_zero; RawType further_from_negative_zero; RawType close_to_one; RawType further_from_one; RawType infinity; RawType close_to_infinity; RawType further_from_infinity; RawType nan1; RawType nan2; }; typedef typename testing::internal::FloatingPoint<RawType> Floating; typedef typename Floating::Bits Bits; virtual void SetUp() { const size_t max_ulps = Floating::kMaxUlps; // The bits that represent 0.0. const Bits zero_bits = Floating(0).bits(); // Makes some numbers close to 0.0. values_.close_to_positive_zero = Floating::ReinterpretBits( zero_bits + max_ulps/2); values_.close_to_negative_zero = -Floating::ReinterpretBits( zero_bits + max_ulps - max_ulps/2); values_.further_from_negative_zero = -Floating::ReinterpretBits( zero_bits + max_ulps + 1 - max_ulps/2); // The bits that represent 1.0. const Bits one_bits = Floating(1).bits(); // Makes some numbers close to 1.0. values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps); values_.further_from_one = Floating::ReinterpretBits( one_bits + max_ulps + 1); // +infinity. values_.infinity = Floating::Infinity(); // The bits that represent +infinity. const Bits infinity_bits = Floating(values_.infinity).bits(); // Makes some numbers close to infinity. values_.close_to_infinity = Floating::ReinterpretBits( infinity_bits - max_ulps); values_.further_from_infinity = Floating::ReinterpretBits( infinity_bits - max_ulps - 1); // Makes some NAN's. Sets the most significant bit of the fraction so that // our NaN's are quiet; trying to process a signaling NaN would raise an // exception if our environment enables floating point exceptions. values_.nan1 = Floating::ReinterpretBits(Floating::kExponentBitMask | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1); values_.nan2 = Floating::ReinterpretBits(Floating::kExponentBitMask | (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200); } void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); } static TestValues values_; }; template <typename RawType> typename FloatingPointTest<RawType>::TestValues FloatingPointTest<RawType>::values_; // Instantiates FloatingPointTest for testing *_FLOAT_EQ. typedef FloatingPointTest<float> FloatTest; // Tests that the size of Float::Bits matches the size of float. TEST_F(FloatTest, Size) { TestSize(); } // Tests comparing with +0 and -0. TEST_F(FloatTest, Zeros) { EXPECT_FLOAT_EQ(0.0, -0.0); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), "1.0"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), "1.5"); } // Tests comparing numbers close to 0. // // This ensures that *_FLOAT_EQ handles the sign correctly and no // overflow occurs when comparing numbers whose absolute value is very // small. TEST_F(FloatTest, AlmostZeros) { // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const FloatTest::TestValues& v = this->values_; EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero); EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero); EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero); }, "v.further_from_negative_zero"); } // Tests comparing numbers close to each other. TEST_F(FloatTest, SmallDiff) { EXPECT_FLOAT_EQ(1.0, values_.close_to_one); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one), "values_.further_from_one"); } // Tests comparing numbers far apart. TEST_F(FloatTest, LargeDiff) { EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), "3.0"); } // Tests comparing with infinity. // // This ensures that no overflow occurs when comparing numbers whose // absolute value is very large. TEST_F(FloatTest, Infinity) { EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity); EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity); #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); // This is interesting as the representations of infinity and nan1 // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1), "values_.nan1"); #endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(FloatTest, NaN) { #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const FloatTest::TestValues& v = this->values_; EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), "v.infinity"); #endif // !GTEST_OS_SYMBIAN } // Tests that *_FLOAT_EQ are reflexive. TEST_F(FloatTest, Reflexive) { EXPECT_FLOAT_EQ(0.0, 0.0); EXPECT_FLOAT_EQ(1.0, 1.0); ASSERT_FLOAT_EQ(values_.infinity, values_.infinity); } // Tests that *_FLOAT_EQ are commutative. TEST_F(FloatTest, Commutative) { // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one). EXPECT_FLOAT_EQ(values_.close_to_one, 1.0); // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one). EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0), "1.0"); } // Tests EXPECT_NEAR. TEST_F(FloatTest, EXPECT_NEAR) { EXPECT_NEAR(-1.0f, -1.1f, 0.2f); EXPECT_NEAR(2.0f, 3.0f, 1.0f); EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f,1.5f, 0.25f), // NOLINT "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous line. } // Tests ASSERT_NEAR. TEST_F(FloatTest, ASSERT_NEAR) { ASSERT_NEAR(-1.0f, -1.1f, 0.2f); ASSERT_NEAR(2.0f, 3.0f, 1.0f); EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f,1.5f, 0.25f), // NOLINT "The difference between 1.0f and 1.5f is 0.5, " "which exceeds 0.25f"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous line. } // Tests the cases where FloatLE() should succeed. TEST_F(FloatTest, FloatLESucceeds) { EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f); // When val1 < val2, ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f); // val1 == val2, // or when val1 is greater than, but almost equals to, val2. EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f); } // Tests the cases where FloatLE() should fail. TEST_F(FloatTest, FloatLEFails) { // When val1 is greater than val2 by a large margin, EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f), "(2.0f) <= (1.0f)"); // or by a small yet non-negligible margin, EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f); }, "(values_.further_from_one) <= (1.0f)"); #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) // Nokia's STLport crashes if we try to output infinity or NaN. // C++Builder gives bad results for ordered comparisons involving NaNs // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1); }, "(-values_.infinity) <= (values_.nan1)"); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } // Instantiates FloatingPointTest for testing *_DOUBLE_EQ. typedef FloatingPointTest<double> DoubleTest; // Tests that the size of Double::Bits matches the size of double. TEST_F(DoubleTest, Size) { TestSize(); } // Tests comparing with +0 and -0. TEST_F(DoubleTest, Zeros) { EXPECT_DOUBLE_EQ(0.0, -0.0); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), "1.0"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), "1.0"); } // Tests comparing numbers close to 0. // // This ensures that *_DOUBLE_EQ handles the sign correctly and no // overflow occurs when comparing numbers whose absolute value is very // small. TEST_F(DoubleTest, AlmostZeros) { // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const DoubleTest::TestValues& v = this->values_; EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero); EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero); EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_DOUBLE_EQ(v.close_to_positive_zero, v.further_from_negative_zero); }, "v.further_from_negative_zero"); } // Tests comparing numbers close to each other. TEST_F(DoubleTest, SmallDiff) { EXPECT_DOUBLE_EQ(1.0, values_.close_to_one); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one), "values_.further_from_one"); } // Tests comparing numbers far apart. TEST_F(DoubleTest, LargeDiff) { EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), "3.0"); } // Tests comparing with infinity. // // This ensures that no overflow occurs when comparing numbers whose // absolute value is very large. TEST_F(DoubleTest, Infinity) { EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity); EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity); #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity), "-values_.infinity"); // This is interesting as the representations of infinity_ and nan1_ // are only 1 DLP apart. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1), "values_.nan1"); #endif // !GTEST_OS_SYMBIAN } // Tests that comparing with NAN always returns false. TEST_F(DoubleTest, NaN) { #if !GTEST_OS_SYMBIAN // In C++Builder, names within local classes (such as used by // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the // scoping class. Use a static local alias as a workaround. // We use the assignment syntax since some compilers, like Sun Studio, // don't allow initializing references using construction syntax // (parentheses). static const DoubleTest::TestValues& v = this->values_; // Nokia's STLport crashes if we try to output infinity or NaN. EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), "v.nan1"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), "v.nan2"); EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), "v.nan1"); EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), "v.infinity"); #endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are reflexive. TEST_F(DoubleTest, Reflexive) { EXPECT_DOUBLE_EQ(0.0, 0.0); EXPECT_DOUBLE_EQ(1.0, 1.0); #if !GTEST_OS_SYMBIAN // Nokia's STLport crashes if we try to output infinity or NaN. ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity); #endif // !GTEST_OS_SYMBIAN } // Tests that *_DOUBLE_EQ are commutative. TEST_F(DoubleTest, Commutative) { // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one). EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0); // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one). EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0), "1.0"); } // Tests EXPECT_NEAR. TEST_F(DoubleTest, EXPECT_NEAR) { EXPECT_NEAR(-1.0, -1.1, 0.2); EXPECT_NEAR(2.0, 3.0, 1.0); EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25), // NOLINT "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous statement. } // Tests ASSERT_NEAR. TEST_F(DoubleTest, ASSERT_NEAR) { ASSERT_NEAR(-1.0, -1.1, 0.2); ASSERT_NEAR(2.0, 3.0, 1.0); EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25), // NOLINT "The difference between 1.0 and 1.5 is 0.5, " "which exceeds 0.25"); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous statement. } // Tests the cases where DoubleLE() should succeed. TEST_F(DoubleTest, DoubleLESucceeds) { EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0); // When val1 < val2, ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0); // val1 == val2, // or when val1 is greater than, but almost equals to, val2. EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0); } // Tests the cases where DoubleLE() should fail. TEST_F(DoubleTest, DoubleLEFails) { // When val1 is greater than val2 by a large margin, EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0), "(2.0) <= (1.0)"); // or by a small yet non-negligible margin, EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0); }, "(values_.further_from_one) <= (1.0)"); #if !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) // Nokia's STLport crashes if we try to output infinity or NaN. // C++Builder gives bad results for ordered comparisons involving NaNs // due to compiler bugs. EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity); }, "(values_.nan1) <= (values_.infinity)"); EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1); }, " (-values_.infinity) <= (values_.nan1)"); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1); }, "(values_.nan1) <= (values_.nan1)"); #endif // !GTEST_OS_SYMBIAN && !defined(__BORLANDC__) } // Verifies that a test or test case whose name starts with DISABLED_ is // not run. // A test whose name starts with DISABLED_. // Should not run. TEST(DisabledTest, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Disabled test should not be run."; } // A test whose name does not start with DISABLED_. // Should run. TEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); } // A test case whose name starts with DISABLED_. // Should not run. TEST(DISABLED_TestCase, TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } // A test case and test whose names start with DISABLED_. // Should not run. TEST(DISABLED_TestCase, DISABLED_TestShouldNotRun) { FAIL() << "Unexpected failure: Test in disabled test case should not be run."; } // Check that when all tests in a test case are disabled, SetupTestCase() and // TearDownTestCase() are not called. class DisabledTestsTest : public Test { protected: static void SetUpTestCase() { FAIL() << "Unexpected failure: All tests disabled in test case. " "SetupTestCase() should not be called."; } static void TearDownTestCase() { FAIL() << "Unexpected failure: All tests disabled in test case. " "TearDownTestCase() should not be called."; } }; TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) { FAIL() << "Unexpected failure: Disabled test should not be run."; } TEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) { FAIL() << "Unexpected failure: Disabled test should not be run."; } // Tests that disabled typed tests aren't run. #if GTEST_HAS_TYPED_TEST template <typename T> class TypedTest : public Test { }; typedef testing::Types<int, double> NumericTypes; TYPED_TEST_CASE(TypedTest, NumericTypes); TYPED_TEST(TypedTest, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; } template <typename T> class DISABLED_TypedTest : public Test { }; TYPED_TEST_CASE(DISABLED_TypedTest, NumericTypes); TYPED_TEST(DISABLED_TypedTest, ShouldNotRun) { FAIL() << "Unexpected failure: Disabled typed test should not run."; } #endif // GTEST_HAS_TYPED_TEST // Tests that disabled type-parameterized tests aren't run. #if GTEST_HAS_TYPED_TEST_P template <typename T> class TypedTestP : public Test { }; TYPED_TEST_CASE_P(TypedTestP); TYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } REGISTER_TYPED_TEST_CASE_P(TypedTestP, DISABLED_ShouldNotRun); INSTANTIATE_TYPED_TEST_CASE_P(My, TypedTestP, NumericTypes); template <typename T> class DISABLED_TypedTestP : public Test { }; TYPED_TEST_CASE_P(DISABLED_TypedTestP); TYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) { FAIL() << "Unexpected failure: " << "Disabled type-parameterized test should not run."; } REGISTER_TYPED_TEST_CASE_P(DISABLED_TypedTestP, ShouldNotRun); INSTANTIATE_TYPED_TEST_CASE_P(My, DISABLED_TypedTestP, NumericTypes); #endif // GTEST_HAS_TYPED_TEST_P // Tests that assertion macros evaluate their arguments exactly once. class SingleEvaluationTest : public Test { public: // Must be public and not protected due to a bug in g++ 3.4.2. // This helper function is needed by the FailedASSERT_STREQ test // below. It's public to work around C++Builder's bug with scoping local // classes. static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); } // This helper function is needed by the FailedASSERT_NE test below. It's // public to work around C++Builder's bug with scoping local classes. static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); } protected: SingleEvaluationTest() { p1_ = s1_; p2_ = s2_; a_ = 0; b_ = 0; } static const char* const s1_; static const char* const s2_; static const char* p1_; static const char* p2_; static int a_; static int b_; }; const char* const SingleEvaluationTest::s1_ = "01234"; const char* const SingleEvaluationTest::s2_ = "abcde"; const char* SingleEvaluationTest::p1_; const char* SingleEvaluationTest::p2_; int SingleEvaluationTest::a_; int SingleEvaluationTest::b_; // Tests that when ASSERT_STREQ fails, it evaluates its arguments // exactly once. TEST_F(SingleEvaluationTest, FailedASSERT_STREQ) { EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(), "p2_++"); EXPECT_EQ(s1_ + 1, p1_); EXPECT_EQ(s2_ + 1, p2_); } // Tests that string assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ASSERT_STR) { // successful EXPECT_STRNE EXPECT_STRNE(p1_++, p2_++); EXPECT_EQ(s1_ + 1, p1_); EXPECT_EQ(s2_ + 1, p2_); // failed EXPECT_STRCASEEQ EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), "Ignoring case"); EXPECT_EQ(s1_ + 2, p1_); EXPECT_EQ(s2_ + 2, p2_); } // Tests that when ASSERT_NE fails, it evaluates its arguments exactly // once. TEST_F(SingleEvaluationTest, FailedASSERT_NE) { EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(), "(a_++) != (b_++)"); EXPECT_EQ(1, a_); EXPECT_EQ(1, b_); } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, OtherCases) { // successful EXPECT_TRUE EXPECT_TRUE(0 == a_++); // NOLINT EXPECT_EQ(1, a_); // failed EXPECT_TRUE EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), "-1 == a_++"); EXPECT_EQ(2, a_); // successful EXPECT_GT EXPECT_GT(a_++, b_++); EXPECT_EQ(3, a_); EXPECT_EQ(1, b_); // failed EXPECT_LT EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), "(a_++) < (b_++)"); EXPECT_EQ(4, a_); EXPECT_EQ(2, b_); // successful ASSERT_TRUE ASSERT_TRUE(0 < a_++); // NOLINT EXPECT_EQ(5, a_); // successful ASSERT_GT ASSERT_GT(a_++, b_++); EXPECT_EQ(6, a_); EXPECT_EQ(3, b_); } #if GTEST_HAS_EXCEPTIONS void ThrowAnInteger() { throw 1; } // Tests that assertion arguments are evaluated exactly once. TEST_F(SingleEvaluationTest, ExceptionTests) { // successful EXPECT_THROW EXPECT_THROW({ // NOLINT a_++; ThrowAnInteger(); }, int); EXPECT_EQ(1, a_); // failed EXPECT_THROW, throws different EXPECT_NONFATAL_FAILURE(EXPECT_THROW({ // NOLINT a_++; ThrowAnInteger(); }, bool), "throws a different type"); EXPECT_EQ(2, a_); // failed EXPECT_THROW, throws nothing EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), "throws nothing"); EXPECT_EQ(3, a_); // successful EXPECT_NO_THROW EXPECT_NO_THROW(a_++); EXPECT_EQ(4, a_); // failed EXPECT_NO_THROW EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({ // NOLINT a_++; ThrowAnInteger(); }), "it throws"); EXPECT_EQ(5, a_); // successful EXPECT_ANY_THROW EXPECT_ANY_THROW({ // NOLINT a_++; ThrowAnInteger(); }); EXPECT_EQ(6, a_); // failed EXPECT_ANY_THROW EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), "it doesn't"); EXPECT_EQ(7, a_); } #endif // GTEST_HAS_EXCEPTIONS // Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE. class NoFatalFailureTest : public Test { protected: void Succeeds() {} void FailsNonFatal() { ADD_FAILURE() << "some non-fatal failure"; } void Fails() { FAIL() << "some fatal failure"; } void DoAssertNoFatalFailureOnFails() { ASSERT_NO_FATAL_FAILURE(Fails()); ADD_FAILURE() << "shold not reach here."; } void DoExpectNoFatalFailureOnFails() { EXPECT_NO_FATAL_FAILURE(Fails()); ADD_FAILURE() << "other failure"; } }; TEST_F(NoFatalFailureTest, NoFailure) { EXPECT_NO_FATAL_FAILURE(Succeeds()); ASSERT_NO_FATAL_FAILURE(Succeeds()); } TEST_F(NoFatalFailureTest, NonFatalIsNoFailure) { EXPECT_NONFATAL_FAILURE( EXPECT_NO_FATAL_FAILURE(FailsNonFatal()), "some non-fatal failure"); EXPECT_NONFATAL_FAILURE( ASSERT_NO_FATAL_FAILURE(FailsNonFatal()), "some non-fatal failure"); } TEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); DoAssertNoFatalFailureOnFails(); } ASSERT_EQ(2, gtest_failures.size()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", gtest_failures.GetTestPartResult(1).message()); } TEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); DoExpectNoFatalFailureOnFails(); } ASSERT_EQ(3, gtest_failures.size()); EXPECT_EQ(TestPartResult::kFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(2).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "some fatal failure", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "it does", gtest_failures.GetTestPartResult(1).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "other failure", gtest_failures.GetTestPartResult(2).message()); } TEST_F(NoFatalFailureTest, MessageIsStreamable) { TestPartResultArray gtest_failures; { ScopedFakeTestPartResultReporter gtest_reporter(>est_failures); EXPECT_NO_FATAL_FAILURE(FAIL() << "foo") << "my message"; } ASSERT_EQ(2, gtest_failures.size()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(0).type()); EXPECT_EQ(TestPartResult::kNonFatalFailure, gtest_failures.GetTestPartResult(1).type()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "foo", gtest_failures.GetTestPartResult(0).message()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "my message", gtest_failures.GetTestPartResult(1).message()); } // Tests non-string assertions. std::string EditsToString(const std::vector<EditType>& edits) { std::string out; for (size_t i = 0; i < edits.size(); ++i) { static const char kEdits[] = " +-/"; out.append(1, kEdits[edits[i]]); } return out; } std::vector<size_t> CharsToIndices(const std::string& str) { std::vector<size_t> out; for (size_t i = 0; i < str.size(); ++i) { out.push_back(str[i]); } return out; } std::vector<std::string> CharsToLines(const std::string& str) { std::vector<std::string> out; for (size_t i = 0; i < str.size(); ++i) { out.push_back(str.substr(i, 1)); } return out; } TEST(EditDistance, TestCases) { struct Case { int line; const char* left; const char* right; const char* expected_edits; const char* expected_diff; }; static const Case kCases[] = { // No change. {__LINE__, "A", "A", " ", ""}, {__LINE__, "ABCDE", "ABCDE", " ", ""}, // Simple adds. {__LINE__, "X", "XA", " +", "@@ +1,2 @@\n X\n+A\n"}, {__LINE__, "X", "XABCD", " ++++", "@@ +1,5 @@\n X\n+A\n+B\n+C\n+D\n"}, // Simple removes. {__LINE__, "XA", "X", " -", "@@ -1,2 @@\n X\n-A\n"}, {__LINE__, "XABCD", "X", " ----", "@@ -1,5 @@\n X\n-A\n-B\n-C\n-D\n"}, // Simple replaces. {__LINE__, "A", "a", "/", "@@ -1,1 +1,1 @@\n-A\n+a\n"}, {__LINE__, "ABCD", "abcd", "////", "@@ -1,4 +1,4 @@\n-A\n-B\n-C\n-D\n+a\n+b\n+c\n+d\n"}, // Path finding. {__LINE__, "ABCDEFGH", "ABXEGH1", " -/ - +", "@@ -1,8 +1,7 @@\n A\n B\n-C\n-D\n+X\n E\n-F\n G\n H\n+1\n"}, {__LINE__, "AAAABCCCC", "ABABCDCDC", "- / + / ", "@@ -1,9 +1,9 @@\n-A\n A\n-A\n+B\n A\n B\n C\n+D\n C\n-C\n+D\n C\n"}, {__LINE__, "ABCDE", "BCDCD", "- +/", "@@ -1,5 +1,5 @@\n-A\n B\n C\n D\n-E\n+C\n+D\n"}, {__LINE__, "ABCDEFGHIJKL", "BCDCDEFGJKLJK", "- ++ -- ++", "@@ -1,4 +1,5 @@\n-A\n B\n+C\n+D\n C\n D\n" "@@ -6,7 +7,7 @@\n F\n G\n-H\n-I\n J\n K\n L\n+J\n+K\n"}, {}}; for (const Case* c = kCases; c->left; ++c) { EXPECT_TRUE(c->expected_edits == EditsToString(CalculateOptimalEdits(CharsToIndices(c->left), CharsToIndices(c->right)))) << "Left <" << c->left << "> Right <" << c->right << "> Edits <" << EditsToString(CalculateOptimalEdits( CharsToIndices(c->left), CharsToIndices(c->right))) << ">"; EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))) << "Left <" << c->left << "> Right <" << c->right << "> Diff <" << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right)) << ">"; } } // Tests EqFailure(), used for implementing *EQ* assertions. TEST(AssertionTest, EqFailure) { const std::string foo_val("5"), bar_val("6"); const std::string msg1( EqFailure("foo", "bar", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( " Expected: foo\n" " Which is: 5\n" "To be equal to: bar\n" " Which is: 6", msg1.c_str()); const std::string msg2( EqFailure("foo", "6", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( " Expected: foo\n" " Which is: 5\n" "To be equal to: 6", msg2.c_str()); const std::string msg3( EqFailure("5", "bar", foo_val, bar_val, false) .failure_message()); EXPECT_STREQ( " Expected: 5\n" "To be equal to: bar\n" " Which is: 6", msg3.c_str()); const std::string msg4( EqFailure("5", "6", foo_val, bar_val, false).failure_message()); EXPECT_STREQ( " Expected: 5\n" "To be equal to: 6", msg4.c_str()); const std::string msg5( EqFailure("foo", "bar", std::string("\"x\""), std::string("\"y\""), true).failure_message()); EXPECT_STREQ( " Expected: foo\n" " Which is: \"x\"\n" "To be equal to: bar\n" " Which is: \"y\"\n" "Ignoring case", msg5.c_str()); } TEST(AssertionTest, EqFailureWithDiff) { const std::string left( "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15"); const std::string right( "1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14"); const std::string msg1( EqFailure("left", "right", left, right, false).failure_message()); EXPECT_STREQ( " Expected: left\n" " Which is: " "1\\n2XXX\\n3\\n5\\n6\\n7\\n8\\n9\\n10\\n11\\n12XXX\\n13\\n14\\n15\n" "To be equal to: right\n" " Which is: 1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n11\\n12\\n13\\n14\n" "With diff:\n@@ -1,5 +1,6 @@\n 1\n-2XXX\n+2\n 3\n+4\n 5\n 6\n" "@@ -7,8 +8,6 @@\n 8\n 9\n-10\n 11\n-12XXX\n+12\n 13\n 14\n-15\n", msg1.c_str()); } // Tests AppendUserMessage(), used for implementing the *EQ* macros. TEST(AssertionTest, AppendUserMessage) { const std::string foo("foo"); Message msg; EXPECT_STREQ("foo", AppendUserMessage(foo, msg).c_str()); msg << "bar"; EXPECT_STREQ("foo\nbar", AppendUserMessage(foo, msg).c_str()); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch #endif // Tests ASSERT_TRUE. TEST(AssertionTest, ASSERT_TRUE) { ASSERT_TRUE(2 > 1); // NOLINT EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), "2 < 1"); } // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult. TEST(AssertionTest, AssertTrueWithAssertionResult) { ASSERT_TRUE(ResultIsEven(2)); #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)), "Value of: ResultIsEven(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); #endif ASSERT_TRUE(ResultIsEvenNoExplanation(2)); EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)), "Value of: ResultIsEvenNoExplanation(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); } // Tests ASSERT_FALSE. TEST(AssertionTest, ASSERT_FALSE) { ASSERT_FALSE(2 < 1); // NOLINT EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1), "Value of: 2 > 1\n" " Actual: true\n" "Expected: false"); } // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult. TEST(AssertionTest, AssertFalseWithAssertionResult) { ASSERT_FALSE(ResultIsEven(3)); #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)), "Value of: ResultIsEven(2)\n" " Actual: true (2 is even)\n" "Expected: false"); #endif ASSERT_FALSE(ResultIsEvenNoExplanation(3)); EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)), "Value of: ResultIsEvenNoExplanation(2)\n" " Actual: true\n" "Expected: false"); } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" supressed them # pragma option pop #endif // Tests using ASSERT_EQ on double values. The purpose is to make // sure that the specialization we did for integer and anonymous enums // isn't used for double arguments. TEST(ExpectTest, ASSERT_EQ_Double) { // A success. ASSERT_EQ(5.6, 5.6); // A failure. EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), "5.1"); } // Tests ASSERT_EQ. TEST(AssertionTest, ASSERT_EQ) { ASSERT_EQ(5, 2 + 3); EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3), " Expected: 5\n" "To be equal to: 2*3\n" " Which is: 6"); } // Tests ASSERT_EQ(NULL, pointer). #if GTEST_CAN_COMPARE_NULL TEST(AssertionTest, ASSERT_EQ_NULL) { // A success. const char* p = NULL; - // Some older GCC versions may issue a spurious waring in this or the next + // Some older GCC versions may issue a spurious warning in this or the next // assertion statement. This warning should not be suppressed with // static_cast since the test verifies the ability to use bare NULL as the // expected parameter to the macro. ASSERT_EQ(NULL, p); // A failure. static int n = 0; EXPECT_FATAL_FAILURE(ASSERT_EQ(NULL, &n), "To be equal to: &n\n"); } #endif // GTEST_CAN_COMPARE_NULL // Tests ASSERT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure // that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as // ASSERT_EQ(static_cast<void*>(NULL), non_pointer). TEST(ExpectTest, ASSERT_EQ_0) { int n = 0; // A success. ASSERT_EQ(0, n); // A failure. EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), "Expected: 0"); } // Tests ASSERT_NE. TEST(AssertionTest, ASSERT_NE) { ASSERT_NE(6, 7); EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'), "Expected: ('a') != ('a'), " "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); } // Tests ASSERT_LE. TEST(AssertionTest, ASSERT_LE) { ASSERT_LE(2, 3); ASSERT_LE(2, 2); EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); } // Tests ASSERT_LT. TEST(AssertionTest, ASSERT_LT) { ASSERT_LT(2, 3); EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); } // Tests ASSERT_GE. TEST(AssertionTest, ASSERT_GE) { ASSERT_GE(2, 1); ASSERT_GE(2, 2); EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); } // Tests ASSERT_GT. TEST(AssertionTest, ASSERT_GT) { ASSERT_GT(2, 1); EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); } #if GTEST_HAS_EXCEPTIONS void ThrowNothing() {} // Tests ASSERT_THROW. TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowAnInteger(), int); # ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of type bool.\n" " Actual: it throws a different type."); # endif EXPECT_FATAL_FAILURE( ASSERT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" " Actual: it throws nothing."); } // Tests ASSERT_NO_THROW. TEST(AssertionTest, ASSERT_NO_THROW) { ASSERT_NO_THROW(ThrowNothing()); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an exception." "\n Actual: it throws."); } // Tests ASSERT_ANY_THROW. TEST(AssertionTest, ASSERT_ANY_THROW) { ASSERT_ANY_THROW(ThrowAnInteger()); EXPECT_FATAL_FAILURE( ASSERT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS // Makes sure we deal with the precedence of <<. This test should // compile. TEST(AssertionTest, AssertPrecedence) { ASSERT_EQ(1 < 2, true); bool false_value = false; ASSERT_EQ(true && false_value, false); } // A subroutine used by the following test. void TestEq1(int x) { ASSERT_EQ(1, x); } // Tests calling a test subroutine that's not part of a fixture. TEST(AssertionTest, NonFixtureSubroutine) { EXPECT_FATAL_FAILURE(TestEq1(2), "To be equal to: x"); } // An uncopyable class. class Uncopyable { public: explicit Uncopyable(int a_value) : value_(a_value) {} int value() const { return value_; } bool operator==(const Uncopyable& rhs) const { return value() == rhs.value(); } private: // This constructor deliberately has no implementation, as we don't // want this class to be copyable. Uncopyable(const Uncopyable&); // NOLINT int value_; }; ::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) { return os << value.value(); } bool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; } // A subroutine used by the following test. void TestAssertNonPositive() { Uncopyable y(-1); ASSERT_PRED1(IsPositiveUncopyable, y); } // A subroutine used by the following test. void TestAssertEqualsUncopyable() { Uncopyable x(5); Uncopyable y(-1); ASSERT_EQ(x, y); } // Tests that uncopyable objects can be used in assertions. TEST(AssertionTest, AssertWorksWithUncopyableObject) { Uncopyable x(5); ASSERT_PRED1(IsPositiveUncopyable, x); ASSERT_EQ(x, x); EXPECT_FATAL_FAILURE(TestAssertNonPositive(), "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(), "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1"); } // Tests that uncopyable objects can be used in expects. TEST(AssertionTest, ExpectWorksWithUncopyableObject) { Uncopyable x(5); EXPECT_PRED1(IsPositiveUncopyable, x); Uncopyable y(-1); EXPECT_NONFATAL_FAILURE(EXPECT_PRED1(IsPositiveUncopyable, y), "IsPositiveUncopyable(y) evaluates to false, where\ny evaluates to -1"); EXPECT_EQ(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "Expected: x\n Which is: 5\nTo be equal to: y\n Which is: -1"); } enum NamedEnum { kE1 = 0, kE2 = 1 }; TEST(AssertionTest, NamedEnum) { EXPECT_EQ(kE1, kE1); EXPECT_LT(kE1, kE2); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 0"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), "Which is: 1"); } // The version of gcc used in XCode 2.2 has a bug and doesn't allow // anonymous enums in assertions. Therefore the following test is not // done on Mac. // Sun Studio and HP aCC also reject this code. #if !GTEST_OS_MAC && !defined(__SUNPRO_CC) && !defined(__HP_aCC) // Tests using assertions with anonymous enums. enum { kCaseA = -1, # if GTEST_OS_LINUX // We want to test the case where the size of the anonymous enum is // larger than sizeof(int), to make sure our implementation of the // assertions doesn't truncate the enums. However, MSVC // (incorrectly) doesn't allow an enum value to exceed the range of // an int, so this has to be conditionally compiled. // // On Linux, kCaseB and kCaseA have the same value when truncated to // int size. We want to test whether this will confuse the // assertions. kCaseB = testing::internal::kMaxBiggestInt, # else kCaseB = INT_MAX, # endif // GTEST_OS_LINUX kCaseC = 42 }; TEST(AssertionTest, AnonymousEnum) { # if GTEST_OS_LINUX EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB)); # endif // GTEST_OS_LINUX EXPECT_EQ(kCaseA, kCaseA); EXPECT_NE(kCaseA, kCaseB); EXPECT_LT(kCaseA, kCaseB); EXPECT_LE(kCaseA, kCaseB); EXPECT_GT(kCaseB, kCaseA); EXPECT_GE(kCaseA, kCaseA); EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), "(kCaseA) >= (kCaseB)"); EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), "-1 vs 42"); ASSERT_EQ(kCaseA, kCaseA); ASSERT_NE(kCaseA, kCaseB); ASSERT_LT(kCaseA, kCaseB); ASSERT_LE(kCaseA, kCaseB); ASSERT_GT(kCaseB, kCaseA); ASSERT_GE(kCaseA, kCaseA); # ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), "To be equal to: kCaseB"); EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "Which is: 42"); # endif EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), "Which is: -1"); } #endif // !GTEST_OS_MAC && !defined(__SUNPRO_CC) #if GTEST_OS_WINDOWS static HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; } static HRESULT OkHRESULTSuccess() { return S_OK; } static HRESULT FalseHRESULTSuccess() { return S_FALSE; } // HRESULT assertion tests test both zero and non-zero // success codes as well as failure message for each. // // Windows CE doesn't support message texts. TEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) { EXPECT_HRESULT_SUCCEEDED(S_OK); EXPECT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) { ASSERT_HRESULT_SUCCEEDED(S_OK); ASSERT_HRESULT_SUCCEEDED(S_FALSE); EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()), "Expected: (UnexpectedHRESULTFailure()) succeeds.\n" " Actual: 0x8000FFFF"); } TEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) { EXPECT_HRESULT_FAILED(E_UNEXPECTED); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()), "Expected: (OkHRESULTSuccess()) fails.\n" " Actual: 0x0"); EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()), "Expected: (FalseHRESULTSuccess()) fails.\n" " Actual: 0x1"); } TEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) { ASSERT_HRESULT_FAILED(E_UNEXPECTED); # ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()), "Expected: (OkHRESULTSuccess()) fails.\n" " Actual: 0x0"); # endif EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()), "Expected: (FalseHRESULTSuccess()) fails.\n" " Actual: 0x1"); } // Tests that streaming to the HRESULT macros works. TEST(HRESULTAssertionTest, Streaming) { EXPECT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; ASSERT_HRESULT_SUCCEEDED(S_OK) << "unexpected failure"; EXPECT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; ASSERT_HRESULT_FAILED(E_UNEXPECTED) << "unexpected failure"; EXPECT_NONFATAL_FAILURE( EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", "expected failure"); # ifndef __BORLANDC__ // ICE's in C++Builder 2007 and 2009. EXPECT_FATAL_FAILURE( ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED) << "expected failure", "expected failure"); # endif EXPECT_NONFATAL_FAILURE( EXPECT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE( ASSERT_HRESULT_FAILED(S_OK) << "expected failure", "expected failure"); } #endif // GTEST_OS_WINDOWS #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch #endif // Tests that the assertion macros behave like single statements. TEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) ASSERT_TRUE(false) << "This should never be executed; " "It's a compilation test only."; if (AlwaysTrue()) EXPECT_FALSE(false); else ; // NOLINT if (AlwaysFalse()) ASSERT_LT(1, 3); if (AlwaysFalse()) ; // NOLINT else EXPECT_GT(3, 2) << ""; } #if GTEST_HAS_EXCEPTIONS // Tests that the compiler will not complain about unreachable code in the // EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros. TEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) { int n = 0; EXPECT_THROW(throw 1, int); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), ""); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), ""); EXPECT_NO_THROW(n++); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), ""); EXPECT_ANY_THROW(throw 1); EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), ""); } TEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool); if (AlwaysTrue()) EXPECT_THROW(ThrowAnInteger(), int); else ; // NOLINT if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger()); if (AlwaysTrue()) EXPECT_NO_THROW(ThrowNothing()); else ; // NOLINT if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing()); if (AlwaysTrue()) EXPECT_ANY_THROW(ThrowAnInteger()); else ; // NOLINT } #endif // GTEST_HAS_EXCEPTIONS TEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) { if (AlwaysFalse()) EXPECT_NO_FATAL_FAILURE(FAIL()) << "This should never be executed. " << "It's a compilation test only."; else ; // NOLINT if (AlwaysFalse()) ASSERT_NO_FATAL_FAILURE(FAIL()) << ""; else ; // NOLINT if (AlwaysTrue()) EXPECT_NO_FATAL_FAILURE(SUCCEED()); else ; // NOLINT if (AlwaysFalse()) ; // NOLINT else ASSERT_NO_FATAL_FAILURE(SUCCEED()); } // Tests that the assertion macros work well with switch statements. TEST(AssertionSyntaxTest, WorksWithSwitch) { switch (0) { case 1: break; default: ASSERT_TRUE(true); } switch (0) case 0: EXPECT_FALSE(false) << "EXPECT_FALSE failed in switch case"; // Binary assertions are implemented using a different code path // than the Boolean assertions. Hence we test them separately. switch (0) { case 1: default: ASSERT_EQ(1, 1) << "ASSERT_EQ failed in default switch handler"; } switch (0) case 0: EXPECT_NE(1, 2); } #if GTEST_HAS_EXCEPTIONS void ThrowAString() { throw "std::string"; } // Test that the exception assertion macros compile and work with const // type qualifier. TEST(AssertionSyntaxTest, WorksWithConst) { ASSERT_THROW(ThrowAString(), const char*); EXPECT_THROW(ThrowAString(), const char*); } #endif // GTEST_HAS_EXCEPTIONS } // namespace namespace testing { // Tests that Google Test tracks SUCCEED*. TEST(SuccessfulAssertionTest, SUCCEED) { SUCCEED(); SUCCEED() << "OK"; EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful EXPECT_*. TEST(SuccessfulAssertionTest, EXPECT) { EXPECT_TRUE(true); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful EXPECT_STR*. TEST(SuccessfulAssertionTest, EXPECT_STR) { EXPECT_STREQ("", ""); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful ASSERT_*. TEST(SuccessfulAssertionTest, ASSERT) { ASSERT_TRUE(true); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } // Tests that Google Test doesn't track successful ASSERT_STR*. TEST(SuccessfulAssertionTest, ASSERT_STR) { ASSERT_STREQ("", ""); EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count()); } } // namespace testing namespace { // Tests the message streaming variation of assertions. TEST(AssertionWithMessageTest, EXPECT) { EXPECT_EQ(1, 1) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << "Expected failure #1.", "Expected failure #1"); EXPECT_LE(1, 2) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << "Expected failure #2.", "Expected failure #2."); EXPECT_GE(1, 0) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << "Expected failure #3.", "Expected failure #3."); EXPECT_STREQ("1", "1") << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("1", "1") << "Expected failure #4.", "Expected failure #4."); EXPECT_STRCASEEQ("a", "A") << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("a", "A") << "Expected failure #5.", "Expected failure #5."); EXPECT_FLOAT_EQ(1, 1) << "This should succeed."; EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << "Expected failure #6.", "Expected failure #6."); EXPECT_NEAR(1, 1.1, 0.2) << "This should succeed."; } TEST(AssertionWithMessageTest, ASSERT) { ASSERT_EQ(1, 1) << "This should succeed."; ASSERT_NE(1, 2) << "This should succeed."; ASSERT_LE(1, 2) << "This should succeed."; ASSERT_LT(1, 2) << "This should succeed."; ASSERT_GE(1, 0) << "This should succeed."; EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << "Expected failure.", "Expected failure."); } TEST(AssertionWithMessageTest, ASSERT_STR) { ASSERT_STREQ("1", "1") << "This should succeed."; ASSERT_STRNE("1", "2") << "This should succeed."; ASSERT_STRCASEEQ("a", "A") << "This should succeed."; EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("a", "A") << "Expected failure.", "Expected failure."); } TEST(AssertionWithMessageTest, ASSERT_FLOATING) { ASSERT_FLOAT_EQ(1, 1) << "This should succeed."; ASSERT_DOUBLE_EQ(1, 1) << "This should succeed."; EXPECT_FATAL_FAILURE(ASSERT_NEAR(1,1.2, 0.1) << "Expect failure.", // NOLINT "Expect failure."); // To work around a bug in gcc 2.95.0, there is intentionally no // space after the first comma in the previous statement. } // Tests using ASSERT_FALSE with a streamed message. TEST(AssertionWithMessageTest, ASSERT_FALSE) { ASSERT_FALSE(false) << "This shouldn't fail."; EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_FALSE(true) << "Expected failure: " << 2 << " > " << 1 << " evaluates to " << true; }, "Expected failure"); } // Tests using FAIL with a streamed message. TEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, "0"); } // Tests using SUCCEED with a streamed message. TEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << "Success == " << 1; } // Tests using ASSERT_TRUE with a streamed message. TEST(AssertionWithMessageTest, ASSERT_TRUE) { ASSERT_TRUE(true) << "This should succeed."; ASSERT_TRUE(true) << true; EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_TRUE(false) << static_cast<const char *>(NULL) << static_cast<char *>(NULL); }, "(null)(null)"); } #if GTEST_OS_WINDOWS // Tests using wide strings in assertion messages. TEST(AssertionWithMessageTest, WideStringMessage) { EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_TRUE(false) << L"This failure is expected.\x8119"; }, "This failure is expected."); EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_EQ(1, 2) << "This failure is " << L"expected too.\x8120"; }, "This failure is expected too."); } #endif // GTEST_OS_WINDOWS // Tests EXPECT_TRUE. TEST(ExpectTest, EXPECT_TRUE) { EXPECT_TRUE(true) << "Intentional success"; EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #1.", "Intentional failure #1."); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "Intentional failure #2.", "Intentional failure #2."); EXPECT_TRUE(2 > 1); // NOLINT EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1), "Value of: 2 < 1\n" " Actual: false\n" "Expected: true"); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), "2 > 3"); } // Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult. TEST(ExpectTest, ExpectTrueWithAssertionResult) { EXPECT_TRUE(ResultIsEven(2)); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)), "Value of: ResultIsEven(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); EXPECT_TRUE(ResultIsEvenNoExplanation(2)); EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)), "Value of: ResultIsEvenNoExplanation(3)\n" " Actual: false (3 is odd)\n" "Expected: true"); } // Tests EXPECT_FALSE with a streamed message. TEST(ExpectTest, EXPECT_FALSE) { EXPECT_FALSE(2 < 1); // NOLINT EXPECT_FALSE(false) << "Intentional success"; EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #1.", "Intentional failure #1."); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "Intentional failure #2.", "Intentional failure #2."); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1), "Value of: 2 > 1\n" " Actual: true\n" "Expected: false"); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), "2 < 3"); } // Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult. TEST(ExpectTest, ExpectFalseWithAssertionResult) { EXPECT_FALSE(ResultIsEven(3)); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)), "Value of: ResultIsEven(2)\n" " Actual: true (2 is even)\n" "Expected: false"); EXPECT_FALSE(ResultIsEvenNoExplanation(3)); EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)), "Value of: ResultIsEvenNoExplanation(2)\n" " Actual: true\n" "Expected: false"); } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" supressed them # pragma option pop #endif // Tests EXPECT_EQ. TEST(ExpectTest, EXPECT_EQ) { EXPECT_EQ(5, 2 + 3); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3), " Expected: 5\n" "To be equal to: 2*3\n" " Which is: 6"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), "2 - 3"); } // Tests using EXPECT_EQ on double values. The purpose is to make // sure that the specialization we did for integer and anonymous enums // isn't used for double arguments. TEST(ExpectTest, EXPECT_EQ_Double) { // A success. EXPECT_EQ(5.6, 5.6); // A failure. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), "5.1"); } #if GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(NULL, pointer). TEST(ExpectTest, EXPECT_EQ_NULL) { // A success. const char* p = NULL; // Some older GCC versions may issue a spurious warning in this or the next // assertion statement. This warning should not be suppressed with // static_cast since the test verifies the ability to use bare NULL as the // expected parameter to the macro. EXPECT_EQ(NULL, p); // A failure. int n = 0; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(NULL, &n), "To be equal to: &n\n"); } #endif // GTEST_CAN_COMPARE_NULL // Tests EXPECT_EQ(0, non_pointer). Since the literal 0 can be // treated as a null pointer by the compiler, we need to make sure // that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as // EXPECT_EQ(static_cast<void*>(NULL), non_pointer). TEST(ExpectTest, EXPECT_EQ_0) { int n = 0; // A success. EXPECT_EQ(0, n); // A failure. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), "Expected: 0"); } // Tests EXPECT_NE. TEST(ExpectTest, EXPECT_NE) { EXPECT_NE(6, 7); EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'), "Expected: ('a') != ('a'), " "actual: 'a' (97, 0x61) vs 'a' (97, 0x61)"); EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), "2"); char* const p0 = NULL; EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), "p0"); // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does // a direct C-style to char*. void* pv1 = (void*)0x1234; // NOLINT char* const p1 = reinterpret_cast<char*>(pv1); EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), "p1"); } // Tests EXPECT_LE. TEST(ExpectTest, EXPECT_LE) { EXPECT_LE(2, 3); EXPECT_LE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0), "Expected: (2) <= (0), actual: 2 vs 0"); EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), "(1.1) <= (0.9)"); } // Tests EXPECT_LT. TEST(ExpectTest, EXPECT_LT) { EXPECT_LT(2, 3); EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2), "Expected: (2) < (2), actual: 2 vs 2"); EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), "(2) < (1)"); } // Tests EXPECT_GE. TEST(ExpectTest, EXPECT_GE) { EXPECT_GE(2, 1); EXPECT_GE(2, 2); EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3), "Expected: (2) >= (3), actual: 2 vs 3"); EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), "(0.9) >= (1.1)"); } // Tests EXPECT_GT. TEST(ExpectTest, EXPECT_GT) { EXPECT_GT(2, 1); EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2), "Expected: (2) > (2), actual: 2 vs 2"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), "(2) > (3)"); } #if GTEST_HAS_EXCEPTIONS // Tests EXPECT_THROW. TEST(ExpectTest, EXPECT_THROW) { EXPECT_THROW(ThrowAnInteger(), int); EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool), "Expected: ThrowAnInteger() throws an exception of " "type bool.\n Actual: it throws a different type."); EXPECT_NONFATAL_FAILURE( EXPECT_THROW(ThrowNothing(), bool), "Expected: ThrowNothing() throws an exception of type bool.\n" " Actual: it throws nothing."); } // Tests EXPECT_NO_THROW. TEST(ExpectTest, EXPECT_NO_THROW) { EXPECT_NO_THROW(ThrowNothing()); EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()), "Expected: ThrowAnInteger() doesn't throw an " "exception.\n Actual: it throws."); } // Tests EXPECT_ANY_THROW. TEST(ExpectTest, EXPECT_ANY_THROW) { EXPECT_ANY_THROW(ThrowAnInteger()); EXPECT_NONFATAL_FAILURE( EXPECT_ANY_THROW(ThrowNothing()), "Expected: ThrowNothing() throws an exception.\n" " Actual: it doesn't."); } #endif // GTEST_HAS_EXCEPTIONS // Make sure we deal with the precedence of <<. TEST(ExpectTest, ExpectPrecedence) { EXPECT_EQ(1 < 2, true); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false), "To be equal to: true && false"); } // Tests the StreamableToString() function. // Tests using StreamableToString() on a scalar. TEST(StreamableToStringTest, Scalar) { EXPECT_STREQ("5", StreamableToString(5).c_str()); } // Tests using StreamableToString() on a non-char pointer. TEST(StreamableToStringTest, Pointer) { int n = 0; int* p = &n; EXPECT_STRNE("(null)", StreamableToString(p).c_str()); } // Tests using StreamableToString() on a NULL non-char pointer. TEST(StreamableToStringTest, NullPointer) { int* p = NULL; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } // Tests using StreamableToString() on a C string. TEST(StreamableToStringTest, CString) { EXPECT_STREQ("Foo", StreamableToString("Foo").c_str()); } // Tests using StreamableToString() on a NULL C string. TEST(StreamableToStringTest, NullCString) { char* p = NULL; EXPECT_STREQ("(null)", StreamableToString(p).c_str()); } // Tests using streamable values as assertion messages. // Tests using std::string as an assertion message. TEST(StreamableTest, string) { static const std::string str( "This failure message is a std::string, and is expected."); EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str()); } // Tests that we can output strings containing embedded NULs. // Limited to Linux because we can only do this with std::string's. TEST(StreamableTest, stringWithEmbeddedNUL) { static const char char_array_with_nul[] = "Here's a NUL\0 and some more string"; static const std::string string_with_nul(char_array_with_nul, sizeof(char_array_with_nul) - 1); // drops the trailing NUL EXPECT_FATAL_FAILURE(FAIL() << string_with_nul, "Here's a NUL\\0 and some more string"); } // Tests that we can output a NUL char. TEST(StreamableTest, NULChar) { EXPECT_FATAL_FAILURE({ // NOLINT FAIL() << "A NUL" << '\0' << " and some more string"; }, "A NUL\\0 and some more string"); } // Tests using int as an assertion message. TEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, "900913"); } // Tests using NULL char pointer as an assertion message. // // In MSVC, streaming a NULL char * causes access violation. Google Test // implemented a workaround (substituting "(null)" for NULL). This // tests whether the workaround works. TEST(StreamableTest, NullCharPtr) { EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(NULL), "(null)"); } // Tests that basic IO manipulators (endl, ends, and flush) can be // streamed to testing::Message. TEST(StreamableTest, BasicIoManip) { EXPECT_FATAL_FAILURE({ // NOLINT FAIL() << "Line 1." << std::endl << "A NUL char " << std::ends << std::flush << " in line 2."; }, "Line 1.\nA NUL char \\0 in line 2."); } // Tests the macros that haven't been covered so far. void AddFailureHelper(bool* aborted) { *aborted = true; ADD_FAILURE() << "Intentional failure."; *aborted = false; } // Tests ADD_FAILURE. TEST(MacroTest, ADD_FAILURE) { bool aborted = true; EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), "Intentional failure."); EXPECT_FALSE(aborted); } // Tests ADD_FAILURE_AT. TEST(MacroTest, ADD_FAILURE_AT) { // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and // the failure message contains the user-streamed part. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42) << "Wrong!", "Wrong!"); // Verifies that the user-streamed part is optional. EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT("foo.cc", 42), "Failed"); // Unfortunately, we cannot verify that the failure message contains // the right file path and line number the same way, as // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and // line number. Instead, we do that in gtest_output_test_.cc. } // Tests FAIL. TEST(MacroTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL(), "Failed"); EXPECT_FATAL_FAILURE(FAIL() << "Intentional failure.", "Intentional failure."); } // Tests SUCCEED TEST(MacroTest, SUCCEED) { SUCCEED(); SUCCEED() << "Explicit success."; } // Tests for EXPECT_EQ() and ASSERT_EQ(). // // These tests fail *intentionally*, s.t. the failure messages can be // generated and tested. // // We have different tests for different argument types. // Tests using bool values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Bool) { EXPECT_EQ(true, true); EXPECT_FATAL_FAILURE({ bool false_value = false; ASSERT_EQ(false_value, true); }, "To be equal to: true"); } // Tests using int values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Int) { ASSERT_EQ(32, 32); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), "33"); } // Tests using time_t values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Time_T) { EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0)); EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), "1234"); } // Tests using char values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, Char) { ASSERT_EQ('z', 'z'); const char ch = 'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\0', ch), "ch"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), "ch"); } // Tests using wchar_t values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, WideChar) { EXPECT_EQ(L'b', L'b'); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\0', L'x'), " Expected: L'\0'\n" " Which is: L'\0' (0, 0x0)\n" "To be equal to: L'x'\n" " Which is: L'x' (120, 0x78)"); static wchar_t wchar; wchar = L'b'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), "wchar"); wchar = 0x8119; EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar), "To be equal to: wchar"); } // Tests using ::std::string values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, StdString) { // Compares a const char* to an std::string that has identical // content. ASSERT_EQ("Test", ::std::string("Test")); // Compares two identical std::strings. static const ::std::string str1("A * in the middle"); static const ::std::string str2(str1); EXPECT_EQ(str1, str2); // Compares a const char* to an std::string that has different // content EXPECT_NONFATAL_FAILURE(EXPECT_EQ("Test", ::std::string("test")), "\"test\""); // Compares an std::string to a char* that has different content. char* const p1 = const_cast<char*>("foo"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string("bar"), p1), "p1"); // Compares two std::strings that have different contents, one of // which having a NUL character in the middle. This should fail. static ::std::string str3(str1); str3.at(2) = '\0'; EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3), "To be equal to: str3\n" " Which is: \"A \\0 in the middle\""); } #if GTEST_HAS_STD_WSTRING // Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, StdWideString) { // Compares two identical std::wstrings. const ::std::wstring wstr1(L"A * in the middle"); const ::std::wstring wstr2(wstr1); ASSERT_EQ(wstr1, wstr2); // Compares an std::wstring to a const wchar_t* that has identical // content. const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119); // Compares an std::wstring to a const wchar_t* that has different // content. const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120); }, "kTestX8120"); // Compares two std::wstrings that have different contents, one of // which having a NUL character in the middle. ::std::wstring wstr3(wstr1); wstr3.at(2) = L'\0'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), "wstr3"); // Compares a wchar_t* to an std::wstring that has different // content. EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_EQ(const_cast<wchar_t*>(L"foo"), ::std::wstring(L"bar")); }, ""); } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_STRING // Tests using ::string values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, GlobalString) { // Compares a const char* to a ::string that has identical content. EXPECT_EQ("Test", ::string("Test")); // Compares two identical ::strings. const ::string str1("A * in the middle"); const ::string str2(str1); ASSERT_EQ(str1, str2); // Compares a ::string to a const char* that has different content. EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::string("Test"), "test"), "test"); // Compares two ::strings that have different contents, one of which // having a NUL character in the middle. ::string str3(str1); str3.at(2) = '\0'; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(str1, str3), "str3"); // Compares a ::string to a char* that has different content. EXPECT_FATAL_FAILURE({ // NOLINT ASSERT_EQ(::string("bar"), const_cast<char*>("foo")); }, ""); } #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING // Tests using ::wstring values in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, GlobalWideString) { // Compares two identical ::wstrings. static const ::wstring wstr1(L"A * in the middle"); static const ::wstring wstr2(wstr1); EXPECT_EQ(wstr1, wstr2); // Compares a const wchar_t* to a ::wstring that has identical content. const wchar_t kTestX8119[] = { 'T', 'e', 's', 't', 0x8119, '\0' }; ASSERT_EQ(kTestX8119, ::wstring(kTestX8119)); // Compares a const wchar_t* to a ::wstring that has different // content. const wchar_t kTestX8120[] = { 'T', 'e', 's', 't', 0x8120, '\0' }; EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_EQ(kTestX8120, ::wstring(kTestX8119)); }, "Test\\x8119"); // Compares a wchar_t* to a ::wstring that has different content. wchar_t* const p1 = const_cast<wchar_t*>(L"foo"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, ::wstring(L"bar")), "bar"); // Compares two ::wstrings that have different contents, one of which // having a NUL character in the middle. static ::wstring wstr3; wstr3 = wstr1; wstr3.at(2) = L'\0'; EXPECT_FATAL_FAILURE(ASSERT_EQ(wstr1, wstr3), "wstr3"); } #endif // GTEST_HAS_GLOBAL_WSTRING // Tests using char pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, CharPointer) { char* const p0 = NULL; // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does // a direct C-style to char*. void* pv1 = (void*)0x1234; // NOLINT void* pv2 = (void*)0xABC0; // NOLINT char* const p1 = reinterpret_cast<char*>(pv1); char* const p2 = reinterpret_cast<char*>(pv2); ASSERT_EQ(p1, p1); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), "To be equal to: p2"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), "p2"); EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234), reinterpret_cast<char*>(0xABC0)), "ABC0"); } // Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, WideCharPointer) { wchar_t* const p0 = NULL; // Only way to get the Nokia compiler to compile the cast // is to have a separate void* variable first. Putting // the two casts on the same line doesn't work, neither does // a direct C-style to char*. void* pv1 = (void*)0x1234; // NOLINT void* pv2 = (void*)0xABC0; // NOLINT wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1); wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2); EXPECT_EQ(p0, p0); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), "To be equal to: p2"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), "p2"); void* pv3 = (void*)0x1234; // NOLINT void* pv4 = (void*)0xABC0; // NOLINT const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3); const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), "p4"); } // Tests using other types of pointers in {EXPECT|ASSERT}_EQ. TEST(EqAssertionTest, OtherPointer) { ASSERT_EQ(static_cast<const int*>(NULL), static_cast<const int*>(NULL)); EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(NULL), reinterpret_cast<const int*>(0x1234)), "0x1234"); } // A class that supports binary comparison operators but not streaming. class UnprintableChar { public: explicit UnprintableChar(char ch) : char_(ch) {} bool operator==(const UnprintableChar& rhs) const { return char_ == rhs.char_; } bool operator!=(const UnprintableChar& rhs) const { return char_ != rhs.char_; } bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; } bool operator<=(const UnprintableChar& rhs) const { return char_ <= rhs.char_; } bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; } bool operator>=(const UnprintableChar& rhs) const { return char_ >= rhs.char_; } private: char char_; }; // Tests that ASSERT_EQ() and friends don't require the arguments to // be printable. TEST(ComparisonAssertionTest, AcceptsUnprintableArgs) { const UnprintableChar x('x'), y('y'); ASSERT_EQ(x, x); EXPECT_NE(x, y); ASSERT_LT(x, y); EXPECT_LE(x, y); ASSERT_GT(y, x); EXPECT_GE(x, x); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <78>"); EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), "1-byte object <79>"); EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), "1-byte object <79>"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <78>"); EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), "1-byte object <79>"); // Code tested by EXPECT_FATAL_FAILURE cannot reference local // variables, so we have to write UnprintableChar('x') instead of x. #ifndef __BORLANDC__ // ICE's in C++Builder. EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')), "1-byte object <78>"); EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), "1-byte object <78>"); #endif EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')), "1-byte object <79>"); EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), "1-byte object <78>"); EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')), "1-byte object <79>"); } // Tests the FRIEND_TEST macro. // This class has a private member we want to test. We will test it // both in a TEST and in a TEST_F. class Foo { public: Foo() {} private: int Bar() const { return 1; } // Declares the friend tests that can access the private member // Bar(). FRIEND_TEST(FRIEND_TEST_Test, TEST); FRIEND_TEST(FRIEND_TEST_Test2, TEST_F); }; // Tests that the FRIEND_TEST declaration allows a TEST to access a // class's private members. This should compile. TEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); } // The fixture needed to test using FRIEND_TEST with TEST_F. class FRIEND_TEST_Test2 : public Test { protected: Foo foo; }; // Tests that the FRIEND_TEST declaration allows a TEST_F to access a // class's private members. This should compile. TEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); } // Tests the life cycle of Test objects. // The test fixture for testing the life cycle of Test objects. // // This class counts the number of live test objects that uses this // fixture. class TestLifeCycleTest : public Test { protected: // Constructor. Increments the number of test objects that uses // this fixture. TestLifeCycleTest() { count_++; } // Destructor. Decrements the number of test objects that uses this // fixture. ~TestLifeCycleTest() { count_--; } // Returns the number of live test objects that uses this fixture. int count() const { return count_; } private: static int count_; }; int TestLifeCycleTest::count_ = 0; // Tests the life cycle of test objects. TEST_F(TestLifeCycleTest, Test1) { // There should be only one test object in this test case that's // currently alive. ASSERT_EQ(1, count()); } // Tests the life cycle of test objects. TEST_F(TestLifeCycleTest, Test2) { // After Test1 is done and Test2 is started, there should still be // only one live test object, as the object for Test1 should've been // deleted. ASSERT_EQ(1, count()); } } // namespace // Tests that the copy constructor works when it is NOT optimized away by // the compiler. TEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) { // Checks that the copy constructor doesn't try to dereference NULL pointers // in the source object. AssertionResult r1 = AssertionSuccess(); AssertionResult r2 = r1; // The following line is added to prevent the compiler from optimizing // away the constructor call. r1 << "abc"; AssertionResult r3 = r1; EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1)); EXPECT_STREQ("abc", r1.message()); } // Tests that AssertionSuccess and AssertionFailure construct // AssertionResult objects as expected. TEST(AssertionResultTest, ConstructionWorks) { AssertionResult r1 = AssertionSuccess(); EXPECT_TRUE(r1); EXPECT_STREQ("", r1.message()); AssertionResult r2 = AssertionSuccess() << "abc"; EXPECT_TRUE(r2); EXPECT_STREQ("abc", r2.message()); AssertionResult r3 = AssertionFailure(); EXPECT_FALSE(r3); EXPECT_STREQ("", r3.message()); AssertionResult r4 = AssertionFailure() << "def"; EXPECT_FALSE(r4); EXPECT_STREQ("def", r4.message()); AssertionResult r5 = AssertionFailure(Message() << "ghi"); EXPECT_FALSE(r5); EXPECT_STREQ("ghi", r5.message()); } // Tests that the negation flips the predicate result but keeps the message. TEST(AssertionResultTest, NegationWorks) { AssertionResult r1 = AssertionSuccess() << "abc"; EXPECT_FALSE(!r1); EXPECT_STREQ("abc", (!r1).message()); AssertionResult r2 = AssertionFailure() << "def"; EXPECT_TRUE(!r2); EXPECT_STREQ("def", (!r2).message()); } TEST(AssertionResultTest, StreamingWorks) { AssertionResult r = AssertionSuccess(); r << "abc" << 'd' << 0 << true; EXPECT_STREQ("abcd0true", r.message()); } TEST(AssertionResultTest, CanStreamOstreamManipulators) { AssertionResult r = AssertionSuccess(); r << "Data" << std::endl << std::flush << std::ends << "Will be visible"; EXPECT_STREQ("Data\n\\0Will be visible", r.message()); } // The next test uses explicit conversion operators -- a C++11 feature. #if GTEST_LANG_CXX11 TEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) { struct ExplicitlyConvertibleToBool { explicit operator bool() const { return value; } bool value; }; ExplicitlyConvertibleToBool v1 = {false}; ExplicitlyConvertibleToBool v2 = {true}; EXPECT_FALSE(v1); EXPECT_TRUE(v2); } #endif // GTEST_LANG_CXX11 struct ConvertibleToAssertionResult { operator AssertionResult() const { return AssertionResult(true); } }; TEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) { ConvertibleToAssertionResult obj; EXPECT_TRUE(obj); } // Tests streaming a user type whose definition and operator << are // both in the global namespace. class Base { public: explicit Base(int an_x) : x_(an_x) {} int x() const { return x_; } private: int x_; }; std::ostream& operator<<(std::ostream& os, const Base& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const Base* pointer) { return os << "(" << pointer->x() << ")"; } TEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) { Message msg; Base a(1); msg << a << &a; // Uses ::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming a user type whose definition and operator<< are // both in an unnamed namespace. namespace { class MyTypeInUnnamedNameSpace : public Base { public: explicit MyTypeInUnnamedNameSpace(int an_x): Base(an_x) {} }; std::ostream& operator<<(std::ostream& os, const MyTypeInUnnamedNameSpace& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const MyTypeInUnnamedNameSpace* pointer) { return os << "(" << pointer->x() << ")"; } } // namespace TEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) { Message msg; MyTypeInUnnamedNameSpace a(1); msg << a << &a; // Uses <unnamed_namespace>::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming a user type whose definition and operator<< are // both in a user namespace. namespace namespace1 { class MyTypeInNameSpace1 : public Base { public: explicit MyTypeInNameSpace1(int an_x): Base(an_x) {} }; std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) { return os << "(" << pointer->x() << ")"; } } // namespace namespace1 TEST(MessageTest, CanStreamUserTypeInUserNameSpace) { Message msg; namespace1::MyTypeInNameSpace1 a(1); msg << a << &a; // Uses namespace1::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming a user type whose definition is in a user namespace // but whose operator<< is in the global namespace. namespace namespace2 { class MyTypeInNameSpace2 : public ::Base { public: explicit MyTypeInNameSpace2(int an_x): Base(an_x) {} }; } // namespace namespace2 std::ostream& operator<<(std::ostream& os, const namespace2::MyTypeInNameSpace2& val) { return os << val.x(); } std::ostream& operator<<(std::ostream& os, const namespace2::MyTypeInNameSpace2* pointer) { return os << "(" << pointer->x() << ")"; } TEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) { Message msg; namespace2::MyTypeInNameSpace2 a(1); msg << a << &a; // Uses ::operator<<. EXPECT_STREQ("1(1)", msg.GetString().c_str()); } // Tests streaming NULL pointers to testing::Message. TEST(MessageTest, NullPointers) { Message msg; char* const p1 = NULL; unsigned char* const p2 = NULL; int* p3 = NULL; double* p4 = NULL; bool* p5 = NULL; Message* p6 = NULL; msg << p1 << p2 << p3 << p4 << p5 << p6; ASSERT_STREQ("(null)(null)(null)(null)(null)(null)", msg.GetString().c_str()); } // Tests streaming wide strings to testing::Message. TEST(MessageTest, WideStrings) { // Streams a NULL of type const wchar_t*. const wchar_t* const_wstr = NULL; EXPECT_STREQ("(null)", (Message() << const_wstr).GetString().c_str()); // Streams a NULL of type wchar_t*. wchar_t* wstr = NULL; EXPECT_STREQ("(null)", (Message() << wstr).GetString().c_str()); // Streams a non-NULL of type const wchar_t*. const_wstr = L"abc\x8119"; EXPECT_STREQ("abc\xe8\x84\x99", (Message() << const_wstr).GetString().c_str()); // Streams a non-NULL of type wchar_t*. wstr = const_cast<wchar_t*>(const_wstr); EXPECT_STREQ("abc\xe8\x84\x99", (Message() << wstr).GetString().c_str()); } // This line tests that we can define tests in the testing namespace. namespace testing { // Tests the TestInfo class. class TestInfoTest : public Test { protected: static const TestInfo* GetTestInfo(const char* test_name) { const TestCase* const test_case = GetUnitTestImpl()-> GetTestCase("TestInfoTest", "", NULL, NULL); for (int i = 0; i < test_case->total_test_count(); ++i) { const TestInfo* const test_info = test_case->GetTestInfo(i); if (strcmp(test_name, test_info->name()) == 0) return test_info; } return NULL; } static const TestResult* GetTestResult( const TestInfo* test_info) { return test_info->result(); } }; // Tests TestInfo::test_case_name() and TestInfo::name(). TEST_F(TestInfoTest, Names) { const TestInfo* const test_info = GetTestInfo("Names"); ASSERT_STREQ("TestInfoTest", test_info->test_case_name()); ASSERT_STREQ("Names", test_info->name()); } // Tests TestInfo::result(). TEST_F(TestInfoTest, result) { const TestInfo* const test_info = GetTestInfo("result"); // Initially, there is no TestPartResult for this test. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); // After the previous assertion, there is still none. ASSERT_EQ(0, GetTestResult(test_info)->total_part_count()); } #define VERIFY_CODE_LOCATION \ const int expected_line = __LINE__ - 1; \ const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \ ASSERT_TRUE(test_info); \ EXPECT_STREQ(__FILE__, test_info->file()); \ EXPECT_EQ(expected_line, test_info->line()) TEST(CodeLocationForTEST, Verify) { VERIFY_CODE_LOCATION; } class CodeLocationForTESTF : public Test { }; TEST_F(CodeLocationForTESTF, Verify) { VERIFY_CODE_LOCATION; } class CodeLocationForTESTP : public TestWithParam<int> { }; TEST_P(CodeLocationForTESTP, Verify) { VERIFY_CODE_LOCATION; } INSTANTIATE_TEST_CASE_P(, CodeLocationForTESTP, Values(0)); template <typename T> class CodeLocationForTYPEDTEST : public Test { }; TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int); TYPED_TEST(CodeLocationForTYPEDTEST, Verify) { VERIFY_CODE_LOCATION; } template <typename T> class CodeLocationForTYPEDTESTP : public Test { }; TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP); TYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) { VERIFY_CODE_LOCATION; } REGISTER_TYPED_TEST_CASE_P(CodeLocationForTYPEDTESTP, Verify); INSTANTIATE_TYPED_TEST_CASE_P(My, CodeLocationForTYPEDTESTP, int); #undef VERIFY_CODE_LOCATION // Tests setting up and tearing down a test case. class SetUpTestCaseTest : public Test { protected: // This will be called once before the first test in this test case // is run. static void SetUpTestCase() { printf("Setting up the test case . . .\n"); // Initializes some shared resource. In this simple example, we // just create a C string. More complex stuff can be done if // desired. shared_resource_ = "123"; // Increments the number of test cases that have been set up. counter_++; // SetUpTestCase() should be called only once. EXPECT_EQ(1, counter_); } // This will be called once after the last test in this test case is // run. static void TearDownTestCase() { printf("Tearing down the test case . . .\n"); // Decrements the number of test cases that have been set up. counter_--; // TearDownTestCase() should be called only once. EXPECT_EQ(0, counter_); // Cleans up the shared resource. shared_resource_ = NULL; } // This will be called before each test in this test case. virtual void SetUp() { // SetUpTestCase() should be called only once, so counter_ should // always be 1. EXPECT_EQ(1, counter_); } // Number of test cases that have been set up. static int counter_; // Some resource to be shared by all tests in this test case. static const char* shared_resource_; }; int SetUpTestCaseTest::counter_ = 0; const char* SetUpTestCaseTest::shared_resource_ = NULL; // A test that uses the shared resource. TEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(NULL, shared_resource_); } // Another test that uses the shared resource. TEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ("123", shared_resource_); } // The InitGoogleTestTest test case tests testing::InitGoogleTest(). // The Flags struct stores a copy of all Google Test flags. struct Flags { // Constructs a Flags struct where each flag has its default value. Flags() : also_run_disabled_tests(false), break_on_failure(false), catch_exceptions(false), death_test_use_fork(false), filter(""), list_tests(false), output(""), print_time(true), random_seed(0), repeat(1), shuffle(false), stack_trace_depth(kMaxStackTraceDepth), stream_result_to(""), throw_on_failure(false) {} // Factory methods. // Creates a Flags struct where the gtest_also_run_disabled_tests flag has // the given value. static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) { Flags flags; flags.also_run_disabled_tests = also_run_disabled_tests; return flags; } // Creates a Flags struct where the gtest_break_on_failure flag has // the given value. static Flags BreakOnFailure(bool break_on_failure) { Flags flags; flags.break_on_failure = break_on_failure; return flags; } // Creates a Flags struct where the gtest_catch_exceptions flag has // the given value. static Flags CatchExceptions(bool catch_exceptions) { Flags flags; flags.catch_exceptions = catch_exceptions; return flags; } // Creates a Flags struct where the gtest_death_test_use_fork flag has // the given value. static Flags DeathTestUseFork(bool death_test_use_fork) { Flags flags; flags.death_test_use_fork = death_test_use_fork; return flags; } // Creates a Flags struct where the gtest_filter flag has the given // value. static Flags Filter(const char* filter) { Flags flags; flags.filter = filter; return flags; } // Creates a Flags struct where the gtest_list_tests flag has the // given value. static Flags ListTests(bool list_tests) { Flags flags; flags.list_tests = list_tests; return flags; } // Creates a Flags struct where the gtest_output flag has the given // value. static Flags Output(const char* output) { Flags flags; flags.output = output; return flags; } // Creates a Flags struct where the gtest_print_time flag has the given // value. static Flags PrintTime(bool print_time) { Flags flags; flags.print_time = print_time; return flags; } // Creates a Flags struct where the gtest_random_seed flag has // the given value. static Flags RandomSeed(Int32 random_seed) { Flags flags; flags.random_seed = random_seed; return flags; } // Creates a Flags struct where the gtest_repeat flag has the given // value. static Flags Repeat(Int32 repeat) { Flags flags; flags.repeat = repeat; return flags; } // Creates a Flags struct where the gtest_shuffle flag has // the given value. static Flags Shuffle(bool shuffle) { Flags flags; flags.shuffle = shuffle; return flags; } // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has // the given value. static Flags StackTraceDepth(Int32 stack_trace_depth) { Flags flags; flags.stack_trace_depth = stack_trace_depth; return flags; } // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has // the given value. static Flags StreamResultTo(const char* stream_result_to) { Flags flags; flags.stream_result_to = stream_result_to; return flags; } // Creates a Flags struct where the gtest_throw_on_failure flag has // the given value. static Flags ThrowOnFailure(bool throw_on_failure) { Flags flags; flags.throw_on_failure = throw_on_failure; return flags; } // These fields store the flag values. bool also_run_disabled_tests; bool break_on_failure; bool catch_exceptions; bool death_test_use_fork; const char* filter; bool list_tests; const char* output; bool print_time; Int32 random_seed; Int32 repeat; bool shuffle; Int32 stack_trace_depth; const char* stream_result_to; bool throw_on_failure; }; // Fixture for testing InitGoogleTest(). class InitGoogleTestTest : public Test { protected: // Clears the flags before each test. virtual void SetUp() { GTEST_FLAG(also_run_disabled_tests) = false; GTEST_FLAG(break_on_failure) = false; GTEST_FLAG(catch_exceptions) = false; GTEST_FLAG(death_test_use_fork) = false; GTEST_FLAG(filter) = ""; GTEST_FLAG(list_tests) = false; GTEST_FLAG(output) = ""; GTEST_FLAG(print_time) = true; GTEST_FLAG(random_seed) = 0; GTEST_FLAG(repeat) = 1; GTEST_FLAG(shuffle) = false; GTEST_FLAG(stack_trace_depth) = kMaxStackTraceDepth; GTEST_FLAG(stream_result_to) = ""; GTEST_FLAG(throw_on_failure) = false; } // Asserts that two narrow or wide string arrays are equal. template <typename CharType> static void AssertStringArrayEq(size_t size1, CharType** array1, size_t size2, CharType** array2) { ASSERT_EQ(size1, size2) << " Array sizes different."; for (size_t i = 0; i != size1; i++) { ASSERT_STREQ(array1[i], array2[i]) << " where i == " << i; } } // Verifies that the flag values match the expected values. static void CheckFlags(const Flags& expected) { EXPECT_EQ(expected.also_run_disabled_tests, GTEST_FLAG(also_run_disabled_tests)); EXPECT_EQ(expected.break_on_failure, GTEST_FLAG(break_on_failure)); EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG(catch_exceptions)); EXPECT_EQ(expected.death_test_use_fork, GTEST_FLAG(death_test_use_fork)); EXPECT_STREQ(expected.filter, GTEST_FLAG(filter).c_str()); EXPECT_EQ(expected.list_tests, GTEST_FLAG(list_tests)); EXPECT_STREQ(expected.output, GTEST_FLAG(output).c_str()); EXPECT_EQ(expected.print_time, GTEST_FLAG(print_time)); EXPECT_EQ(expected.random_seed, GTEST_FLAG(random_seed)); EXPECT_EQ(expected.repeat, GTEST_FLAG(repeat)); EXPECT_EQ(expected.shuffle, GTEST_FLAG(shuffle)); EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG(stack_trace_depth)); EXPECT_STREQ(expected.stream_result_to, GTEST_FLAG(stream_result_to).c_str()); EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG(throw_on_failure)); } // Parses a command line (specified by argc1 and argv1), then // verifies that the flag values are expected and that the // recognized flags are removed from the command line. template <typename CharType> static void TestParsingFlags(int argc1, const CharType** argv1, int argc2, const CharType** argv2, const Flags& expected, bool should_print_help) { const bool saved_help_flag = ::testing::internal::g_help_flag; ::testing::internal::g_help_flag = false; #if GTEST_HAS_STREAM_REDIRECTION CaptureStdout(); #endif // Parses the command line. internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1)); #if GTEST_HAS_STREAM_REDIRECTION const std::string captured_stdout = GetCapturedStdout(); #endif // Verifies the flag values. CheckFlags(expected); // Verifies that the recognized flags are removed from the command // line. AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2); // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the // help message for the flags it recognizes. EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag); #if GTEST_HAS_STREAM_REDIRECTION const char* const expected_help_fragment = "This program contains tests written using"; if (should_print_help) { EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout); } else { EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment, captured_stdout); } #endif // GTEST_HAS_STREAM_REDIRECTION ::testing::internal::g_help_flag = saved_help_flag; } // This macro wraps TestParsingFlags s.t. the user doesn't need // to specify the array sizes. #define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \ TestParsingFlags(sizeof(argv1)/sizeof(*argv1) - 1, argv1, \ sizeof(argv2)/sizeof(*argv2) - 1, argv2, \ expected, should_print_help) }; // Tests parsing an empty command line. TEST_F(InitGoogleTestTest, Empty) { const char* argv[] = { NULL }; const char* argv2[] = { NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } // Tests parsing a command line that has no flag. TEST_F(InitGoogleTestTest, NoFlag) { const char* argv[] = { "foo.exe", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } // Tests parsing a bad --gtest_filter flag. TEST_F(InitGoogleTestTest, FilterBad) { const char* argv[] = { "foo.exe", "--gtest_filter", NULL }; const char* argv2[] = { "foo.exe", "--gtest_filter", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), true); } // Tests parsing an empty --gtest_filter flag. TEST_F(InitGoogleTestTest, FilterEmpty) { const char* argv[] = { "foo.exe", "--gtest_filter=", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(""), false); } // Tests parsing a non-empty --gtest_filter flag. TEST_F(InitGoogleTestTest, FilterNonEmpty) { const char* argv[] = { "foo.exe", "--gtest_filter=abc", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); } // Tests parsing --gtest_break_on_failure. TEST_F(InitGoogleTestTest, BreakOnFailureWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } // Tests parsing --gtest_break_on_failure=0. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_0) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing --gtest_break_on_failure=f. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_f) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=f", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing --gtest_break_on_failure=F. TEST_F(InitGoogleTestTest, BreakOnFailureFalse_F) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=F", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false); } // Tests parsing a --gtest_break_on_failure flag that has a "true" // definition. TEST_F(InitGoogleTestTest, BreakOnFailureTrue) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false); } // Tests parsing --gtest_catch_exceptions. TEST_F(InitGoogleTestTest, CatchExceptions) { const char* argv[] = { "foo.exe", "--gtest_catch_exceptions", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false); } // Tests parsing --gtest_death_test_use_fork. TEST_F(InitGoogleTestTest, DeathTestUseFork) { const char* argv[] = { "foo.exe", "--gtest_death_test_use_fork", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false); } // Tests having the same flag twice with different values. The // expected behavior is that the one coming last takes precedence. TEST_F(InitGoogleTestTest, DuplicatedFlags) { const char* argv[] = { "foo.exe", "--gtest_filter=a", "--gtest_filter=b", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("b"), false); } // Tests having an unrecognized flag on the command line. TEST_F(InitGoogleTestTest, UnrecognizedFlag) { const char* argv[] = { "foo.exe", "--gtest_break_on_failure", "bar", // Unrecognized by Google Test. "--gtest_filter=b", NULL }; const char* argv2[] = { "foo.exe", "bar", NULL }; Flags flags; flags.break_on_failure = true; flags.filter = "b"; GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false); } // Tests having a --gtest_list_tests flag TEST_F(InitGoogleTestTest, ListTestsFlag) { const char* argv[] = { "foo.exe", "--gtest_list_tests", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } // Tests having a --gtest_list_tests flag with a "true" value TEST_F(InitGoogleTestTest, ListTestsTrue) { const char* argv[] = { "foo.exe", "--gtest_list_tests=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false); } // Tests having a --gtest_list_tests flag with a "false" value TEST_F(InitGoogleTestTest, ListTestsFalse) { const char* argv[] = { "foo.exe", "--gtest_list_tests=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_list_tests=f. TEST_F(InitGoogleTestTest, ListTestsFalse_f) { const char* argv[] = { "foo.exe", "--gtest_list_tests=f", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_list_tests=F. TEST_F(InitGoogleTestTest, ListTestsFalse_F) { const char* argv[] = { "foo.exe", "--gtest_list_tests=F", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false); } // Tests parsing --gtest_output (invalid). TEST_F(InitGoogleTestTest, OutputEmpty) { const char* argv[] = { "foo.exe", "--gtest_output", NULL }; const char* argv2[] = { "foo.exe", "--gtest_output", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true); } // Tests parsing --gtest_output=xml TEST_F(InitGoogleTestTest, OutputXml) { const char* argv[] = { "foo.exe", "--gtest_output=xml", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml"), false); } // Tests parsing --gtest_output=xml:file TEST_F(InitGoogleTestTest, OutputXmlFile) { const char* argv[] = { "foo.exe", "--gtest_output=xml:file", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:file"), false); } // Tests parsing --gtest_output=xml:directory/path/ TEST_F(InitGoogleTestTest, OutputXmlDirectory) { const char* argv[] = { "foo.exe", "--gtest_output=xml:directory/path/", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output("xml:directory/path/"), false); } // Tests having a --gtest_print_time flag TEST_F(InitGoogleTestTest, PrintTimeFlag) { const char* argv[] = { "foo.exe", "--gtest_print_time", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } // Tests having a --gtest_print_time flag with a "true" value TEST_F(InitGoogleTestTest, PrintTimeTrue) { const char* argv[] = { "foo.exe", "--gtest_print_time=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false); } // Tests having a --gtest_print_time flag with a "false" value TEST_F(InitGoogleTestTest, PrintTimeFalse) { const char* argv[] = { "foo.exe", "--gtest_print_time=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_print_time=f. TEST_F(InitGoogleTestTest, PrintTimeFalse_f) { const char* argv[] = { "foo.exe", "--gtest_print_time=f", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_print_time=F. TEST_F(InitGoogleTestTest, PrintTimeFalse_F) { const char* argv[] = { "foo.exe", "--gtest_print_time=F", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false); } // Tests parsing --gtest_random_seed=number TEST_F(InitGoogleTestTest, RandomSeed) { const char* argv[] = { "foo.exe", "--gtest_random_seed=1000", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false); } // Tests parsing --gtest_repeat=number TEST_F(InitGoogleTestTest, Repeat) { const char* argv[] = { "foo.exe", "--gtest_repeat=1000", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false); } // Tests having a --gtest_also_run_disabled_tests flag TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFlag) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), false); } // Tests having a --gtest_also_run_disabled_tests flag with a "true" value TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsTrue) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true), false); } // Tests having a --gtest_also_run_disabled_tests flag with a "false" value TEST_F(InitGoogleTestTest, AlsoRunDisabledTestsFalse) { const char* argv[] = { "foo.exe", "--gtest_also_run_disabled_tests=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false), false); } // Tests parsing --gtest_shuffle. TEST_F(InitGoogleTestTest, ShuffleWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_shuffle", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } // Tests parsing --gtest_shuffle=0. TEST_F(InitGoogleTestTest, ShuffleFalse_0) { const char* argv[] = { "foo.exe", "--gtest_shuffle=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false); } // Tests parsing a --gtest_shuffle flag that has a "true" // definition. TEST_F(InitGoogleTestTest, ShuffleTrue) { const char* argv[] = { "foo.exe", "--gtest_shuffle=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false); } // Tests parsing --gtest_stack_trace_depth=number. TEST_F(InitGoogleTestTest, StackTraceDepth) { const char* argv[] = { "foo.exe", "--gtest_stack_trace_depth=5", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false); } TEST_F(InitGoogleTestTest, StreamResultTo) { const char* argv[] = { "foo.exe", "--gtest_stream_result_to=localhost:1234", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_( argv, argv2, Flags::StreamResultTo("localhost:1234"), false); } // Tests parsing --gtest_throw_on_failure. TEST_F(InitGoogleTestTest, ThrowOnFailureWithoutValue) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } // Tests parsing --gtest_throw_on_failure=0. TEST_F(InitGoogleTestTest, ThrowOnFailureFalse_0) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure=0", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false); } // Tests parsing a --gtest_throw_on_failure flag that has a "true" // definition. TEST_F(InitGoogleTestTest, ThrowOnFailureTrue) { const char* argv[] = { "foo.exe", "--gtest_throw_on_failure=1", NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false); } #if GTEST_OS_WINDOWS // Tests parsing wide strings. TEST_F(InitGoogleTestTest, WideStrings) { const wchar_t* argv[] = { L"foo.exe", L"--gtest_filter=Foo*", L"--gtest_list_tests=1", L"--gtest_break_on_failure", L"--non_gtest_flag", NULL }; const wchar_t* argv2[] = { L"foo.exe", L"--non_gtest_flag", NULL }; Flags expected_flags; expected_flags.break_on_failure = true; expected_flags.filter = "Foo*"; expected_flags.list_tests = true; GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } # endif // GTEST_OS_WINDOWS #if GTEST_USE_OWN_FLAGFILE_FLAG_ class FlagfileTest : public InitGoogleTestTest { public: virtual void SetUp() { InitGoogleTestTest::SetUp(); testdata_path_.Set(internal::FilePath( testing::TempDir() + internal::GetCurrentExecutableName().string() + "_flagfile_test")); testing::internal::posix::RmDir(testdata_path_.c_str()); EXPECT_TRUE(testdata_path_.CreateFolder()); } virtual void TearDown() { testing::internal::posix::RmDir(testdata_path_.c_str()); InitGoogleTestTest::TearDown(); } internal::FilePath CreateFlagfile(const char* contents) { internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName( testdata_path_, internal::FilePath("unique"), "txt")); FILE* f = testing::internal::posix::FOpen(file_path.c_str(), "w"); fprintf(f, "%s", contents); fclose(f); return file_path; } private: internal::FilePath testdata_path_; }; // Tests an empty flagfile. TEST_F(FlagfileTest, Empty) { internal::FilePath flagfile_path(CreateFlagfile("")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); const char* argv[] = { "foo.exe", flagfile_flag.c_str(), NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); } // Tests passing a non-empty --gtest_filter flag via --gtest_flagfile. TEST_F(FlagfileTest, FilterNonEmpty) { internal::FilePath flagfile_path(CreateFlagfile( "--" GTEST_FLAG_PREFIX_ "filter=abc")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); const char* argv[] = { "foo.exe", flagfile_flag.c_str(), NULL }; const char* argv2[] = { "foo.exe", NULL }; GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); } // Tests passing several flags via --gtest_flagfile. TEST_F(FlagfileTest, SeveralFlags) { internal::FilePath flagfile_path(CreateFlagfile( "--" GTEST_FLAG_PREFIX_ "filter=abc\n" "--" GTEST_FLAG_PREFIX_ "break_on_failure\n" "--" GTEST_FLAG_PREFIX_ "list_tests")); std::string flagfile_flag = std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); const char* argv[] = { "foo.exe", flagfile_flag.c_str(), NULL }; const char* argv2[] = { "foo.exe", NULL }; Flags expected_flags; expected_flags.break_on_failure = true; expected_flags.filter = "abc"; expected_flags.list_tests = true; GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false); } #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ // Tests current_test_info() in UnitTest. class CurrentTestInfoTest : public Test { protected: // Tests that current_test_info() returns NULL before the first test in // the test case is run. static void SetUpTestCase() { // There should be no tests running at this point. const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == NULL) << "There should be no tests running at this point."; } // Tests that current_test_info() returns NULL after the last test in // the test case has run. static void TearDownTestCase() { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); EXPECT_TRUE(test_info == NULL) << "There should be no tests running at this point."; } }; // Tests that current_test_info() returns TestInfo for currently running // test by checking the expected test name against the actual one. TEST_F(CurrentTestInfoTest, WorksForFirstTestInATestCase) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(NULL != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) << "Expected the name of the currently running test case."; EXPECT_STREQ("WorksForFirstTestInATestCase", test_info->name()) << "Expected the name of the currently running test."; } // Tests that current_test_info() returns TestInfo for currently running // test by checking the expected test name against the actual one. We // use this test to see that the TestInfo object actually changed from // the previous invocation. TEST_F(CurrentTestInfoTest, WorksForSecondTestInATestCase) { const TestInfo* test_info = UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(NULL != test_info) << "There is a test running so we should have a valid TestInfo."; EXPECT_STREQ("CurrentTestInfoTest", test_info->test_case_name()) << "Expected the name of the currently running test case."; EXPECT_STREQ("WorksForSecondTestInATestCase", test_info->name()) << "Expected the name of the currently running test."; } } // namespace testing // These two lines test that we can define tests in a namespace that // has the name "testing" and is nested in another namespace. namespace my_namespace { namespace testing { // Makes sure that TEST knows to use ::testing::Test instead of // ::my_namespace::testing::Test. class Test {}; // Makes sure that an assertion knows to use ::testing::Message instead of // ::my_namespace::testing::Message. class Message {}; // Makes sure that an assertion knows to use // ::testing::AssertionResult instead of // ::my_namespace::testing::AssertionResult. class AssertionResult {}; // Tests that an assertion that should succeed works as expected. TEST(NestedTestingNamespaceTest, Success) { EXPECT_EQ(1, 1) << "This shouldn't fail."; } // Tests that an assertion that should fail works as expected. TEST(NestedTestingNamespaceTest, Failure) { EXPECT_FATAL_FAILURE(FAIL() << "This failure is expected.", "This failure is expected."); } } // namespace testing } // namespace my_namespace // Tests that one can call superclass SetUp and TearDown methods-- // that is, that they are not private. // No tests are based on this fixture; the test "passes" if it compiles // successfully. class ProtectedFixtureMethodsTest : public Test { protected: virtual void SetUp() { Test::SetUp(); } virtual void TearDown() { Test::TearDown(); } }; // StreamingAssertionsTest tests the streaming versions of a representative // sample of assertions. TEST(StreamingAssertionsTest, Unconditional) { SUCCEED() << "expected success"; EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(FAIL() << "expected failure", "expected failure"); } #ifdef __BORLANDC__ // Silences warnings: "Condition is always true", "Unreachable code" # pragma option push -w-ccc -w-rch #endif TEST(StreamingAssertionsTest, Truth) { EXPECT_TRUE(true) << "unexpected failure"; ASSERT_TRUE(true) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, Truth2) { EXPECT_FALSE(false) << "unexpected failure"; ASSERT_FALSE(false) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << "expected failure", "expected failure"); } #ifdef __BORLANDC__ // Restores warnings after previous "#pragma option push" supressed them # pragma option pop #endif TEST(StreamingAssertionsTest, IntegerEquals) { EXPECT_EQ(1, 1) << "unexpected failure"; ASSERT_EQ(1, 1) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, IntegerLessThan) { EXPECT_LT(1, 2) << "unexpected failure"; ASSERT_LT(1, 2) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsEqual) { EXPECT_STREQ("foo", "foo") << "unexpected failure"; ASSERT_STREQ("foo", "foo") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STREQ("foo", "bar") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STREQ("foo", "bar") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsNotEqual) { EXPECT_STRNE("foo", "bar") << "unexpected failure"; ASSERT_STRNE("foo", "bar") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRNE("foo", "foo") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRNE("foo", "foo") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringsEqualIgnoringCase) { EXPECT_STRCASEEQ("foo", "FOO") << "unexpected failure"; ASSERT_STRCASEEQ("foo", "FOO") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ("foo", "bar") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ("foo", "bar") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) { EXPECT_STRCASENE("foo", "bar") << "unexpected failure"; ASSERT_STRCASENE("foo", "bar") << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE("foo", "FOO") << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_STRCASENE("bar", "BAR") << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, FloatingPointEquals) { EXPECT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; ASSERT_FLOAT_EQ(1.0, 1.0) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << "expected failure", "expected failure"); } #if GTEST_HAS_EXCEPTIONS TEST(StreamingAssertionsTest, Throw) { EXPECT_THROW(ThrowAnInteger(), int) << "unexpected failure"; ASSERT_THROW(ThrowAnInteger(), int) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, NoThrow) { EXPECT_NO_THROW(ThrowNothing()) << "unexpected failure"; ASSERT_NO_THROW(ThrowNothing()) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << "expected failure", "expected failure"); } TEST(StreamingAssertionsTest, AnyThrow) { EXPECT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; ASSERT_ANY_THROW(ThrowAnInteger()) << "unexpected failure"; EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()) << "expected failure", "expected failure"); EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << "expected failure", "expected failure"); } #endif // GTEST_HAS_EXCEPTIONS // Tests that Google Test correctly decides whether to use colors in the output. TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) { GTEST_FLAG(color) = "yes"; SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. } TEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) { SetEnv("TERM", "dumb"); // TERM doesn't support colors. GTEST_FLAG(color) = "True"; EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. GTEST_FLAG(color) = "t"; EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. GTEST_FLAG(color) = "1"; EXPECT_TRUE(ShouldUseColor(false)); // Stdout is not a TTY. } TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) { GTEST_FLAG(color) = "no"; SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. } TEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) { SetEnv("TERM", "xterm"); // TERM supports colors. GTEST_FLAG(color) = "F"; EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. GTEST_FLAG(color) = "0"; EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. GTEST_FLAG(color) = "unknown"; EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. } TEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) { GTEST_FLAG(color) = "auto"; SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_FALSE(ShouldUseColor(false)); // Stdout is not a TTY. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. } TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { GTEST_FLAG(color) = "auto"; #if GTEST_OS_WINDOWS // On Windows, we ignore the TERM variable as it's usually not set. SetEnv("TERM", "dumb"); EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", ""); EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm"); EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. #else // On non-Windows platforms, we rely on TERM to determine if the // terminal supports colors. SetEnv("TERM", "dumb"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "emacs"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "vt100"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm-mono"); // TERM doesn't support colors. EXPECT_FALSE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm-color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "xterm-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "screen"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "screen-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "tmux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "tmux-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "rxvt-unicode"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "rxvt-unicode-256color"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "linux"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. SetEnv("TERM", "cygwin"); // TERM supports colors. EXPECT_TRUE(ShouldUseColor(true)); // Stdout is a TTY. #endif // GTEST_OS_WINDOWS } // Verifies that StaticAssertTypeEq works in a namespace scope. static bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>(); static bool dummy2 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<const int, const int>(); // Verifies that StaticAssertTypeEq works in a class. template <typename T> class StaticAssertTypeEqTestHelper { public: StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); } }; TEST(StaticAssertTypeEqTest, WorksInClass) { StaticAssertTypeEqTestHelper<bool>(); } // Verifies that StaticAssertTypeEq works inside a function. typedef int IntAlias; TEST(StaticAssertTypeEqTest, CompilesForEqualTypes) { StaticAssertTypeEq<int, IntAlias>(); StaticAssertTypeEq<int*, IntAlias*>(); } TEST(GetCurrentOsStackTraceExceptTopTest, ReturnsTheStackTrace) { testing::UnitTest* const unit_test = testing::UnitTest::GetInstance(); // We don't have a stack walker in Google Test yet. EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 0).c_str()); EXPECT_STREQ("", GetCurrentOsStackTraceExceptTop(unit_test, 1).c_str()); } TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) { EXPECT_FALSE(HasNonfatalFailure()); } static void FailFatally() { FAIL(); } TEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) { FailFatally(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_FALSE(has_nonfatal_failure); } TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } TEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { FailFatally(); ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } // A wrapper for calling HasNonfatalFailure outside of a test body. static bool HasNonfatalFailureHelper() { return testing::Test::HasNonfatalFailure(); } TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) { EXPECT_FALSE(HasNonfatalFailureHelper()); } TEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) { ADD_FAILURE(); const bool has_nonfatal_failure = HasNonfatalFailureHelper(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_nonfatal_failure); } TEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) { EXPECT_FALSE(HasFailure()); } TEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) { FailFatally(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } TEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) { ADD_FAILURE(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } TEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) { FailFatally(); ADD_FAILURE(); const bool has_failure = HasFailure(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } // A wrapper for calling HasFailure outside of a test body. static bool HasFailureHelper() { return testing::Test::HasFailure(); } TEST(HasFailureTest, WorksOutsideOfTestBody) { EXPECT_FALSE(HasFailureHelper()); } TEST(HasFailureTest, WorksOutsideOfTestBody2) { ADD_FAILURE(); const bool has_failure = HasFailureHelper(); ClearCurrentTestPartResults(); EXPECT_TRUE(has_failure); } class TestListener : public EmptyTestEventListener { public: TestListener() : on_start_counter_(NULL), is_destroyed_(NULL) {} TestListener(int* on_start_counter, bool* is_destroyed) : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {} virtual ~TestListener() { if (is_destroyed_) *is_destroyed_ = true; } protected: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { if (on_start_counter_ != NULL) (*on_start_counter_)++; } private: int* on_start_counter_; bool* is_destroyed_; }; // Tests the constructor. TEST(TestEventListenersTest, ConstructionWorks) { TestEventListeners listeners; EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != NULL); EXPECT_TRUE(listeners.default_result_printer() == NULL); EXPECT_TRUE(listeners.default_xml_generator() == NULL); } // Tests that the TestEventListeners destructor deletes all the listeners it // owns. TEST(TestEventListenersTest, DestructionWorks) { bool default_result_printer_is_destroyed = false; bool default_xml_printer_is_destroyed = false; bool extra_listener_is_destroyed = false; TestListener* default_result_printer = new TestListener( NULL, &default_result_printer_is_destroyed); TestListener* default_xml_printer = new TestListener( NULL, &default_xml_printer_is_destroyed); TestListener* extra_listener = new TestListener( NULL, &extra_listener_is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, default_result_printer); TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, default_xml_printer); listeners.Append(extra_listener); } EXPECT_TRUE(default_result_printer_is_destroyed); EXPECT_TRUE(default_xml_printer_is_destroyed); EXPECT_TRUE(extra_listener_is_destroyed); } // Tests that a listener Append'ed to a TestEventListeners list starts // receiving events. TEST(TestEventListenersTest, Append) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; listeners.Append(listener); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } EXPECT_TRUE(is_destroyed); } // Tests that listeners receive events in the order they were appended to // the list, except for *End requests, which must be received in the reverse // order. class SequenceTestingListener : public EmptyTestEventListener { public: SequenceTestingListener(std::vector<std::string>* vector, const char* id) : vector_(vector), id_(id) {} protected: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) { vector_->push_back(GetEventDescription("OnTestProgramStart")); } virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) { vector_->push_back(GetEventDescription("OnTestProgramEnd")); } virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, int /*iteration*/) { vector_->push_back(GetEventDescription("OnTestIterationStart")); } virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, int /*iteration*/) { vector_->push_back(GetEventDescription("OnTestIterationEnd")); } private: std::string GetEventDescription(const char* method) { Message message; message << id_ << "." << method; return message.GetString(); } std::vector<std::string>* vector_; const char* const id_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SequenceTestingListener); }; TEST(EventListenerTest, AppendKeepsOrder) { std::vector<std::string> vec; TestEventListeners listeners; listeners.Append(new SequenceTestingListener(&vec, "1st")); listeners.Append(new SequenceTestingListener(&vec, "2nd")); listeners.Append(new SequenceTestingListener(&vec, "3rd")); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestProgramStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestProgramStart", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramEnd( *UnitTest::GetInstance()); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestProgramEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestProgramEnd", vec[1].c_str()); EXPECT_STREQ("1st.OnTestProgramEnd", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationStart( *UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("1st.OnTestIterationStart", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationStart", vec[1].c_str()); EXPECT_STREQ("3rd.OnTestIterationStart", vec[2].c_str()); vec.clear(); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestIterationEnd( *UnitTest::GetInstance(), 0); ASSERT_EQ(3U, vec.size()); EXPECT_STREQ("3rd.OnTestIterationEnd", vec[0].c_str()); EXPECT_STREQ("2nd.OnTestIterationEnd", vec[1].c_str()); EXPECT_STREQ("1st.OnTestIterationEnd", vec[2].c_str()); } // Tests that a listener removed from a TestEventListeners list stops receiving // events and is not deleted when the list is destroyed. TEST(TestEventListenersTest, Release) { int on_start_counter = 0; bool is_destroyed = false; // Although Append passes the ownership of this object to the list, // the following calls release it, and we need to delete it before the // test ends. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; listeners.Append(listener); EXPECT_EQ(listener, listeners.Release(listener)); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_TRUE(listeners.Release(listener) == NULL); } EXPECT_EQ(0, on_start_counter); EXPECT_FALSE(is_destroyed); delete listener; } // Tests that no events are forwarded when event forwarding is disabled. TEST(EventListenerTest, SuppressEventForwarding) { int on_start_counter = 0; TestListener* listener = new TestListener(&on_start_counter, NULL); TestEventListeners listeners; listeners.Append(listener); ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::SuppressEventForwarding(&listeners); ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners)); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Tests that events generated by Google Test are not forwarded in // death test subprocesses. TEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) { EXPECT_DEATH_IF_SUPPORTED({ GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled( *GetUnitTestImpl()->listeners())) << "expected failure";}, "expected failure"); } // Tests that a listener installed via SetDefaultResultPrinter() starts // receiving events and is returned via default_result_printer() and that // the previous default_result_printer is removed from the list and deleted. TEST(EventListenerTest, default_result_printer) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); EXPECT_EQ(listener, listeners.default_result_printer()); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); // Replacing default_result_printer with something else should remove it // from the list and destroy it. TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, NULL); EXPECT_TRUE(listeners.default_result_printer() == NULL); EXPECT_TRUE(is_destroyed); // After broadcasting an event the counter is still the same, indicating // the listener is not in the list anymore. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } // Tests that the default_result_printer listener stops receiving events // when removed via Release and that is not owned by the list anymore. TEST(EventListenerTest, RemovingDefaultResultPrinterWorks) { int on_start_counter = 0; bool is_destroyed = false; // Although Append passes the ownership of this object to the list, // the following calls release it, and we need to delete it before the // test ends. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_TRUE(listeners.default_result_printer() == NULL); EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_result_printer. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Destroying the list should not affect the listener now, too. EXPECT_FALSE(is_destroyed); delete listener; } // Tests that a listener installed via SetDefaultXmlGenerator() starts // receiving events and is returned via default_xml_generator() and that // the previous default_xml_generator is removed from the list and deleted. TEST(EventListenerTest, default_xml_generator) { int on_start_counter = 0; bool is_destroyed = false; TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); TestEventListeners listeners; TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); EXPECT_EQ(listener, listeners.default_xml_generator()); TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); // Replacing default_xml_generator with something else should remove it // from the list and destroy it. TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, NULL); EXPECT_TRUE(listeners.default_xml_generator() == NULL); EXPECT_TRUE(is_destroyed); // After broadcasting an event the counter is still the same, indicating // the listener is not in the list anymore. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(1, on_start_counter); } // Tests that the default_xml_generator listener stops receiving events // when removed via Release and that is not owned by the list anymore. TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { int on_start_counter = 0; bool is_destroyed = false; // Although Append passes the ownership of this object to the list, // the following calls release it, and we need to delete it before the // test ends. TestListener* listener = new TestListener(&on_start_counter, &is_destroyed); { TestEventListeners listeners; TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener); EXPECT_EQ(listener, listeners.Release(listener)); EXPECT_TRUE(listeners.default_xml_generator() == NULL); EXPECT_FALSE(is_destroyed); // Broadcasting events now should not affect default_xml_generator. TestEventListenersAccessor::GetRepeater(&listeners)->OnTestProgramStart( *UnitTest::GetInstance()); EXPECT_EQ(0, on_start_counter); } // Destroying the list should not affect the listener now, too. EXPECT_FALSE(is_destroyed); delete listener; } // Sanity tests to ensure that the alternative, verbose spellings of // some of the macros work. We don't test them thoroughly as that // would be quite involved. Since their implementations are // straightforward, and they are rarely used, we'll just rely on the // users to tell us when they are broken. GTEST_TEST(AlternativeNameTest, Works) { // GTEST_TEST is the same as TEST. GTEST_SUCCEED() << "OK"; // GTEST_SUCCEED is the same as SUCCEED. // GTEST_FAIL is the same as FAIL. EXPECT_FATAL_FAILURE(GTEST_FAIL() << "An expected failure", "An expected failure"); // GTEST_ASSERT_XY is the same as ASSERT_XY. GTEST_ASSERT_EQ(0, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_NE(0, 1); GTEST_ASSERT_NE(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_LE(0, 0); GTEST_ASSERT_LE(0, 1); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_LT(0, 1); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << "An expected failure", "An expected failure"); GTEST_ASSERT_GE(0, 0); GTEST_ASSERT_GE(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << "An expected failure", "An expected failure"); GTEST_ASSERT_GT(1, 0); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << "An expected failure", "An expected failure"); EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << "An expected failure", "An expected failure"); } // Tests for internal utilities necessary for implementation of the universal // printing. // TODO(vladl@google.com): Find a better home for them. class ConversionHelperBase {}; class ConversionHelperDerived : public ConversionHelperBase {}; // Tests that IsAProtocolMessage<T>::value is a compile-time constant. TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { GTEST_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value, const_true); GTEST_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false); } // Tests that IsAProtocolMessage<T>::value is true when T is // proto2::Message or a sub-class of it. TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value); } // Tests that IsAProtocolMessage<T>::value is false when T is neither // ProtocolMessage nor a sub-class of it. TEST(IsAProtocolMessageTest, ValueIsFalseWhenTypeIsNotAProtocolMessage) { EXPECT_FALSE(IsAProtocolMessage<int>::value); EXPECT_FALSE(IsAProtocolMessage<const ConversionHelperBase>::value); } // Tests that CompileAssertTypesEqual compiles when the type arguments are // equal. TEST(CompileAssertTypesEqual, CompilesWhenTypesAreEqual) { CompileAssertTypesEqual<void, void>(); CompileAssertTypesEqual<int*, int*>(); } // Tests that RemoveReference does not affect non-reference types. TEST(RemoveReferenceTest, DoesNotAffectNonReferenceType) { CompileAssertTypesEqual<int, RemoveReference<int>::type>(); CompileAssertTypesEqual<const char, RemoveReference<const char>::type>(); } // Tests that RemoveReference removes reference from reference types. TEST(RemoveReferenceTest, RemovesReference) { CompileAssertTypesEqual<int, RemoveReference<int&>::type>(); CompileAssertTypesEqual<const char, RemoveReference<const char&>::type>(); } // Tests GTEST_REMOVE_REFERENCE_. template <typename T1, typename T2> void TestGTestRemoveReference() { CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_(T2)>(); } TEST(RemoveReferenceTest, MacroVersion) { TestGTestRemoveReference<int, int>(); TestGTestRemoveReference<const char, const char&>(); } // Tests that RemoveConst does not affect non-const types. TEST(RemoveConstTest, DoesNotAffectNonConstType) { CompileAssertTypesEqual<int, RemoveConst<int>::type>(); CompileAssertTypesEqual<char&, RemoveConst<char&>::type>(); } // Tests that RemoveConst removes const from const types. TEST(RemoveConstTest, RemovesConst) { CompileAssertTypesEqual<int, RemoveConst<const int>::type>(); CompileAssertTypesEqual<char[2], RemoveConst<const char[2]>::type>(); CompileAssertTypesEqual<char[2][3], RemoveConst<const char[2][3]>::type>(); } // Tests GTEST_REMOVE_CONST_. template <typename T1, typename T2> void TestGTestRemoveConst() { CompileAssertTypesEqual<T1, GTEST_REMOVE_CONST_(T2)>(); } TEST(RemoveConstTest, MacroVersion) { TestGTestRemoveConst<int, int>(); TestGTestRemoveConst<double&, double&>(); TestGTestRemoveConst<char, const char>(); } // Tests GTEST_REMOVE_REFERENCE_AND_CONST_. template <typename T1, typename T2> void TestGTestRemoveReferenceAndConst() { CompileAssertTypesEqual<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>(); } TEST(RemoveReferenceToConstTest, Works) { TestGTestRemoveReferenceAndConst<int, int>(); TestGTestRemoveReferenceAndConst<double, double&>(); TestGTestRemoveReferenceAndConst<char, const char>(); TestGTestRemoveReferenceAndConst<char, const char&>(); TestGTestRemoveReferenceAndConst<const char*, const char*>(); } // Tests that AddReference does not affect reference types. TEST(AddReferenceTest, DoesNotAffectReferenceType) { CompileAssertTypesEqual<int&, AddReference<int&>::type>(); CompileAssertTypesEqual<const char&, AddReference<const char&>::type>(); } // Tests that AddReference adds reference to non-reference types. TEST(AddReferenceTest, AddsReference) { CompileAssertTypesEqual<int&, AddReference<int>::type>(); CompileAssertTypesEqual<const char&, AddReference<const char>::type>(); } // Tests GTEST_ADD_REFERENCE_. template <typename T1, typename T2> void TestGTestAddReference() { CompileAssertTypesEqual<T1, GTEST_ADD_REFERENCE_(T2)>(); } TEST(AddReferenceTest, MacroVersion) { TestGTestAddReference<int&, int>(); TestGTestAddReference<const char&, const char&>(); } // Tests GTEST_REFERENCE_TO_CONST_. template <typename T1, typename T2> void TestGTestReferenceToConst() { CompileAssertTypesEqual<T1, GTEST_REFERENCE_TO_CONST_(T2)>(); } TEST(GTestReferenceToConstTest, Works) { TestGTestReferenceToConst<const char&, char>(); TestGTestReferenceToConst<const int&, const int>(); TestGTestReferenceToConst<const double&, double>(); TestGTestReferenceToConst<const std::string&, const std::string&>(); } // Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant. TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) { GTEST_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true); GTEST_COMPILE_ASSERT_((!ImplicitlyConvertible<void*, int*>::value), const_false); } // Tests that ImplicitlyConvertible<T1, T2>::value is true when T1 can // be implicitly converted to T2. TEST(ImplicitlyConvertibleTest, ValueIsTrueWhenConvertible) { EXPECT_TRUE((ImplicitlyConvertible<int, double>::value)); EXPECT_TRUE((ImplicitlyConvertible<double, int>::value)); EXPECT_TRUE((ImplicitlyConvertible<int*, void*>::value)); EXPECT_TRUE((ImplicitlyConvertible<int*, const int*>::value)); EXPECT_TRUE((ImplicitlyConvertible<ConversionHelperDerived&, const ConversionHelperBase&>::value)); EXPECT_TRUE((ImplicitlyConvertible<const ConversionHelperBase, ConversionHelperBase>::value)); } // Tests that ImplicitlyConvertible<T1, T2>::value is false when T1 // cannot be implicitly converted to T2. TEST(ImplicitlyConvertibleTest, ValueIsFalseWhenNotConvertible) { EXPECT_FALSE((ImplicitlyConvertible<double, int*>::value)); EXPECT_FALSE((ImplicitlyConvertible<void*, int*>::value)); EXPECT_FALSE((ImplicitlyConvertible<const int*, int*>::value)); EXPECT_FALSE((ImplicitlyConvertible<ConversionHelperBase&, ConversionHelperDerived&>::value)); } // Tests IsContainerTest. class NonContainer {}; TEST(IsContainerTestTest, WorksForNonContainer) { EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0))); EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0))); } TEST(IsContainerTestTest, WorksForContainer) { EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool> >(0))); EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::map<int, double> >(0))); } // Tests ArrayEq(). TEST(ArrayEqTest, WorksForDegeneratedArrays) { EXPECT_TRUE(ArrayEq(5, 5L)); EXPECT_FALSE(ArrayEq('a', 0)); } TEST(ArrayEqTest, WorksForOneDimensionalArrays) { // Note that a and b are distinct but compatible types. const int a[] = { 0, 1 }; long b[] = { 0, 1 }; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); b[0] = 2; EXPECT_FALSE(ArrayEq(a, b)); EXPECT_FALSE(ArrayEq(a, 1, b)); } TEST(ArrayEqTest, WorksForTwoDimensionalArrays) { const char a[][3] = { "hi", "lo" }; const char b[][3] = { "hi", "lo" }; const char c[][3] = { "hi", "li" }; EXPECT_TRUE(ArrayEq(a, b)); EXPECT_TRUE(ArrayEq(a, 2, b)); EXPECT_FALSE(ArrayEq(a, c)); EXPECT_FALSE(ArrayEq(a, 2, c)); } // Tests ArrayAwareFind(). TEST(ArrayAwareFindTest, WorksForOneDimensionalArray) { const char a[] = "hello"; EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o')); EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x')); } TEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) { int a[][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } }; const int b[2] = { 2, 3 }; EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b)); const int c[2] = { 6, 7 }; EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c)); } // Tests CopyArray(). TEST(CopyArrayTest, WorksForDegeneratedArrays) { int n = 0; CopyArray('a', &n); EXPECT_EQ('a', n); } TEST(CopyArrayTest, WorksForOneDimensionalArrays) { const char a[3] = "hi"; int b[3]; #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. CopyArray(a, &b); EXPECT_TRUE(ArrayEq(a, b)); #endif int c[3]; CopyArray(a, 3, c); EXPECT_TRUE(ArrayEq(a, c)); } TEST(CopyArrayTest, WorksForTwoDimensionalArrays) { const int a[2][3] = { { 0, 1, 2 }, { 3, 4, 5 } }; int b[2][3]; #ifndef __BORLANDC__ // C++Builder cannot compile some array size deductions. CopyArray(a, &b); EXPECT_TRUE(ArrayEq(a, b)); #endif int c[2][3]; CopyArray(a, 2, c); EXPECT_TRUE(ArrayEq(a, c)); } // Tests NativeArray. TEST(NativeArrayTest, ConstructorFromArrayWorks) { const int a[3] = { 0, 1, 2 }; NativeArray<int> na(a, 3, RelationToSourceReference()); EXPECT_EQ(3U, na.size()); EXPECT_EQ(a, na.begin()); } TEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) { typedef int Array[2]; Array* a = new Array[1]; (*a)[0] = 0; (*a)[1] = 1; NativeArray<int> na(*a, 2, RelationToSourceCopy()); EXPECT_NE(*a, na.begin()); delete[] a; EXPECT_EQ(0, na.begin()[0]); EXPECT_EQ(1, na.begin()[1]); // We rely on the heap checker to verify that na deletes the copy of // array. } TEST(NativeArrayTest, TypeMembersAreCorrect) { StaticAssertTypeEq<char, NativeArray<char>::value_type>(); StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>(); StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>(); StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>(); } TEST(NativeArrayTest, MethodsWork) { const int a[3] = { 0, 1, 2 }; NativeArray<int> na(a, 3, RelationToSourceCopy()); ASSERT_EQ(3U, na.size()); EXPECT_EQ(3, na.end() - na.begin()); NativeArray<int>::const_iterator it = na.begin(); EXPECT_EQ(0, *it); ++it; EXPECT_EQ(1, *it); it++; EXPECT_EQ(2, *it); ++it; EXPECT_EQ(na.end(), it); EXPECT_TRUE(na == na); NativeArray<int> na2(a, 3, RelationToSourceReference()); EXPECT_TRUE(na == na2); const int b1[3] = { 0, 1, 1 }; const int b2[4] = { 0, 1, 2, 3 }; EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference())); EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy())); } TEST(NativeArrayTest, WorksForTwoDimensionalArray) { const char a[2][3] = { "hi", "lo" }; NativeArray<char[3]> na(a, 2, RelationToSourceReference()); ASSERT_EQ(2U, na.size()); EXPECT_EQ(a, na.begin()); } // Tests SkipPrefix(). TEST(SkipPrefixTest, SkipsWhenPrefixMatches) { const char* const str = "hello"; const char* p = str; EXPECT_TRUE(SkipPrefix("", &p)); EXPECT_EQ(str, p); p = str; EXPECT_TRUE(SkipPrefix("hell", &p)); EXPECT_EQ(str + 4, p); } TEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) { const char* const str = "world"; const char* p = str; EXPECT_FALSE(SkipPrefix("W", &p)); EXPECT_EQ(str, p); p = str; EXPECT_FALSE(SkipPrefix("world!", &p)); EXPECT_EQ(str, p); } diff --git a/googletest/test/gtest_xml_outfiles_test.py b/googletest/test/gtest_xml_outfiles_test.py index 524e437e..678f546c 100755 --- a/googletest/test/gtest_xml_outfiles_test.py +++ b/googletest/test/gtest_xml_outfiles_test.py @@ -1,132 +1,132 @@ #!/usr/bin/env python # # Copyright 2008, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit test for the gtest_xml_output module.""" __author__ = "keith.ray@gmail.com (Keith Ray)" import os from xml.dom import minidom, Node import gtest_test_utils import gtest_xml_test_utils GTEST_OUTPUT_SUBDIR = "xml_outfiles" GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_" GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_" EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" /> </testsuite> </testsuites> """ EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" /> </testsuite> </testsuites> """ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase): """Unit test for Google Test's XML output functionality.""" def setUp(self): # We want the trailing '/' that the last "" provides in os.path.join, for # telling Google Test to create an output directory instead of a single file # for xml output. self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(), GTEST_OUTPUT_SUBDIR, "") self.DeleteFilesAndDir() def tearDown(self): self.DeleteFilesAndDir() def DeleteFilesAndDir(self): try: os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + ".xml")) except os.error: pass try: os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + ".xml")) except os.error: pass try: os.rmdir(self.output_dir_) except os.error: pass def testOutfile1(self): self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1) def testOutfile2(self): self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2) def _TestOutFile(self, test_name, expected_xml): gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name) command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_] p = gtest_test_utils.Subprocess(command, working_dir=gtest_test_utils.GetTempDir()) self.assert_(p.exited) self.assertEquals(0, p.exit_code) # TODO(wan@google.com): libtool causes the built test binary to be # named lt-gtest_xml_outfiles_test_ instead of - # gtest_xml_outfiles_test_. To account for this possibillity, we + # gtest_xml_outfiles_test_. To account for this possibility, we # allow both names in the following code. We should remove this # hack when Chandler Carruth's libtool replacement tool is ready. output_file_name1 = test_name + ".xml" output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 output_file2 = os.path.join(self.output_dir_, output_file_name2) self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2), output_file1) expected = minidom.parseString(expected_xml) if os.path.isfile(output_file1): actual = minidom.parse(output_file1) else: actual = minidom.parse(output_file2) self.NormalizeXml(actual.documentElement) self.AssertEquivalentNodes(expected.documentElement, actual.documentElement) expected.unlink() actual.unlink() if __name__ == "__main__": os.environ["GTEST_STACK_TRACE_DEPTH"] = "0" gtest_test_utils.Main() diff --git a/googletest/test/gtest_xml_output_unittest.py b/googletest/test/gtest_xml_output_unittest.py index bcd59759..e940a5aa 100755 --- a/googletest/test/gtest_xml_output_unittest.py +++ b/googletest/test/gtest_xml_output_unittest.py @@ -1,308 +1,308 @@ #!/usr/bin/env python # # Copyright 2006, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit test for the gtest_xml_output module""" __author__ = 'eefacm@gmail.com (Sean Mcafee)' import datetime import errno import os import re import sys from xml.dom import minidom, Node import gtest_test_utils import gtest_xml_test_utils GTEST_FILTER_FLAG = '--gtest_filter' GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' GTEST_OUTPUT_FLAG = "--gtest_output" GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml" GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_" SUPPORTS_STACK_TRACES = False if SUPPORTS_STACK_TRACES: STACK_TRACE_TEMPLATE = '\nStack trace:\n*' else: STACK_TRACE_TEMPLATE = '' EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> </testsuite> <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="Fails" status="run" time="*" classname="FailedTest"> <failure message="gtest_xml_output_unittest_.cc:*
 Expected: 1
To be equal to: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected: 1 To be equal to: 2%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/> <testcase name="Fails" status="run" time="*" classname="MixedResultTest"> <failure message="gtest_xml_output_unittest_.cc:*
 Expected: 1
To be equal to: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected: 1 To be equal to: 2%(stack)s]]></failure> <failure message="gtest_xml_output_unittest_.cc:*
 Expected: 2
To be equal to: 3" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Expected: 2 To be equal to: 3%(stack)s]]></failure> </testcase> <testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/> </testsuite> <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest"> <failure message="gtest_xml_output_unittest_.cc:*
Failed
XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]></top>" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]><![CDATA[</top>%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest"> <failure message="gtest_xml_output_unittest_.cc:*
Failed
Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed Invalid characters in brackets []%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*"> <testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/> </testsuite> <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" SetUpTestCase="yes" TearDownTestCase="aye"> <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/> <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/> <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/> <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/> </testsuite> <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*"> <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/> <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/> <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/> </testsuite> <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="HasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> </testsuite> <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/0" /> </testsuite> <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/1" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/0" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/1" /> </testsuite> </testsuites>""" % {'stack': STACK_TRACE_TEMPLATE} EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> </testsuite> </testsuites>""" EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="0" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> </testsuites>""" GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): """ Unit test for Google Test's XML output functionality. """ # This test currently breaks on platforms that do not support typed and # type-parameterized tests, so we don't run it under them. if SUPPORTS_TYPED_TESTS: def testNonEmptyXmlOutput(self): """ Runs a test program that generates a non-empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1) def testEmptyXmlOutput(self): """Verifies XML output for a Google Test binary without actual tests. Runs a test program that generates an empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0) def testTimestampValue(self): """Checks whether the timestamp attribute in the XML output is valid. Runs a test program that generates an empty XML output, and checks if the timestamp attribute in the testsuites tag is valid. """ actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0) date_time_str = actual.documentElement.getAttributeNode('timestamp').value # datetime.strptime() is only available in Python 2.5+ so we have to # parse the expected datetime manually. match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) self.assertTrue( re.match, 'XML datettime string %s has incorrect format' % date_time_str) date_time_from_xml = datetime.datetime( year=int(match.group(1)), month=int(match.group(2)), day=int(match.group(3)), hour=int(match.group(4)), minute=int(match.group(5)), second=int(match.group(6))) time_delta = abs(datetime.datetime.now() - date_time_from_xml) # timestamp value should be near the current local time self.assertTrue(time_delta < datetime.timedelta(seconds=600), 'time_delta is %s' % time_delta) actual.unlink() def testDefaultOutputFile(self): """ Confirms that Google Test produces an XML output file with the expected default name if no name is explicitly specified. """ output_file = os.path.join(gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE) gtest_prog_path = gtest_test_utils.GetTestExecutablePath( 'gtest_no_test_unittest') try: os.remove(output_file) except OSError: e = sys.exc_info()[1] if e.errno != errno.ENOENT: raise p = gtest_test_utils.Subprocess( [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG], working_dir=gtest_test_utils.GetTempDir()) self.assert_(p.exited) self.assertEquals(0, p.exit_code) self.assert_(os.path.isfile(output_file)) def testSuppressedXmlOutput(self): """ Tests that no XML file is generated if the default XML listener is shut down before RUN_ALL_TESTS is invoked. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), GTEST_PROGRAM_NAME + 'out.xml') if os.path.isfile(xml_path): os.remove(xml_path) command = [GTEST_PROGRAM_PATH, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path), '--shut_down_xml'] p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: - # p.signal is avalable only if p.terminated_by_signal is True. + # p.signal is available only if p.terminated_by_signal is True. self.assertFalse( p.terminated_by_signal, '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) else: self.assert_(p.exited) self.assertEquals(1, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, 1)) self.assert_(not os.path.isfile(xml_path)) def testFilteredTestXmlOutput(self): """Verifies XML output when a filter is applied. Runs a test program that executes only some tests and verifies that non-selected tests do not show up in the XML output. """ self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0, extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) def _GetXmlOutput(self, gtest_prog_name, extra_args, expected_exit_code): """ Returns the xml output generated by running the program gtest_prog_name. Furthermore, the program's exit code must be expected_exit_code. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), gtest_prog_name + 'out.xml') gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] + extra_args) p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: self.assert_(False, '%s was killed by signal %d' % (gtest_prog_name, p.signal)) else: self.assert_(p.exited) self.assertEquals(expected_exit_code, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, expected_exit_code)) actual = minidom.parse(xml_path) return actual def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code, extra_args=None): """ Asserts that the XML document generated by running the program gtest_prog_name matches expected_xml, a string containing another XML document. Furthermore, the program's exit code must be expected_exit_code. """ actual = self._GetXmlOutput(gtest_prog_name, extra_args or [], expected_exit_code) expected = minidom.parseString(expected_xml) self.NormalizeXml(actual.documentElement) self.AssertEquivalentNodes(expected.documentElement, actual.documentElement) expected.unlink() actual.unlink() if __name__ == '__main__': os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' gtest_test_utils.Main() diff --git a/googletest/xcode/Scripts/versiongenerate.py b/googletest/xcode/Scripts/versiongenerate.py index 81de8c96..16791d25 100755 --- a/googletest/xcode/Scripts/versiongenerate.py +++ b/googletest/xcode/Scripts/versiongenerate.py @@ -1,100 +1,100 @@ #!/usr/bin/env python # # Copyright 2008, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """A script to prepare version informtion for use the gtest Info.plist file. This script extracts the version information from the configure.ac file and uses it to generate a header file containing the same information. The #defines in this header file will be included in during the generation of the Info.plist of the framework, giving the correct value to the version shown in the Finder. This script makes the following assumptions (these are faults of the script, not problems with the Autoconf): 1. The AC_INIT macro will be contained within the first 1024 characters of configure.ac 2. The version string will be 3 integers separated by periods and will be - surrounded by squre brackets, "[" and "]" (e.g. [1.0.1]). The first + surrounded by square brackets, "[" and "]" (e.g. [1.0.1]). The first segment represents the major version, the second represents the minor version and the third represents the fix version. 3. No ")" character exists between the opening "(" and closing ")" of AC_INIT, including in comments and character strings. """ import sys import re # Read the command line argument (the output directory for Version.h) if (len(sys.argv) < 3): print "Usage: versiongenerate.py input_dir output_dir" sys.exit(1) else: input_dir = sys.argv[1] output_dir = sys.argv[2] # Read the first 1024 characters of the configure.ac file config_file = open("%s/configure.ac" % input_dir, 'r') buffer_size = 1024 opening_string = config_file.read(buffer_size) config_file.close() # Extract the version string from the AC_INIT macro # The following init_expression means: -# Extract three integers separated by periods and surrounded by squre +# Extract three integers separated by periods and surrounded by square # brackets(e.g. "[1.0.1]") between "AC_INIT(" and ")". Do not be greedy # (*? is the non-greedy flag) since that would pull in everything between # the first "(" and the last ")" in the file. version_expression = re.compile(r"AC_INIT\(.*?\[(\d+)\.(\d+)\.(\d+)\].*?\)", re.DOTALL) version_values = version_expression.search(opening_string) major_version = version_values.group(1) minor_version = version_values.group(2) fix_version = version_values.group(3) # Write the version information to a header file to be included in the # Info.plist file. file_data = """// // DO NOT MODIFY THIS FILE (but you can delete it) // // This file is autogenerated by the versiongenerate.py script. This script // is executed in a "Run Script" build phase when creating gtest.framework. This // header file is not used during compilation of C-source. Rather, it simply // defines some version strings for substitution in the Info.plist. Because of -// this, we are not not restricted to C-syntax nor are we using include guards. +// this, we are not restricted to C-syntax nor are we using include guards. // #define GTEST_VERSIONINFO_SHORT %s.%s #define GTEST_VERSIONINFO_LONG %s.%s.%s """ % (major_version, minor_version, major_version, minor_version, fix_version) version_file = open("%s/Version.h" % output_dir, 'w') version_file.write(file_data) version_file.close()