diff options
author | Iain Merrick <husky@google.com> | 2010-10-19 14:37:37 +0100 |
---|---|---|
committer | Iain Merrick <husky@google.com> | 2010-10-19 14:37:37 +0100 |
commit | 3345a6884c488ff3a535c2c9acdd33d74b37e311 (patch) | |
tree | 7784b988ef1698cb6967ea1bdf07616237716c6c /testing | |
parent | efc8475837ec58186051f23bb03542620424f6ce (diff) | |
download | external_chromium-3345a6884c488ff3a535c2c9acdd33d74b37e311.zip external_chromium-3345a6884c488ff3a535c2c9acdd33d74b37e311.tar.gz external_chromium-3345a6884c488ff3a535c2c9acdd33d74b37e311.tar.bz2 |
Merge Chromium at 7.0.540.0 : Initial merge by git
Not including third_party/icu as it contains huge data files that break Gerrit, and aren't actually used.
Change-Id: I428a386e70f3b58cacd28677b8cfda282e891e15
Diffstat (limited to 'testing')
68 files changed, 2649 insertions, 4169 deletions
diff --git a/testing/gmock.gyp b/testing/gmock.gyp index 1d7d255..f879dcf 100644 --- a/testing/gmock.gyp +++ b/testing/gmock.gyp @@ -20,7 +20,6 @@ 'gmock/include/gmock/gmock-generated-matchers.h', 'gmock/include/gmock/gmock-generated-nice-strict.h', 'gmock/include/gmock/gmock-matchers.h', - 'gmock/include/gmock/gmock-printers.h', 'gmock/include/gmock/gmock-spec-builders.h', 'gmock/include/gmock/gmock.h', 'gmock/include/gmock/internal/gmock-generated-internal-utils.h', @@ -30,7 +29,6 @@ 'gmock/src/gmock-cardinalities.cc', 'gmock/src/gmock-internal-utils.cc', 'gmock/src/gmock-matchers.cc', - 'gmock/src/gmock-printers.cc', 'gmock/src/gmock-spec-builders.cc', 'gmock/src/gmock.cc', 'gmock_mutant.h', # gMock helpers diff --git a/testing/gmock.target.mk b/testing/gmock.target.mk index bb9e855..b43fc81 100644 --- a/testing/gmock.target.mk +++ b/testing/gmock.target.mk @@ -18,6 +18,7 @@ CFLAGS_Debug := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O0 \ -g @@ -51,6 +52,7 @@ CFLAGS_Release := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O2 \ -fno-ident \ @@ -72,7 +74,6 @@ INCS_Release := -Itesting/gmock \ OBJS := $(obj).target/$(TARGET)/testing/gmock/src/gmock-cardinalities.o \ $(obj).target/$(TARGET)/testing/gmock/src/gmock-internal-utils.o \ $(obj).target/$(TARGET)/testing/gmock/src/gmock-matchers.o \ - $(obj).target/$(TARGET)/testing/gmock/src/gmock-printers.o \ $(obj).target/$(TARGET)/testing/gmock/src/gmock-spec-builders.o \ $(obj).target/$(TARGET)/testing/gmock/src/gmock.o @@ -101,11 +102,12 @@ $(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD # End of this set of suffix rules ### Rules for final target. LDFLAGS_Debug := -pthread \ - -Wl,-z,noexecstack \ - -rdynamic + -Wl,-z,noexecstack LDFLAGS_Release := -pthread \ -Wl,-z,noexecstack \ + -Wl,-O1 \ + -Wl,--as-needed \ -Wl,--gc-sections LIBS := diff --git a/testing/gmock/Makefile.am b/testing/gmock/Makefile.am index 30941d4..e2a4673 100644 --- a/testing/gmock/Makefile.am +++ b/testing/gmock/Makefile.am @@ -38,7 +38,6 @@ pkginclude_HEADERS = include/gmock/gmock.h \ include/gmock/gmock-generated-nice-strict.h \ include/gmock/gmock-matchers.h \ include/gmock/gmock-more-actions.h \ - include/gmock/gmock-printers.h \ include/gmock/gmock-spec-builders.h pkginclude_internaldir = $(pkgincludedir)/internal @@ -76,15 +75,26 @@ test_gmock_link_test_SOURCES = test/gmock_link_test.cc \ test/gmock_link_test.h test_gmock_link_test_LDADD = $(GTEST_LIBS) lib/libgmock_main.la +# Tests that fused gmock files compile and work. +TESTS += test/gmock_fused_test +check_PROGRAMS += test/gmock_fused_test +test_gmock_fused_test_SOURCES = fused-src/gmock-gtest-all.cc \ + fused-src/gmock_main.cc \ + fused-src/gmock/gmock.h \ + fused-src/gtest/gtest.h \ + test/gmock_test.cc +test_gmock_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src" + # Google Mock source files that we don't compile directly. -EXTRA_DIST += \ +GMOCK_SOURCE_INGLUDES = \ src/gmock.cc \ src/gmock-cardinalities.cc \ src/gmock-internal-utils.cc \ src/gmock-matchers.cc \ - src/gmock-printers.cc \ src/gmock-spec-builders.cc +EXTRA_DIST += $(GMOCK_SOURCE_INGLUDES) + # C++ tests that we don't compile using autotools. EXTRA_DIST += \ test/gmock_all_test.cc \ @@ -98,9 +108,7 @@ EXTRA_DIST += \ test/gmock-matchers_test.cc \ test/gmock-more-actions_test.cc \ test/gmock-nice-strict_test.cc \ - test/gmock-port_test.cc \ - test/gmock-printers_test.cc \ - test/gmock_test.cc + test/gmock-port_test.cc # Python tests, which we don't run using autotools. EXTRA_DIST += \ @@ -126,9 +134,7 @@ EXTRA_DIST += include/gmock/gmock-generated-actions.h.pump \ include/gmock/internal/gmock-generated-internal-utils.h.pump # Script for fusing Google Mock and Google Test source files. -EXTRA_DIST += \ - scripts/fuse_gmock_files.py \ - scripts/test/Makefile +EXTRA_DIST += scripts/fuse_gmock_files.py # The Google Mock Generator tool from the cppclean project. EXTRA_DIST += \ @@ -152,3 +158,30 @@ EXTRA_DIST += \ msvc/gmock_main.vcproj \ msvc/gmock-spec-builders_test.vcproj \ msvc/gmock_test.vcproj + +# gmock_test.cc does not really depend on files generated by the +# fused-gmock-internal rule. However, gmock_test.o does, and it is +# important to include test/gmock_test.cc as part of this rule in order to +# prevent compiling gmock_test.o until all dependent files have been +# generated. +$(test_gmock_fused_test_SOURCES): fused-gmock-internal + +# TODO(vladl@google.com): Find a way to add Google Tests's sources here. +fused-gmock-internal: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \ + $(lib_libgmock_la_SOURCES) $(GMOCK_SOURCE_INGLUDES) \ + $(lib_libgmock_main_la_SOURCES) \ + scripts/fuse_gmock_files.py + mkdir -p "$(srcdir)/fused-src" + chmod -R u+w "$(srcdir)/fused-src" + rm -f "$(srcdir)/fused-src/gtest/gtest.h" + rm -f "$(srcdir)/fused-src/gmock/gmock.h" + rm -f "$(srcdir)/fused-src/gmock-gtest-all.cc" + "$(srcdir)/scripts/fuse_gmock_files.py" "$(srcdir)/fused-src" + cp -f "$(srcdir)/src/gmock_main.cc" "$(srcdir)/fused-src" + +maintainer-clean-local: + rm -rf "$(srcdir)/fused-src" + +# Death tests may produce core dumps in the build directory. In case +# this happens, clean them to keep distcleancheck happy. +CLEANFILES = core diff --git a/testing/gmock/README b/testing/gmock/README index 4b3efd8..8e4150a 100644 --- a/testing/gmock/README +++ b/testing/gmock/README @@ -1,13 +1,16 @@ Google C++ Mocking Framework ============================ + http://code.google.com/p/googlemock/ Overview -------- -Google's framework for writing and using C++ mock classes on Linux, -Mac OS X, and Windows. Inspired by jMock, EasyMock, and Hamcrest, and -designed with C++'s specifics in mind, it can help you derive better -designs of your system and write better tests. + +Google's framework for writing and using C++ mock classes on a variety +of platforms (Linux, Mac OS X, Windows, Windows CE, Symbian, etc). +Inspired by jMock, EasyMock, and Hamcrest, and designed with C++'s +specifics in mind, it can help you derive better designs of your +system and write better tests. Google Mock: @@ -25,22 +28,23 @@ Google Mock: - does not use exceptions, and - is easy to learn and use. -Please see the project page above for more information as well as mailing lists -for questions, discussions, and development. There is also an IRC channel on -OFTC (irc.oftc.net) #gtest available. Please join us! +Please see the project page above for more information as well as the +mailing list for questions, discussions, and development. There is +also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please +join us! Please note that code under scripts/generator/ is from the cppclean project (http://code.google.com/p/cppclean/) and under the Apache License, which is different from Google Mock's license. -Requirements ------------- -Google Mock is not a testing framework itself. Instead, it needs a -testing framework for writing tests. It works with Google Test -(http://code.google.com/p/googletest/) out of the box. You can use -either the copy of Google Test that comes with Google Mock, or a -compatible version you already have. This version of Google Mock -requires Google Test 1.4.0. +Requirements for End Users +-------------------------- + +Google Mock is implemented on top of the Google Test C++ testing +framework (http://code.google.com/p/googletest/), and includes the +latter as part of the SVN repositary and distribution package. You +must use the bundled version of Google Test when using Google Mock, or +you may get compiler/linker errors. You can also easily configure Google Mock to work with another testing framework of your choice; although it will still need Google Test as @@ -52,90 +56,186 @@ Google Mock depends on advanced C++ features and thus requires a more modern compiler. The following are needed to use Google Mock: ### Linux Requirements ### + These are the base requirements to build and use Google Mock from a source package (as described below): + * GNU-compatible Make or "gmake" * POSIX-standard shell * POSIX(-2) Regular Expressions (regex.h) - * gcc 3.4 or newer. - -Furthermore, if you are building Google Mock from a VCS Checkout (also -described below), there are further requirements: - * Automake version 1.9 or newer - * Autoconf version 2.59 or newer - * Libtool / Libtoolize - * Python version 2.3 or newer + * C++98-standard-compliant compiler (e.g. GCC 3.4 or newer) ### Windows Requirements ### + * Microsoft Visual C++ 8.0 SP1 or newer ### Mac OS X Requirements ### + * Mac OS X 10.4 Tiger or newer * Developer Tools Installed +Requirements for Contributors +----------------------------- + +We welcome patches. If you plan to contribute a patch, you need to +build Google Mock and its own tests from an SVN checkout (described +below), which has further requirements: + + * Automake version 1.9 or newer + * Autoconf version 2.59 or newer + * Libtool / Libtoolize + * Python version 2.3 or newer (for running some of the tests and + re-generating certain source files from templates) + Getting the Source ------------------ -There are two primary ways of getting Google Mock's source code: you can -download a source release in your preferred archive format, or directly check -out the source from a Version Control System (VCS, we use Google Code's -Subversion hosting). The VCS checkout requires a few extra steps and some extra -software packages on your system, but lets you track development, and make -patches to contribute much more easily, so we highly encourage it. - -### VCS Checkout: ### -The first step is to select whether you want to check out the main line of -development on Google Mock, or one of the released branches. The former will be -much more active and have the latest features, but the latter provides much -more stability and predictability. Choose whichever fits your needs best, and -proceed with the following Subversion commands: - svn checkout http://googlemock.googlecode.com/svn/trunk/ gmock-svn +There are two primary ways of getting Google Mock's source code: you +can download a stable source release in your preferred archive format, +or directly check out the source from our Subversion (SVN) repositary. +The SVN checkout requires a few extra steps and some extra software +packages on your system, but lets you track development and make +patches much more easily, so we highly encourage it. -or for a release version X.Y.*'s branch: +### Source Package ### - svn checkout http://googlemock.googlecode.com/svn/branches/release-X.Y/ \ - gmock-X.Y-svn +Google Mock is released in versioned source packages which can be +downloaded from the download page [1]. Several different archive +formats are provided, but the only difference is the tools needed to +extract their contents, and the size of the resulting file. Download +whichever you are most comfortable with. -Next you will need to prepare the GNU Autotools build system, if you -are using Linux or Mac OS X. Enter the target directory of the -checkout command you used ('gmock-svn' or 'gmock-X.Y-svn' above) and -proceed with the following command: + [1] http://code.google.com/p/googlemock/downloads/list + +Once downloaded expand the archive using whichever tools you prefer +for that type. This will always result in a new directory with the +name "gmock-X.Y.Z" which contains all of the source code. Here are +some examples on Linux: + + tar -xvzf gmock-X.Y.Z.tar.gz + tar -xvjf gmock-X.Y.Z.tar.bz2 + unzip gmock-X.Y.Z.zip + +### SVN Checkout ### + +To check out the main branch (also known as the "trunk") of Google +Mock, run the following Subversion command: + + svn checkout http://googlemock.googlecode.com/svn/trunk/ gmock-svn + +If you are using a *nix system and plan to use the GNU Autotools build +system to build Google Mock (described below), you'll need to +configure it now. Otherwise you are done with getting the source +files. + +To prepare the Autotools build system, enter the target directory of +the checkout command you used ('gmock-svn') and proceed with the +following command: autoreconf -fvi -Once you have completed this step, you are ready to build the library. Note -that you should only need to complete this step once. The subsequent `make' -invocations will automatically re-generate the bits of the build system that -need to be changed. +Once you have completed this step, you are ready to build the library. +Note that you should only need to complete this step once. The +subsequent 'make' invocations will automatically re-generate the bits +of the build system that need to be changed. -If your system uses older versions of the autotools, the above command will -fail. You may need to explicitly specify a version to use. For instance, if you -have both GNU Automake 1.4 and 1.9 installed and `automake' would invoke the -1.4, use instead: +If your system uses older versions of the autotools, the above command +will fail. You may need to explicitly specify a version to use. For +instance, if you have both GNU Automake 1.4 and 1.9 installed and +'automake' would invoke the 1.4, use instead: AUTOMAKE=automake-1.9 ACLOCAL=aclocal-1.9 autoreconf -fvi Make sure you're using the same version of automake and aclocal. -### Source Package: ### -Google Mock is also released in source packages which can be downloaded from -its Google Code download page[1]. Several different archive formats are -provided, but the only difference is the tools needed to extract their -contents, and the size of the resulting file. Download whichever you are most -comfortable with. +Setting up the Build +-------------------- - [1] Google Mock Downloads: http://code.google.com/p/googlemock/downloads/list +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. -Once downloaded expand the archive using whichever tools you prefer for that -type. This will always result in a new directory with the name "gmock-X.Y.Z" -which contains all of the source code. Here are some examples in Linux: +### Generic Build Instructions ### - tar -xvzf gmock-X.Y.Z.tar.gz - tar -xvjf gmock-X.Y.Z.tar.bz2 - unzip gmock-X.Y.Z.zip +This section shows how you can integrate Google Mock into your +existing build system. + +Suppose you put Google Mock in directory ${GMOCK_DIR} and Google Test +in ${GTEST_DIR} (the latter is ${GMOCK_DIR}/gtest by default). To +build Google Mock, create a library build target (or a project as +called by Visual Studio and Xcode) to compile + + ${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc + +with + + ${GTEST_DIR}/include, ${GTEST_DIR}, ${GMOCK_DIR}/include, and ${GMOCK_DIR} + +in the header search path. Assuming a Linux-like system and gcc, +something like the following will do: + + g++ -I${GTEST_DIR}/include -I${GTEST_DIR} -I${GMOCK_DIR}/include \ + -I${GMOCK_DIR} -c ${GTEST_DIR}/src/gtest-all.cc + g++ -I${GTEST_DIR}/include -I${GTEST_DIR} -I${GMOCK_DIR}/include \ + -I${GMOCK_DIR} -c ${GMOCK_DIR}/src/gmock-all.cc + ar -rv libgmock.a gtest-all.o gmock-all.o + +Next, you should compile your test source file with +${GTEST_DIR}/include and ${GMOCK_DIR}/include in the header search +path, and link it with gmock and any other necessary libraries: + + g++ -I${GTEST_DIR}/include -I${GMOCK_DIR}/include \ + path/to/your_test.cc libgmock.a -o your_test + +As an example, the make/ directory contains a Makefile that you can +use to build Google Mock on systems where GNU make is available +(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google +Mock's own tests. Instead, it just builds the Google Mock library and +a sample test. You can use it as a starting point for your own build +script. + +If the default settings are correct for your environment, the +following commands should succeed: + + cd ${GMOCK_DIR}/make + make + ./gmock_test + +If you see errors, try to tweak the contents of make/Makefile to make +them go away. There are instructions in make/Makefile on how to do +it. + +### Windows ### + +The msvc/ directory contains VC++ 2005 projects for building Google +Mock and selected tests. + +Open msvc/gmock.sln and build the library and tests. 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 and select it. + * In Project Properties | Configuration Properties | General | Additional + Include Directories, type <path to Google Mock>/include. + +Tweaking Google Mock +-------------------- + +Google Mock can be used in diverse environments. The default +configuration may not work (or may not work well) out of the box in +some environments. However, you can easily tweak Google Mock by +defining control macros on the compiler command line. Generally, +these macros are named like GTEST_XYZ and you define them to either 1 +or 0 to enable or disable a certain feature. + +We list the most frequently used macros below. For a complete list, +see file ${GTEST_DIR}/include/gtest/internal/gtest-port.h. + +### Choosing a TR1 Tuple Library ### -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 @@ -146,104 +246,85 @@ 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 (this requirement is new in -Google Test 1.4.0 and Google Mock 1.2.0, so you may need to take care -of it when upgrading from an earlier version), or the two 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. +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. -Building the Source -------------------- -### Linux and Mac OS X (without Xcode) ### -There are two primary options for building the source at this point: build it -inside the source code tree, or in a separate directory. We recommend building -in a separate directory as that tends to produce both more consistent results -and be easier to clean up should anything go wrong, but both patterns are -supported. The only hard restriction is that while the build directory can be -a subdirectory of the source directory, the opposite is not possible and will -result in errors. Once you have selected where you wish to build Google Mock, -create the directory if necessary, and enter it. The following steps apply for -either approach by simply substituting the shell variable SRCDIR with "." for -building inside the source directory, and the relative path to the source -directory otherwise. - - ${SRCDIR}/configure # Standard GNU configure script, --help for more info - -Once you have successfully configured Google Mock, the build steps are standard -for GNU-style OSS packages. - - make # Standard makefile following GNU conventions - make check # Builds and runs all tests - all should pass +### Tweaking Google Test ### -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. +Most of Google Test's control macros apply to Google Mock as well. +Please see file ${GTEST_DIR}/README for how to tweak them. -### Windows ### -The msvc/ directory contains VC++ 2005 projects for building Google -Mock and selected tests. +Upgrading from an Earlier Version +--------------------------------- -If you want to use a version of Google Test other then the one bundled with -Google Mock, change the value of the GTestDir macro in gmock_config.vsprop -to point to the new location. +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. -Open msvc/gmock.sln and build the library and tests. 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 and select it. - * In Project Properties | Configuration Properties | General | Additional - Include Directories, type <path to Google Mock>/include. +### Upgrading from 1.1.0 or Earlier ### -TODO(wan@google.com): update the .vsprops and .vcproj files such that the -last step is unnecessary. +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". -### Using GNU Make ### -The make/ directory contains a Makefile that you can use to build -Google Mock on systems where GNU make is available (e.g. Linux and Mac -OS X). It doesn't try to build Google Mock's own tests. Instead, it -just builds the Google Mock libraries and some sample tests. You can -use it as a starting point for your own Makefile. +### Upgrading from 1.4.0 or Earlier ### -If the default settings are correct for your environment, the -following commands should succeed: +On platforms where the pthread library is available, Google Test and +Google Mock use it in order to be thread-safe. For this to work, you +may need to tweak your compiler and/or linker flags. Please see the +"Multi-threaded Tests" section in file ${GTEST_DIR}/README for what +you may need to do. - cd ${SRCDIR}/make - make - ./gmock_test +If you have custom matchers defined using MatcherInterface or +MakePolymorphicMatcher(), you'll need to update their definitions to +use the new matcher API [2]. Matchers defined using MATCHER() or +MATCHER_P*() aren't affected. -If you see errors, try to tweak the contents of make/Makefile to make -them go away. There are instructions in make/Makefile on how to do -it. + [2] http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Monomorphic_Matchers, + http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Polymorphic_Matchers -### Using Your Own Build System ### -If none of the build solutions we provide works for you, or if you -prefer your own build system, you just need to compile -${GTEST_SRCDIR}/src/gtest-all.cc (where GTEST_SRCDIR is the root of -the Google Test source tree) and src/gmock-all.cc into a library and -link your tests with it. Assuming a Linux-like system and gcc, -something like the following will do: +Developing Google Mock +---------------------- - cd ${SRCDIR} - g++ -I. -I./include -I${GTEST_SRCDIR} -I${GTEST_SRCDIR}/include \ - -c {GTEST_SRCDIR}/src/gtest-all.cc - g++ -I. -I./include -I${GTEST_SRCDIR} -I${GTEST_SRCDIR}/include \ - -c src/gmock-all.cc - ar -rv libgmock.a gtest-all.o gmock-all.o - g++ -I. -I./include -I${GTEST_SRCDIR} -I${GTEST_SRCDIR}/include \ - path/to/your_test.cc libgmock.a -o your_test +This section discusses how to make your own changes to Google Mock. + +### Testing Google Mock Itself ### + +To make sure your changes work as intended and don't break existing +functionality, you'll want to compile and run Google Test's own tests. +For that you'll need Autotools. First, make sure you have followed +the instructions in section "SVN Checkout" to configure Google Mock. +Then, create a build output directory and enter it. Next, + + ${GMOCK_DIR}/configure # Standard GNU configure script, --help for more info + +Once you have successfully configured Google Mock, the build steps are +standard for GNU-style OSS packages. + + make # Standard makefile following GNU conventions + make check # Builds and runs all tests - all should pass. + +Note that when building your project against Google Mock, you are building +against Google Test as well. There is no need to configure Google Test +separately. + +### Regenerating Source Files ### -Regenerating Source Files -------------------------- Some of Google Mock's source files are generated from templates (not in the C++ sense) using a script. A template file is named FOO.pump, where FOO is the name of the file it will generate. For example, the @@ -251,12 +332,21 @@ file include/gmock/gmock-generated-actions.h.pump is used to generate gmock-generated-actions.h in the same directory. Normally you don't need to worry about regenerating the source files, -unless you need to modify them (e.g. if you are working on a patch for -Google Mock). In that case, you should modify the corresponding .pump -files instead and run the 'pump' script (for Pump is Useful for Meta -Programming) to regenerate them. We are still working on releasing -the script and its documentation. If you need it now, please email -googlemock@googlegroups.com such that we know to make it happen -sooner. +unless you need to modify them. In that case, you should modify the +corresponding .pump files instead and run the 'pump' script (for Pump +is Useful for Meta Programming) to regenerate them. You can find +pump.py in the ${GTEST_DIR}/scripts/ directory. Read the Pump manual +[3] for how to use it. + + [3] http://code.google.com/p/googletest/wiki/PumpManual. + +### Contributing a Patch ### + +We welcome patches. Please read the Google Mock developer's guide [4] +for how you can contribute. In particular, make sure you have signed +the Contributor License Agreement, or we won't be able to accept the +patch. + + [4] http://code.google.com/p/googlemock/wiki/DevGuide Happy testing! diff --git a/testing/gmock/include/gmock/gmock-actions.h b/testing/gmock/include/gmock/gmock-actions.h index 007ad9d..9fe1964 100644 --- a/testing/gmock/include/gmock/gmock-actions.h +++ b/testing/gmock/include/gmock/gmock-actions.h @@ -43,7 +43,6 @@ #include <errno.h> #endif -#include <gmock/gmock-printers.h> #include <gmock/internal/gmock-internal-utils.h> #include <gmock/internal/gmock-port.h> @@ -477,7 +476,7 @@ class ReturnAction { // 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; - GMOCK_COMPILE_ASSERT_( + GTEST_COMPILE_ASSERT_( !internal::is_reference<Result>::value, use_ReturnRef_instead_of_Return_to_return_a_reference); return Action<F>(new Impl<F>(value_)); @@ -504,7 +503,7 @@ class ReturnAction { virtual Result Perform(const ArgumentTuple&) { return value_; } private: - GMOCK_COMPILE_ASSERT_(!internal::is_reference<Result>::value, + GTEST_COMPILE_ASSERT_(!internal::is_reference<Result>::value, Result_cannot_be_a_reference_type); Result value_; @@ -522,7 +521,7 @@ class ReturnNullAction { // Allows ReturnNull() to be used in any pointer-returning function. template <typename Result, typename ArgumentTuple> static Result Perform(const ArgumentTuple&) { - GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value, + GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value, ReturnNull_can_be_used_to_return_a_pointer_only); return NULL; } @@ -555,7 +554,7 @@ class ReturnRefAction { // 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. - GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value, + GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value, use_Return_instead_of_ReturnRef_to_return_a_value); return Action<F>(new Impl<F>(ref_)); } diff --git a/testing/gmock/include/gmock/gmock-generated-function-mockers.h b/testing/gmock/include/gmock/gmock-generated-function-mockers.h index 3b2ede1..58be7e1 100644 --- a/testing/gmock/include/gmock/gmock-generated-function-mockers.h +++ b/testing/gmock/include/gmock/gmock-generated-function-mockers.h @@ -344,7 +344,7 @@ using internal::FunctionMocker; // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD0_(tn, constness, ct, Method, F) \ GMOCK_RESULT_(tn, F) ct Method() constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 0, \ this_method_does_not_take_0_arguments); \ GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ @@ -359,7 +359,7 @@ using internal::FunctionMocker; // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD1_(tn, constness, ct, Method, F) \ GMOCK_RESULT_(tn, F) ct Method(GMOCK_ARG_(tn, F, 1) gmock_a1) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 1, \ this_method_does_not_take_1_argument); \ GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ @@ -376,7 +376,7 @@ using internal::FunctionMocker; #define GMOCK_METHOD2_(tn, constness, ct, Method, F) \ GMOCK_RESULT_(tn, F) ct Method(GMOCK_ARG_(tn, F, 1) gmock_a1, \ GMOCK_ARG_(tn, F, 2) gmock_a2) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 2, \ this_method_does_not_take_2_arguments); \ GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ @@ -395,7 +395,7 @@ using internal::FunctionMocker; GMOCK_RESULT_(tn, F) ct Method(GMOCK_ARG_(tn, F, 1) gmock_a1, \ GMOCK_ARG_(tn, F, 2) gmock_a2, \ GMOCK_ARG_(tn, F, 3) gmock_a3) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 3, \ this_method_does_not_take_3_arguments); \ GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ @@ -417,7 +417,7 @@ using internal::FunctionMocker; GMOCK_ARG_(tn, F, 2) gmock_a2, \ GMOCK_ARG_(tn, F, 3) gmock_a3, \ GMOCK_ARG_(tn, F, 4) gmock_a4) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 4, \ this_method_does_not_take_4_arguments); \ GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ @@ -442,7 +442,7 @@ using internal::FunctionMocker; GMOCK_ARG_(tn, F, 3) gmock_a3, \ GMOCK_ARG_(tn, F, 4) gmock_a4, \ GMOCK_ARG_(tn, F, 5) gmock_a5) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 5, \ this_method_does_not_take_5_arguments); \ GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ @@ -469,7 +469,7 @@ using internal::FunctionMocker; GMOCK_ARG_(tn, F, 4) gmock_a4, \ GMOCK_ARG_(tn, F, 5) gmock_a5, \ GMOCK_ARG_(tn, F, 6) gmock_a6) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 6, \ this_method_does_not_take_6_arguments); \ GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ @@ -498,7 +498,7 @@ using internal::FunctionMocker; GMOCK_ARG_(tn, F, 5) gmock_a5, \ GMOCK_ARG_(tn, F, 6) gmock_a6, \ GMOCK_ARG_(tn, F, 7) gmock_a7) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 7, \ this_method_does_not_take_7_arguments); \ GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ @@ -529,7 +529,7 @@ using internal::FunctionMocker; GMOCK_ARG_(tn, F, 6) gmock_a6, \ GMOCK_ARG_(tn, F, 7) gmock_a7, \ GMOCK_ARG_(tn, F, 8) gmock_a8) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 8, \ this_method_does_not_take_8_arguments); \ GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ @@ -562,7 +562,7 @@ using internal::FunctionMocker; GMOCK_ARG_(tn, F, 7) gmock_a7, \ GMOCK_ARG_(tn, F, 8) gmock_a8, \ GMOCK_ARG_(tn, F, 9) gmock_a9) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 9, \ this_method_does_not_take_9_arguments); \ GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ @@ -598,7 +598,7 @@ using internal::FunctionMocker; GMOCK_ARG_(tn, F, 8) gmock_a8, \ GMOCK_ARG_(tn, F, 9) gmock_a9, \ GMOCK_ARG_(tn, F, 10) gmock_a10) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == 10, \ this_method_does_not_take_10_arguments); \ GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ diff --git a/testing/gmock/include/gmock/gmock-generated-function-mockers.h.pump b/testing/gmock/include/gmock/gmock-generated-function-mockers.h.pump index 619debd..20a4454 100644 --- a/testing/gmock/include/gmock/gmock-generated-function-mockers.h.pump +++ b/testing/gmock/include/gmock/gmock-generated-function-mockers.h.pump @@ -132,7 +132,7 @@ $var matcher_as = [[$for j, \ // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, F) \ GMOCK_RESULT_(tn, F) ct Method($arg_as) constness { \ - GMOCK_COMPILE_ASSERT_(::std::tr1::tuple_size< \ + GTEST_COMPILE_ASSERT_(::std::tr1::tuple_size< \ tn ::testing::internal::Function<F>::ArgumentTuple>::value == $i, \ this_method_does_not_take_$i[[]]_argument[[$if i != 1 [[s]]]]); \ GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \ diff --git a/testing/gmock/include/gmock/gmock-generated-matchers.h b/testing/gmock/include/gmock/gmock-generated-matchers.h index 9e5bede..2790e06 100644 --- a/testing/gmock/include/gmock/gmock-generated-matchers.h +++ b/testing/gmock/include/gmock/gmock-generated-matchers.h @@ -42,7 +42,6 @@ #include <string> #include <vector> #include <gmock/gmock-matchers.h> -#include <gmock/gmock-printers.h> namespace testing { namespace internal { @@ -222,7 +221,7 @@ template <class ArgsTuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> { public: // ArgsTuple may have top-level const or reference modifiers. - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(ArgsTuple)) RawArgsTuple; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple; typedef typename internal::TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9>::type SelectedArgs; typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher; @@ -315,8 +314,7 @@ class ElementsAreMatcher1 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -344,8 +342,7 @@ class ElementsAreMatcher2 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -372,8 +369,7 @@ class ElementsAreMatcher3 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -402,8 +398,7 @@ class ElementsAreMatcher4 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -434,8 +429,7 @@ class ElementsAreMatcher5 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -470,8 +464,7 @@ class ElementsAreMatcher6 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -508,8 +501,7 @@ class ElementsAreMatcher7 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -548,8 +540,7 @@ class ElementsAreMatcher8 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -591,8 +582,7 @@ class ElementsAreMatcher9 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -636,8 +626,7 @@ class ElementsAreMatcher10 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; diff --git a/testing/gmock/include/gmock/gmock-generated-matchers.h.pump b/testing/gmock/include/gmock/gmock-generated-matchers.h.pump index 07a51a3..db498ec 100644 --- a/testing/gmock/include/gmock/gmock-generated-matchers.h.pump +++ b/testing/gmock/include/gmock/gmock-generated-matchers.h.pump @@ -44,7 +44,6 @@ $$ }} This line fixes auto-indentation of the following code in Emacs. #include <string> #include <vector> #include <gmock/gmock-matchers.h> -#include <gmock/gmock-printers.h> namespace testing { namespace internal { @@ -108,7 +107,7 @@ template <class ArgsTuple$for i [[, int k$i = -1]]> class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> { public: // ArgsTuple may have top-level const or reference modifiers. - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(ArgsTuple)) RawArgsTuple; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple; typedef typename internal::TupleFields<RawArgsTuple, $ks>::type SelectedArgs; typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher; @@ -201,8 +200,7 @@ class ElementsAreMatcher$i { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; diff --git a/testing/gmock/include/gmock/gmock-matchers.h b/testing/gmock/include/gmock/gmock-matchers.h index 66efecd..2a42bf9 100644 --- a/testing/gmock/include/gmock/gmock-matchers.h +++ b/testing/gmock/include/gmock/gmock-matchers.h @@ -43,9 +43,9 @@ #include <ostream> // NOLINT #include <sstream> #include <string> +#include <utility> #include <vector> -#include <gmock/gmock-printers.h> #include <gmock/internal/gmock-internal-utils.h> #include <gmock/internal/gmock-port.h> #include <gtest/gtest.h> @@ -419,20 +419,20 @@ class SafeMatcherCastImpl { template <typename U> static inline Matcher<T> Cast(const Matcher<U>& matcher) { // Enforce that T can be implicitly converted to U. - GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value), + 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. - GMOCK_COMPILE_ASSERT_( + GTEST_COMPILE_ASSERT_( internal::is_reference<T>::value || !internal::is_reference<U>::value, cannot_convert_non_referentce_arg_to_reference); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT; - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU; + 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; - GMOCK_COMPILE_ASSERT_( + GTEST_COMPILE_ASSERT_( kTIsOther || kUIsOther || (internal::LosslessArithmeticConvertible<RawT, RawU>::value), conversion_of_arithmetic_types_must_be_lossless); @@ -566,7 +566,7 @@ bool TupleMatches(const MatcherTuple& matcher_tuple, using ::std::tr1::tuple_size; // Makes sure that matcher_tuple and value_tuple have the same // number of fields. - GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value == + 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>:: @@ -703,11 +703,11 @@ class AnythingMatcher { } \ virtual void DescribeTo(::std::ostream* os) const { \ *os << relation " "; \ - UniversalPrinter<Rhs>::Print(rhs_, os); \ + UniversalPrint(rhs_, os); \ } \ virtual void DescribeNegationTo(::std::ostream* os) const { \ *os << negated_relation " "; \ - UniversalPrinter<Rhs>::Print(rhs_, os); \ + UniversalPrint(rhs_, os); \ } \ private: \ Rhs rhs_; \ @@ -911,7 +911,7 @@ class StrEqualityMatcher { if (!case_sensitive_) { *os << "(ignoring case) "; } - UniversalPrinter<StringType>::Print(string_, os); + UniversalPrint(string_, os); } const StringType string_; @@ -948,12 +948,12 @@ class HasSubstrMatcher { // Describes what this matcher matches. void DescribeTo(::std::ostream* os) const { *os << "has substring "; - UniversalPrinter<StringType>::Print(substring_, os); + UniversalPrint(substring_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "has no substring "; - UniversalPrinter<StringType>::Print(substring_, os); + UniversalPrint(substring_, os); } private: @@ -989,12 +989,12 @@ class StartsWithMatcher { void DescribeTo(::std::ostream* os) const { *os << "starts with "; - UniversalPrinter<StringType>::Print(prefix_, os); + UniversalPrint(prefix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't start with "; - UniversalPrinter<StringType>::Print(prefix_, os); + UniversalPrint(prefix_, os); } private: @@ -1029,12 +1029,12 @@ class EndsWithMatcher { void DescribeTo(::std::ostream* os) const { *os << "ends with "; - UniversalPrinter<StringType>::Print(suffix_, os); + UniversalPrint(suffix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't end with "; - UniversalPrinter<StringType>::Print(suffix_, os); + UniversalPrint(suffix_, os); } private: @@ -1096,38 +1096,46 @@ class MatchesRegexMatcher { // // We define this as a macro in order to eliminate duplicated source // code. -#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \ +#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \ class name##2Matcher { \ public: \ template <typename T1, typename T2> \ + operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \ + return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \ + } \ + template <typename T1, typename T2> \ operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \ - return MakeMatcher(new Impl<T1, T2>); \ + return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \ } \ private: \ - template <typename T1, typename T2> \ - class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \ + template <typename Tuple> \ + class Impl : public MatcherInterface<Tuple> { \ public: \ virtual bool MatchAndExplain( \ - const ::std::tr1::tuple<T1, T2>& args, \ + Tuple args, \ MatchResultListener* /* listener */) const { \ return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \ } \ virtual void DescribeTo(::std::ostream* os) const { \ - *os << "are a pair (x, y) where x " #op " y"; \ + *os << "are " relation; \ } \ virtual void DescribeNegationTo(::std::ostream* os) const { \ - *os << "are a pair (x, y) where x " #op " y is false"; \ + *os << "aren't " relation; \ } \ }; \ } // Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively. -GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==); -GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=); -GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >); -GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=); -GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <); -GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=); +GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair"); +GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( + Ge, >=, "a pair where the first >= the second"); +GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( + Gt, >, "a pair where the first > the second"); +GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( + Le, <=, "a pair where the first <= the second"); +GMOCK_IMPLEMENT_COMPARISON2_MATCHER_( + Lt, <, "a pair where the first < the second"); +GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair"); #undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_ @@ -1604,8 +1612,8 @@ class PointeeMatcher { template <typename Pointer> class Impl : public MatcherInterface<Pointer> { public: - typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT - GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee; + typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT + GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee; explicit Impl(const InnerMatcher& matcher) : matcher_(MatcherCast<const Pointee&>(matcher)) {} @@ -1663,7 +1671,7 @@ class FieldMatcher { bool MatchAndExplain(const T& value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: - is_pointer<GMOCK_REMOVE_CONST_(T)>::type(), + is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } @@ -1702,9 +1710,9 @@ 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 GMOCK_REFERENCE_TO_CONST, which works regardless of + // need GTEST_REFERENCE_TO_CONST, which works regardless of // PropertyType being a reference or not. - typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; + typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; PropertyMatcher(PropertyType (Class::*property)() const, const Matcher<RefToConstProperty>& matcher) @@ -1724,7 +1732,7 @@ class PropertyMatcher { bool MatchAndExplain(const T&value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: - is_pointer<GMOCK_REMOVE_CONST_(T)>::type(), + is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } @@ -1874,25 +1882,25 @@ class ContainerEqMatcher { explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. - testing::StaticAssertTypeEq<Container, - GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>(); + (void)testing::StaticAssertTypeEq<Container, + GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>(); } void DescribeTo(::std::ostream* os) const { *os << "equals "; - UniversalPrinter<StlContainer>::Print(rhs_, os); + UniversalPrint(rhs_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "does not equal "; - UniversalPrinter<StlContainer>::Print(rhs_, os); + UniversalPrint(rhs_, os); } template <typename LhsContainer> bool MatchAndExplain(const LhsContainer& lhs, MatchResultListener* listener) const { - // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug + // 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<GMOCK_REMOVE_CONST_(LhsContainer)> + typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); @@ -1914,8 +1922,7 @@ class ContainerEqMatcher { *os << "which has these unexpected elements: "; printed_header = true; } - UniversalPrinter<typename LhsStlContainer::value_type>:: - Print(*it, os); + UniversalPrint(*it, os); } } @@ -1933,7 +1940,7 @@ class ContainerEqMatcher { << " doesn't have these expected elements: "; printed_header2 = true; } - UniversalPrinter<typename StlContainer::value_type>::Print(*it, os); + UniversalPrint(*it, os); } } } @@ -1947,55 +1954,218 @@ class ContainerEqMatcher { GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher); }; -// Implements Contains(element_matcher) for the given argument type Container. +// 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 std::tr1::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 ContainsMatcherImpl : public MatcherInterface<Container> { +class QuantifierMatcherImpl : public MatcherInterface<Container> { public: - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer; + 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 ContainsMatcherImpl(InnerMatcher inner_matcher) + explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) : inner_matcher_( - testing::SafeMatcherCast<const Element&>(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 "; - inner_matcher_.DescribeTo(os); + this->inner_matcher_.DescribeTo(os); } - // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't contain any element that "; - inner_matcher_.DescribeTo(os); + this->inner_matcher_.DescribeTo(os); } virtual bool MatchAndExplain(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; - if (inner_matcher_.MatchAndExplain(*it, &inner_listener)) { - *listener << "whose element #" << i << " matches"; - PrintIfNotEmpty(inner_listener.str(), listener->stream()); - return true; - } - } - return false; + return this->MatchAndExplainImpl(false, container, listener); } private: - const Matcher<const Element&> inner_matcher_; - 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 { @@ -2013,6 +2183,23 @@ class ContainsMatcher { 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 @@ -2020,7 +2207,7 @@ class ContainsMatcher { template <typename PairType> class KeyMatcherImpl : public MatcherInterface<PairType> { public: - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type KeyType; template <typename InnerMatcher> @@ -2082,7 +2269,7 @@ class KeyMatcher { template <typename PairType> class PairMatcherImpl : public MatcherInterface<PairType> { public: - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type FirstType; typedef typename RawPairType::second_type SecondType; @@ -2189,7 +2376,7 @@ class PairMatcher { template <typename Container> class ElementsAreMatcherImpl : public MatcherInterface<Container> { public: - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; @@ -2308,8 +2495,7 @@ class ElementsAreMatcher0 { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -2327,8 +2513,7 @@ class ElementsAreArrayMatcher { template <typename Container> operator Matcher<Container>() const { - typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) - RawContainer; + typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef typename internal::StlContainerView<RawContainer>::type::value_type Element; @@ -2539,7 +2724,7 @@ inline PolymorphicMatcher< return MakePolymorphicMatcher( internal::PropertyMatcher<Class, PropertyType>( property, - MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher))); + 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) @@ -2823,15 +3008,32 @@ Truly(Predicate pred) { // values and order differences are not explained.) template <typename Container> inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT - GMOCK_REMOVE_CONST_(Container)> > + 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 GMOCK_REMOVE_CONST_(Container) RawContainer; + typedef GTEST_REMOVE_CONST_(Container) RawContainer; return MakePolymorphicMatcher( internal::ContainerEqMatcher<RawContainer>(rhs)); } +// 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. + typedef GTEST_REMOVE_CONST_(Container) RawContainer; + return internal::PointwiseMatcher<TupleMatcher, RawContainer>( + tuple_matcher, rhs); +} + // Matches an STL-style container or a native array that contains at // least one element matching the given value or matcher. // @@ -2855,6 +3057,38 @@ 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. diff --git a/testing/gmock/include/gmock/gmock-more-actions.h b/testing/gmock/include/gmock/gmock-more-actions.h index 6226392..6d686cd 100644 --- a/testing/gmock/include/gmock/gmock-more-actions.h +++ b/testing/gmock/include/gmock/gmock-more-actions.h @@ -162,7 +162,7 @@ ACTION_TEMPLATE(SetArgReferee, // Ensures that argument #k is a reference. If you get a compiler // error on the next line, you are using SetArgReferee<k>(value) in // a mock function whose k-th (0-based) argument is not a reference. - GMOCK_COMPILE_ASSERT_(internal::is_reference<argk_type>::value, + GTEST_COMPILE_ASSERT_(internal::is_reference<argk_type>::value, SetArgReferee_must_be_used_with_a_reference_argument); ::std::tr1::get<k>(args) = value; } @@ -198,7 +198,17 @@ ACTION_TEMPLATE(DeleteArg, // Action Throw(exception) can be used in a mock function of any type // to throw the given exception. Any copyable value can be thrown. #if GTEST_HAS_EXCEPTIONS + +// Suppresses the 'unreachable code' warning that VC generates in opt modes. +#ifdef _MSC_VER +#pragma warning(push) // Saves the current warning state. +#pragma warning(disable:4702) // Temporarily disables warning 4702. +#endif ACTION_P(Throw, exception) { throw exception; } +#ifdef _MSC_VER +#pragma warning(pop) // Restores the warning state. +#endif + #endif // GTEST_HAS_EXCEPTIONS #ifdef _MSC_VER diff --git a/testing/gmock/include/gmock/gmock-printers.h b/testing/gmock/include/gmock/gmock-printers.h deleted file mode 100644 index d1cd03c..0000000 --- a/testing/gmock/include/gmock/gmock-printers.h +++ /dev/null @@ -1,725 +0,0 @@ -// 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 a universal value printer that can print a -// value of any type T: -// -// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr); -// -// A user can teach this function how to print a class type T by -// defining either operator<<() or PrintTo() in the namespace that -// defines T. More specifically, the FIRST defined function in the -// following list will be used (assuming T is defined in namespace -// foo): -// -// 1. foo::PrintTo(const T&, ostream*) -// 2. operator<<(ostream&, const T&) defined in either foo or the -// global namespace. -// -// If none of the above is defined, it will print the debug string of -// the value if it is a protocol buffer, or print the raw bytes in the -// value otherwise. -// -// To aid debugging: when T is a reference type, the address of the -// value is also printed; when T is a (const) char pointer, both the -// pointer value and the NUL-terminated string it points to are -// printed. -// -// We also provide some convenient wrappers: -// -// // Prints a value to a string. For a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// std::string ::testing::PrintToString(const T& value); -// -// // Prints a value tersely: for a reference type, the referenced -// // value (but not the address) is printed; for a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// void ::testing::internal::UniversalTersePrint(const T& value, ostream*); -// -// // Prints value using the type inferred by the compiler. The difference -// // from UniversalTersePrint() is that this function prints both the -// // pointer and the NUL-terminated string for a (const or not) char pointer. -// void ::testing::internal::UniversalPrint(const T& value, ostream*); -// -// // Prints the fields of a tuple tersely to a string vector, one -// // element for each field. -// std::vector<string> UniversalTersePrintTupleFieldsToStrings( -// const Tuple& value); -// -// Known limitation: -// -// The print primitives print the elements of an STL-style container -// using the compiler-inferred type of *iter where iter is a -// const_iterator of the container. When const_iterator is an input -// iterator but not a forward iterator, this inferred type may not -// match value_type, and the print output may be incorrect. In -// practice, this is rarely a problem as for most containers -// const_iterator is a forward iterator. We'll fix this if there's an -// actual need for it. Note that this fix cannot rely on value_type -// being defined as many user-defined container types don't have -// value_type. - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_PRINTERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_PRINTERS_H_ - -#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> - -namespace testing { - -// Definitions in the 'internal' and 'internal2' name spaces are -// subject to change without notice. DO NOT USE THEM IN USER CODE! -namespace internal2 { - -// Prints the given number of bytes in the given object to the given -// ostream. -void PrintBytesInObjectTo(const unsigned char* obj_bytes, - size_t count, - ::std::ostream* os); - -// TypeWithoutFormatter<T, kIsProto>::PrintValue(value, os) is called -// by the universal printer to print a value of type T when neither -// operator<< nor PrintTo() is defined for type T. When T is -// ProtocolMessage, proto2::Message, or a subclass of those, kIsProto -// will be true and the short debug string of the protocol message -// value will be printed; otherwise kIsProto will be false and the -// bytes in the value will be printed. -template <typename T, bool kIsProto> -class TypeWithoutFormatter { - public: - static void PrintValue(const T& value, ::std::ostream* os) { - PrintBytesInObjectTo(reinterpret_cast<const unsigned char*>(&value), - sizeof(value), os); - } -}; - -// We print a protobuf using its ShortDebugString() when the string -// doesn't exceed this many characters; otherwise we print it using -// DebugString() for better readability. -const size_t kProtobufOneLinerMaxLength = 50; - -template <typename T> -class TypeWithoutFormatter<T, true> { - public: - static void PrintValue(const T& value, ::std::ostream* os) { - const ::testing::internal::string short_str = value.ShortDebugString(); - const ::testing::internal::string pretty_str = - short_str.length() <= kProtobufOneLinerMaxLength ? - short_str : ("\n" + value.DebugString()); - ::std::operator<<(*os, "<" + pretty_str + ">"); - } -}; - -// Prints the given value to the given ostream. If the value is a -// protocol message, its short debug string is printed; otherwise the -// bytes in the value are printed. This is what -// UniversalPrinter<T>::Print() does when it knows nothing about type -// T and T has no << operator. -// -// A user can override this behavior for a class type Foo by defining -// a << operator in the namespace where Foo is defined. -// -// We put this operator in namespace 'internal2' instead of 'internal' -// to simplify the implementation, as much code in 'internal' needs to -// use << in STL, which would conflict with our own << were it defined -// in 'internal'. -// -// Note that this operator<< takes a generic std::basic_ostream<Char, -// CharTraits> type instead of the more restricted std::ostream. If -// we define it to take an std::ostream instead, we'll get an -// "ambiguous overloads" compiler error when trying to print a type -// Foo that supports streaming to std::basic_ostream<Char, -// CharTraits>, as the compiler cannot tell whether -// operator<<(std::ostream&, const T&) or -// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more -// specific. -template <typename Char, typename CharTraits, typename T> -::std::basic_ostream<Char, CharTraits>& operator<<( - ::std::basic_ostream<Char, CharTraits>& os, const T& x) { - TypeWithoutFormatter<T, ::testing::internal::IsAProtocolMessage<T>::value>:: - PrintValue(x, &os); - return os; -} - -} // namespace internal2 -} // namespace testing - -// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up -// magic needed for implementing UniversalPrinter won't work. -namespace testing_internal { - -// Used to print a value that is not an STL-style container when the -// user doesn't define PrintTo() for it. -template <typename T> -void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { - // With the following statement, during unqualified name lookup, - // testing::internal2::operator<< appears as if it was declared in - // the nearest enclosing namespace that contains both - // ::testing_internal and ::testing::internal2, i.e. the global - // namespace. For more details, refer to the C++ Standard section - // 7.3.4-1 [namespace.udir]. This allows us to fall back onto - // testing::internal2::operator<< in case T doesn't come with a << - // operator. - // - // We cannot write 'using ::testing::internal2::operator<<;', which - // gcc 3.3 fails to compile due to a compiler bug. - using namespace ::testing::internal2; // NOLINT - - // Assuming T is defined in namespace foo, in the next statement, - // the compiler will consider all of: - // - // 1. foo::operator<< (thanks to Koenig look-up), - // 2. ::operator<< (as the current namespace is enclosed in ::), - // 3. testing::internal2::operator<< (thanks to the using statement above). - // - // The operator<< whose type matches T best will be picked. - // - // We deliberately allow #2 to be a candidate, as sometimes it's - // impossible to define #1 (e.g. when foo is ::std, defining - // anything in it is undefined behavior unless you are a compiler - // vendor.). - *os << value; -} - -} // namespace testing_internal - -namespace testing { -namespace internal { - -// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given -// value to the given ostream. The caller must ensure that -// 'ostream_ptr' is not NULL, or the behavior is undefined. -// -// We define UniversalPrinter as a class template (as opposed to a -// function template), as we need to partially specialize it for -// reference types, which cannot be done with function templates. -template <typename T> -class UniversalPrinter; - -template <typename T> -void UniversalPrint(const T& value, ::std::ostream* os); - -// Used to print an STL-style container when the user doesn't define -// a PrintTo() for it. -template <typename C> -void DefaultPrintTo(IsContainer /* dummy */, - false_type /* is not a pointer */, - const C& container, ::std::ostream* os) { - const size_t kMaxCount = 32; // The maximum number of elements to print. - *os << '{'; - size_t count = 0; - for (typename C::const_iterator it = container.begin(); - it != container.end(); ++it, ++count) { - if (count > 0) { - *os << ','; - if (count == kMaxCount) { // Enough has been printed. - *os << " ..."; - break; - } - } - *os << ' '; - // We cannot call PrintTo(*it, os) here as PrintTo() doesn't - // handle *it being a native array. - internal::UniversalPrint(*it, os); - } - - if (count > 0) { - *os << ' '; - } - *os << '}'; -} - -// Used to print a pointer that is neither a char pointer nor a member -// pointer, when the user doesn't define PrintTo() for it. (A member -// variable pointer or member function pointer doesn't really point to -// a location in the address space. Their representation is -// implementation-defined. Therefore they will be printed as raw -// bytes.) -template <typename T> -void DefaultPrintTo(IsNotContainer /* dummy */, - true_type /* is a pointer */, - T* p, ::std::ostream* os) { - if (p == NULL) { - *os << "NULL"; - } else { - // We want to print p as a const void*. However, we cannot cast - // it to const void* directly, even using reinterpret_cast, as - // earlier versions of gcc (e.g. 3.4.5) cannot compile the cast - // when p is a function pointer. Casting to UInt64 first solves - // the problem. - *os << reinterpret_cast<const void*>(reinterpret_cast<internal::UInt64>(p)); - } -} - -// Used to print a non-container, non-pointer value when the user -// doesn't define PrintTo() for it. -template <typename T> -void DefaultPrintTo(IsNotContainer /* dummy */, - false_type /* is not a pointer */, - const T& value, ::std::ostream* os) { - ::testing_internal::DefaultPrintNonContainerTo(value, os); -} - -// Prints the given value using the << operator if it has one; -// otherwise prints the bytes in it. This is what -// UniversalPrinter<T>::Print() does when PrintTo() is not specialized -// or overloaded for type T. -// -// A user can override this behavior for a class type Foo by defining -// an overload of PrintTo() in the namespace where Foo is defined. We -// give the user this option as sometimes defining a << operator for -// Foo is not desirable (e.g. the coding style may prevent doing it, -// or there is already a << operator but it doesn't do what the user -// wants). -template <typename T> -void PrintTo(const T& value, ::std::ostream* os) { - // DefaultPrintTo() is overloaded. The type of its first two - // arguments determine which version will be picked. If T is an - // STL-style container, the version for container will be called; if - // T is a pointer, the pointer version will be called; otherwise the - // generic version will be called. - // - // Note that we check for container types here, prior to we check - // for protocol message types in our operator<<. The rationale is: - // - // For protocol messages, we want to give people a chance to - // override Google Mock's format by defining a PrintTo() or - // operator<<. For STL containers, other formats can be - // incompatible with Google Mock's format for the container - // elements; therefore we check for container types here to ensure - // that our format is used. - // - // The second argument of DefaultPrintTo() is needed to bypass a bug - // in Symbian's C++ compiler that prevents it from picking the right - // overload between: - // - // PrintTo(const T& x, ...); - // PrintTo(T* x, ...); - DefaultPrintTo(IsContainerTest<T>(0), is_pointer<T>(), value, os); -} - -// The following list of PrintTo() overloads tells -// UniversalPrinter<T>::Print() how to print standard types (built-in -// types, strings, plain arrays, and pointers). - -// Overloads for various char types. -void PrintCharTo(char c, int char_code, ::std::ostream* os); -inline void PrintTo(unsigned char c, ::std::ostream* os) { - PrintCharTo(c, c, os); -} -inline void PrintTo(signed char c, ::std::ostream* os) { - PrintCharTo(c, c, os); -} -inline void PrintTo(char c, ::std::ostream* os) { - // When printing a plain char, we always treat it as unsigned. This - // way, the output won't be affected by whether the compiler thinks - // char is signed or not. - PrintTo(static_cast<unsigned char>(c), os); -} - -// Overloads for other simple built-in types. -inline void PrintTo(bool x, ::std::ostream* os) { - *os << (x ? "true" : "false"); -} - -// Overload for wchar_t type. -// Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its decimal code (except for L'\0'). -// The L'\0' char is printed as "L'\\0'". The decimal code is printed -// as signed integer when wchar_t is implemented by the compiler -// as a signed type and is printed as an unsigned integer when wchar_t -// is implemented as an unsigned type. -void PrintTo(wchar_t wc, ::std::ostream* os); - -// Overloads for C strings. -void PrintTo(const char* s, ::std::ostream* os); -inline void PrintTo(char* s, ::std::ostream* os) { - PrintTo(implicit_cast<const char*>(s), os); -} - -// MSVC can be configured to define wchar_t as a typedef of unsigned -// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native -// type. When wchar_t is a typedef, defining an overload for const -// wchar_t* would cause unsigned short* be printed as a wide string, -// possibly causing invalid memory accesses. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) -// Overloads for wide C strings -void PrintTo(const wchar_t* s, ::std::ostream* os); -inline void PrintTo(wchar_t* s, ::std::ostream* os) { - PrintTo(implicit_cast<const wchar_t*>(s), os); -} -#endif - -// Overload for C arrays. Multi-dimensional arrays are printed -// properly. - -// Prints the given number of elements in an array, without printing -// the curly braces. -template <typename T> -void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { - UniversalPrinter<T>::Print(a[0], os); - for (size_t i = 1; i != count; i++) { - *os << ", "; - UniversalPrinter<T>::Print(a[i], os); - } -} - -// Overloads for ::string and ::std::string. -#if GTEST_HAS_GLOBAL_STRING -void PrintStringTo(const ::string&s, ::std::ostream* os); -inline void PrintTo(const ::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} -#endif // GTEST_HAS_GLOBAL_STRING - -void PrintStringTo(const ::std::string&s, ::std::ostream* os); -inline void PrintTo(const ::std::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} - -// Overloads for ::wstring and ::std::wstring. -#if GTEST_HAS_GLOBAL_WSTRING -void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} -#endif // GTEST_HAS_STD_WSTRING - -// Overload for ::std::tr1::tuple. Needed for printing function -// arguments, which are packed as tuples. - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template <typename T> -void PrintTupleTo(const T& t, ::std::ostream* os); - -// Overloaded PrintTo() for tuples of various arities. We support -// tuples of up-to 10 fields. The following implementation works -// regardless of whether tr1::tuple is implemented using the -// non-standard variadic template feature or not. - -inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1> -void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2> -void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3> -void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3, typename T4> -void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5> -void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6> -void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7> -void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8> -void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8, typename T9> -void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -template <typename T1, typename T2, typename T3, typename T4, typename T5, - typename T6, typename T7, typename T8, typename T9, typename T10> -void PrintTo( - const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t, - ::std::ostream* os) { - PrintTupleTo(t, os); -} - -// Overload for std::pair. -template <typename T1, typename T2> -void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) { - *os << '('; - UniversalPrinter<T1>::Print(value.first, os); - *os << ", "; - UniversalPrinter<T2>::Print(value.second, os); - *os << ')'; -} - -// Implements printing a non-reference type T by letting the compiler -// pick the right overload of PrintTo() for T. -template <typename T> -class UniversalPrinter { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. -#ifdef _MSC_VER -#pragma warning(push) // Saves the current warning state. -#pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER - - // Note: we deliberately don't call this PrintTo(), as that name - // conflicts with ::testing::internal::PrintTo in the body of the - // function. - static void Print(const T& value, ::std::ostream* os) { - // By default, ::testing::internal::PrintTo() is used for printing - // the value. - // - // Thanks to Koenig look-up, if T is a class and has its own - // PrintTo() function defined in its namespace, that function will - // be visible here. Since it is more specific than the generic ones - // in ::testing::internal, it will be picked by the compiler in the - // following statement - exactly what we want. - PrintTo(value, os); - } - -#ifdef _MSC_VER -#pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER -}; - -// UniversalPrintArray(begin, len, os) prints an array of 'len' -// elements, starting at address 'begin'. -template <typename T> -void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { - if (len == 0) { - *os << "{}"; - } else { - *os << "{ "; - const size_t kThreshold = 18; - const size_t kChunkSize = 8; - // If the array has more than kThreshold elements, we'll have to - // omit some details by printing only the first and the last - // kChunkSize elements. - // TODO(wan@google.com): let the user control the threshold using a flag. - if (len <= kThreshold) { - PrintRawArrayTo(begin, len, os); - } else { - PrintRawArrayTo(begin, kChunkSize, os); - *os << ", ..., "; - PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); - } - *os << " }"; - } -} -// This overload prints a (const) char array compactly. -void UniversalPrintArray(const char* begin, size_t len, ::std::ostream* os); - -// Implements printing an array type T[N]. -template <typename T, size_t N> -class UniversalPrinter<T[N]> { - public: - // Prints the given array, omitting some elements when there are too - // many. - static void Print(const T (&a)[N], ::std::ostream* os) { - UniversalPrintArray(a, N, os); - } -}; - -// Implements printing a reference type T&. -template <typename T> -class UniversalPrinter<T&> { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. -#ifdef _MSC_VER -#pragma warning(push) // Saves the current warning state. -#pragma warning(disable:4180) // Temporarily disables warning 4180. -#endif // _MSC_VER - - static void Print(const T& value, ::std::ostream* os) { - // Prints the address of the value. We use reinterpret_cast here - // as static_cast doesn't compile when T is a function type. - *os << "@" << reinterpret_cast<const void*>(&value) << " "; - - // Then prints the value itself. - UniversalPrinter<T>::Print(value, os); - } - -#ifdef _MSC_VER -#pragma warning(pop) // Restores the warning state. -#endif // _MSC_VER -}; - -// Prints a value tersely: for a reference type, the referenced value -// (but not the address) is printed; for a (const) char pointer, the -// NUL-terminated string (but not the pointer) is printed. -template <typename T> -void UniversalTersePrint(const T& value, ::std::ostream* os) { - UniversalPrinter<T>::Print(value, os); -} -inline void UniversalTersePrint(const char* str, ::std::ostream* os) { - if (str == NULL) { - *os << "NULL"; - } else { - UniversalPrinter<string>::Print(string(str), os); - } -} -inline void UniversalTersePrint(char* str, ::std::ostream* os) { - UniversalTersePrint(static_cast<const char*>(str), os); -} - -// Prints a value using the type inferred by the compiler. The -// difference between this and UniversalTersePrint() is that for a -// (const) char pointer, this prints both the pointer and the -// NUL-terminated string. -template <typename T> -void UniversalPrint(const T& value, ::std::ostream* os) { - UniversalPrinter<T>::Print(value, os); -} - -typedef ::std::vector<string> Strings; - -// This helper template allows PrintTo() for tuples and -// UniversalTersePrintTupleFieldsToStrings() to be defined by -// induction on the number of tuple fields. The idea is that -// TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N -// fields in tuple t, and can be defined in terms of -// TuplePrefixPrinter<N - 1>. - -// The inductive case. -template <size_t N> -struct TuplePrefixPrinter { - // Prints the first N fields of a tuple. - template <typename Tuple> - static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { - TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os); - *os << ", "; - UniversalPrinter<typename ::std::tr1::tuple_element<N - 1, Tuple>::type> - ::Print(::std::tr1::get<N - 1>(t), os); - } - - // Tersely prints the first N fields of a tuple to a string vector, - // one element for each field. - template <typename Tuple> - static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { - TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings); - ::std::stringstream ss; - UniversalTersePrint(::std::tr1::get<N - 1>(t), &ss); - strings->push_back(ss.str()); - } -}; - -// Base cases. -template <> -struct TuplePrefixPrinter<0> { - template <typename Tuple> - static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} - - template <typename Tuple> - static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} -}; -template <> -template <typename Tuple> -void TuplePrefixPrinter<1>::PrintPrefixTo(const Tuple& t, ::std::ostream* os) { - UniversalPrinter<typename ::std::tr1::tuple_element<0, Tuple>::type>:: - Print(::std::tr1::get<0>(t), os); -} - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template <typename T> -void PrintTupleTo(const T& t, ::std::ostream* os) { - *os << "("; - TuplePrefixPrinter< ::std::tr1::tuple_size<T>::value>:: - PrintPrefixTo(t, os); - *os << ")"; -} - -// Prints the fields of a tuple tersely to a string vector, one -// element for each field. See the comment before -// UniversalTersePrint() for how we define "tersely". -template <typename Tuple> -Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { - Strings result; - TuplePrefixPrinter< ::std::tr1::tuple_size<Tuple>::value>:: - TersePrintPrefixToStrings(value, &result); - return result; -} - -} // namespace internal - -template <typename T> -::std::string PrintToString(const T& value) { - ::std::stringstream ss; - internal::UniversalTersePrint(value, &ss); - return ss.str(); -} - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_PRINTERS_H_ diff --git a/testing/gmock/include/gmock/gmock-spec-builders.h b/testing/gmock/include/gmock/gmock-spec-builders.h index 74a095d..7038c2e 100644 --- a/testing/gmock/include/gmock/gmock-spec-builders.h +++ b/testing/gmock/include/gmock/gmock-spec-builders.h @@ -69,7 +69,6 @@ #include <gmock/gmock-actions.h> #include <gmock/gmock-cardinalities.h> #include <gmock/gmock-matchers.h> -#include <gmock/gmock-printers.h> #include <gmock/internal/gmock-internal-utils.h> #include <gmock/internal/gmock-port.h> #include <gtest/gtest.h> @@ -1269,6 +1268,7 @@ class ActionResultHolder { // Prints the held value as an action's result to os. void PrintAsActionResult(::std::ostream* os) const { *os << "\n Returns: "; + // T may be a reference type, so we don't use UniversalPrint(). UniversalPrinter<T>::Print(value_, os); } @@ -1540,7 +1540,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { *os << "Uninteresting mock function call - "; DescribeDefaultActionTo(args, os); *os << " Function call: " << Name(); - UniversalPrinter<ArgumentTuple>::Print(args, os); + UniversalPrint(args, os); } // Critical section: We must find the matching expectation and the @@ -1776,7 +1776,7 @@ typename Function<F>::Result FunctionMockerBase<F>::InvokeWith( } ss << " Function call: " << Name(); - UniversalPrinter<ArgumentTuple>::Print(args, &ss); + UniversalPrint(args, &ss); // In case the action deletes a piece of the expectation, we // generate the message beforehand. diff --git a/testing/gmock/include/gmock/gmock.h b/testing/gmock/include/gmock/gmock.h index daf5288..e3d5fd8 100644 --- a/testing/gmock/include/gmock/gmock.h +++ b/testing/gmock/include/gmock/gmock.h @@ -63,7 +63,6 @@ #include <gmock/gmock-more-actions.h> #include <gmock/gmock-generated-nice-strict.h> #include <gmock/gmock-matchers.h> -#include <gmock/gmock-printers.h> #include <gmock/internal/gmock-internal-utils.h> namespace testing { diff --git a/testing/gmock/include/gmock/internal/gmock-internal-utils.h b/testing/gmock/include/gmock/internal/gmock-internal-utils.h index 0c33fdd..69a2338 100644 --- a/testing/gmock/include/gmock/internal/gmock-internal-utils.h +++ b/testing/gmock/include/gmock/internal/gmock-internal-utils.h @@ -57,9 +57,6 @@ #define GMOCK_ATTRIBUTE_UNUSED_ #endif // __GNUC__ -class ProtocolMessage; -namespace proto2 { class Message; } - namespace testing { namespace internal { @@ -69,77 +66,6 @@ namespace internal { // "foo_bar_123" are converted to "foo bar 123". string ConvertIdentifierNameToWords(const char* id_name); -// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a -// compiler error iff T1 and T2 are different types. -template <typename T1, typename T2> -struct CompileAssertTypesEqual; - -template <typename T> -struct CompileAssertTypesEqual<T, T> { -}; - -// Removes the reference from a type if it is a reference type, -// otherwise leaves it unchanged. This is the same as -// tr1::remove_reference, which is not widely available yet. -template <typename T> -struct RemoveReference { typedef T type; }; // NOLINT -template <typename T> -struct RemoveReference<T&> { typedef T type; }; // NOLINT - -// A handy wrapper around RemoveReference that works when the argument -// T depends on template parameters. -#define GMOCK_REMOVE_REFERENCE_(T) \ - typename ::testing::internal::RemoveReference<T>::type - -// Removes const from a type if it is a const type, otherwise leaves -// it unchanged. This is the same as tr1::remove_const, which is not -// widely available yet. -template <typename T> -struct RemoveConst { typedef T type; }; // NOLINT -template <typename T> -struct RemoveConst<const T> { typedef T type; }; // NOLINT - -// MSVC 8.0 has a bug which causes the above definition to fail to -// remove the const in 'const int[3]'. The following specialization -// works around the bug. However, it causes trouble with gcc and thus -// needs to be conditionally compiled. -#ifdef _MSC_VER -template <typename T, size_t N> -struct RemoveConst<T[N]> { - typedef typename RemoveConst<T>::type type[N]; -}; -#endif // _MSC_VER - -// A handy wrapper around RemoveConst that works when the argument -// T depends on template parameters. -#define GMOCK_REMOVE_CONST_(T) \ - typename ::testing::internal::RemoveConst<T>::type - -// Adds reference to a type if it is not a reference type, -// otherwise leaves it unchanged. This is the same as -// tr1::add_reference, which is not widely available yet. -template <typename T> -struct AddReference { typedef T& type; }; // NOLINT -template <typename T> -struct AddReference<T&> { typedef T& type; }; // NOLINT - -// A handy wrapper around AddReference that works when the argument T -// depends on template parameters. -#define GMOCK_ADD_REFERENCE_(T) \ - typename ::testing::internal::AddReference<T>::type - -// Adds a reference to const on top of T as necessary. For example, -// it transforms -// -// char ==> const char& -// const char ==> const char& -// char& ==> const char& -// const char& ==> const char& -// -// The argument T must depend on some template parameters. -#define GMOCK_REFERENCE_TO_CONST_(T) \ - GMOCK_ADD_REFERENCE_(const GMOCK_REMOVE_REFERENCE_(T)) - // PointeeOf<Pointer>::type is the type of a value pointed to by a // Pointer, which can be either a smart pointer or a raw pointer. The // following default implementation is for the case where Pointer is a @@ -174,53 +100,6 @@ struct LinkedPtrLessThan { } }; -// ImplicitlyConvertible<From, To>::value is a compile-time bool -// constant that's true iff type From can be implicitly converted to -// type To. -template <typename From, typename To> -class ImplicitlyConvertible { - private: - // We need the following helper functions only for their types. - // They have no implementations. - - // MakeFrom() is an expression whose type is From. We cannot simply - // use From(), as the type From may not have a public default - // constructor. - static From MakeFrom(); - - // These two functions are overloaded. Given an expression - // Helper(x), the compiler will pick the first version if x can be - // implicitly converted to type To; otherwise it will pick the - // second version. - // - // The first version returns a value of size 1, and the second - // version returns a value of size 2. Therefore, by checking the - // size of Helper(x), which can be done at compile time, we can tell - // which version of Helper() is used, and hence whether x can be - // implicitly converted to type To. - static char Helper(To); - static char (&Helper(...))[2]; // NOLINT - - // We have to put the 'public' section after the 'private' section, - // or MSVC refuses to compile the code. - public: - // MSVC warns about implicitly converting from double to int for - // possible loss of data, so we need to temporarily disable the - // warning. -#ifdef _MSC_VER -#pragma warning(push) // Saves the current warning state. -#pragma warning(disable:4244) // Temporarily disables warning 4244. - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -#pragma warning(pop) // Restores the warning state. -#else - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; -#endif // _MSV_VER -}; -template <typename From, typename To> -const bool ImplicitlyConvertible<From, To>::value; - // Symbian compilation can be done with wchar_t being either a native // type or a typedef. Using Google Mock with OpenC without wchar_t // should require the definition of _STLP_NO_WCHAR_T. @@ -385,32 +264,6 @@ struct LosslessArithmeticConvertible : public LosslessArithmeticConvertibleImpl< GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT -// IsAProtocolMessage<T>::value is a compile-time bool constant that's -// true iff T is type ProtocolMessage, proto2::Message, or a subclass -// of those. -template <typename T> -struct IsAProtocolMessage - : public bool_constant< - ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value || - ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> { -}; - -// When the compiler sees expression IsContainerTest<C>(0), the first -// overload of IsContainerTest will be picked if C is an STL-style -// container class (since C::const_iterator* is a valid type and 0 can -// be converted to it), while the second overload will be picked -// otherwise (since C::const_iterator will be an invalid type in this -// case). Therefore, we can determine whether C is a container class -// by checking the type of IsContainerTest<C>(0). The value of the -// expression is insignificant. -typedef int IsContainer; -template <class C> -IsContainer IsContainerTest(typename C::const_iterator*) { return 0; } - -typedef char IsNotContainer; -template <class C> -IsNotContainer IsContainerTest(...) { return '\0'; } - // This interface knows how to report a Google Mock failure (either // non-fatal or fatal). class FailureReporterInterface { @@ -514,149 +367,6 @@ inline T Invalid() { template <> inline void Invalid<void>() {} -// Utilities for native arrays. - -// ArrayEq() compares two k-dimensional native arrays using the -// elements' operator==, where k can be any integer >= 0. When k is -// 0, ArrayEq() degenerates into comparing a single pair of values. - -template <typename T, typename U> -bool ArrayEq(const T* lhs, size_t size, const U* rhs); - -// This generic version is used when k is 0. -template <typename T, typename U> -inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } - -// This overload is used when k >= 1. -template <typename T, typename U, size_t N> -inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { - return internal::ArrayEq(lhs, N, rhs); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous ArrayEq() function, arrays with different sizes would -// lead to different copies of the template code. -template <typename T, typename U> -bool ArrayEq(const T* lhs, size_t size, const U* rhs) { - for (size_t i = 0; i != size; i++) { - if (!internal::ArrayEq(lhs[i], rhs[i])) - return false; - } - return true; -} - -// Finds the first element in the iterator range [begin, end) that -// equals elem. Element may be a native array type itself. -template <typename Iter, typename Element> -Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { - for (Iter it = begin; it != end; ++it) { - if (internal::ArrayEq(*it, elem)) - return it; - } - return end; -} - -// CopyArray() copies a k-dimensional native array using the elements' -// operator=, where k can be any integer >= 0. When k is 0, -// CopyArray() degenerates into copying a single value. - -template <typename T, typename U> -void CopyArray(const T* from, size_t size, U* to); - -// This generic version is used when k is 0. -template <typename T, typename U> -inline void CopyArray(const T& from, U* to) { *to = from; } - -// This overload is used when k >= 1. -template <typename T, typename U, size_t N> -inline void CopyArray(const T(&from)[N], U(*to)[N]) { - internal::CopyArray(from, N, *to); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous CopyArray() function, arrays with different sizes -// would lead to different copies of the template code. -template <typename T, typename U> -void CopyArray(const T* from, size_t size, U* to) { - for (size_t i = 0; i != size; i++) { - internal::CopyArray(from[i], to + i); - } -} - -// The relation between an NativeArray object (see below) and the -// native array it represents. -enum RelationToSource { - kReference, // The NativeArray references the native array. - kCopy // The NativeArray makes a copy of the native array and - // owns the copy. -}; - -// Adapts a native array to a read-only STL-style container. Instead -// of the complete STL container concept, this adaptor only implements -// members useful for Google Mock's container matchers. New members -// should be added as needed. To simplify the implementation, we only -// support Element being a raw type (i.e. having no top-level const or -// reference modifier). It's the client's responsibility to satisfy -// this requirement. Element can be an array type itself (hence -// multi-dimensional arrays are supported). -template <typename Element> -class NativeArray { - public: - // STL-style container typedefs. - typedef Element value_type; - typedef const Element* const_iterator; - - // Constructs from a native array. - NativeArray(const Element* array, size_t count, RelationToSource relation) { - Init(array, count, relation); - } - - // Copy constructor. - NativeArray(const NativeArray& rhs) { - Init(rhs.array_, rhs.size_, rhs.relation_to_source_); - } - - ~NativeArray() { - // Ensures that the user doesn't instantiate NativeArray with a - // const or reference type. - testing::StaticAssertTypeEq<Element, - GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Element))>(); - if (relation_to_source_ == kCopy) - delete[] array_; - } - - // STL-style container methods. - size_t size() const { return size_; } - const_iterator begin() const { return array_; } - const_iterator end() const { return array_ + size_; } - bool operator==(const NativeArray& rhs) const { - return size() == rhs.size() && - ArrayEq(begin(), size(), rhs.begin()); - } - - private: - // Not implemented as we don't want to support assignment. - void operator=(const NativeArray& rhs); - - // Initializes this object; makes a copy of the input array if - // 'relation' is kCopy. - void Init(const Element* array, size_t a_size, RelationToSource relation) { - if (relation == kReference) { - array_ = array; - } else { - Element* const copy = new Element[a_size]; - CopyArray(array, a_size, copy); - array_ = copy; - } - size_ = a_size; - relation_to_source_ = relation; - } - - const Element* array_; - size_t size_; - RelationToSource relation_to_source_; -}; - // Given a raw type (i.e. having no top-level reference or const // modifier) RawContainer that's either an STL-style container or a // native array, class StlContainerView<RawContainer> has the @@ -682,7 +392,7 @@ class StlContainerView { static const_reference ConstReference(const RawContainer& container) { // Ensures that RawContainer is not a const type. testing::StaticAssertTypeEq<RawContainer, - GMOCK_REMOVE_CONST_(RawContainer)>(); + GTEST_REMOVE_CONST_(RawContainer)>(); return container; } static type Copy(const RawContainer& container) { return container; } @@ -692,7 +402,7 @@ class StlContainerView { template <typename Element, size_t N> class StlContainerView<Element[N]> { public: - typedef GMOCK_REMOVE_CONST_(Element) RawElement; + typedef GTEST_REMOVE_CONST_(Element) RawElement; typedef internal::NativeArray<RawElement> type; // NativeArray<T> can represent a native array either by value or by // reference (selected by a constructor argument), so 'const type' @@ -737,7 +447,7 @@ class StlContainerView<Element[N]> { template <typename ElementPointer, typename Size> class StlContainerView< ::std::tr1::tuple<ElementPointer, Size> > { public: - typedef GMOCK_REMOVE_CONST_( + typedef GTEST_REMOVE_CONST_( typename internal::PointeeOf<ElementPointer>::type) RawElement; typedef internal::NativeArray<RawElement> type; typedef const type const_reference; diff --git a/testing/gmock/include/gmock/internal/gmock-port.h b/testing/gmock/include/gmock/internal/gmock-port.h index 30115f2..b644eb4 100644 --- a/testing/gmock/include/gmock/internal/gmock-port.h +++ b/testing/gmock/include/gmock/internal/gmock-port.h @@ -50,149 +50,12 @@ // tr1/tuple. gmock-port.h does this via gtest-port.h, which is // guaranteed to pull in the tuple header. -#if GTEST_OS_LINUX - -#endif // GTEST_OS_LINUX - -namespace testing { -namespace internal { - // For MS Visual C++, check the compiler version. At least VS 2003 is // required to compile Google Mock. #if defined(_MSC_VER) && _MSC_VER < 1310 #error "At least Visual C++ 2003 (7.1) is required to compile Google Mock." #endif -// Use implicit_cast 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 implicit_cast, the compiler checks that -// the cast is safe. Such explicit implicit_casts 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 implicit_cast is the same as for static_cast: -// -// implicit_cast<ToType>(expr) -// -// implicit_cast 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. -template<typename To> -inline To implicit_cast(To x) { return x; } - -// When you upcast (that is, cast a pointer from type Foo to type -// SuperclassOfFoo), it's fine to use implicit_cast<>, 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. -template<typename To, typename From> // use like this: down_cast<T*>(foo); -inline To down_cast(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. - if (false) { - const To to = NULL; - ::testing::internal::implicit_cast<From*>(to); - } - -#if GTEST_HAS_RTTI - assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only! -#endif - return static_cast<To>(f); -} - -// The GMOCK_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: -// -// GMOCK_COMPILE_ASSERT_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, -// content_type_names_incorrect_size); -// -// or to make sure a struct is smaller than a certain size: -// -// GMOCK_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. - -template <bool> -struct CompileAssert { -}; - -#define GMOCK_COMPILE_ASSERT_(expr, msg) \ - typedef ::testing::internal::CompileAssert<(bool(expr))> \ - msg[bool(expr) ? 1 : -1] - -// Implementation details of GMOCK_COMPILE_ASSERT_: -// -// - GMOCK_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 GMOCK_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; -// GMOCK_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 -// -// GMOCK_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. - -#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 - -} // namespace internal -} // namespace testing - // Macro for referencing flags. This is public as we want the user to // use this syntax to reference Google Mock flags. #define GMOCK_FLAG(name) FLAGS_gmock_##name diff --git a/testing/gmock/make/Makefile b/testing/gmock/make/Makefile index ee0527e..6386e5b 100644 --- a/testing/gmock/make/Makefile +++ b/testing/gmock/make/Makefile @@ -27,15 +27,14 @@ GMOCK_DIR = .. USER_DIR = ../test # Flags passed to the preprocessor. -CPPFLAGS += -I$(GMOCK_DIR) -I$(GMOCK_DIR)/include \ - -I$(GTEST_DIR) -I$(GTEST_DIR)/include +CPPFLAGS += -I$(GTEST_DIR)/include -I$(GMOCK_DIR)/include # Flags passed to the C++ compiler. CXXFLAGS += -g -Wall -Wextra # All tests produced by this Makefile. Remember to add new tests you # created to the list. -TESTS = gmock_link_test gmock_test +TESTS = gmock_test # All Google Test headers. Usually you shouldn't change this # definition. @@ -73,13 +72,16 @@ GMOCK_SRCS_ = $(GMOCK_DIR)/src/*.cc $(GMOCK_HEADERS) # Google Test compile fast and for ordinary users their source rarely # changes. gtest-all.o : $(GTEST_SRCS_) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GTEST_DIR)/src/gtest-all.cc + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \ + -c $(GTEST_DIR)/src/gtest-all.cc gmock-all.o : $(GMOCK_SRCS_) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GMOCK_DIR)/src/gmock-all.cc + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \ + -c $(GMOCK_DIR)/src/gmock-all.cc gmock_main.o : $(GMOCK_SRCS_) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GMOCK_DIR)/src/gmock_main.cc + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) -I$(GMOCK_DIR) $(CXXFLAGS) \ + -c $(GMOCK_DIR)/src/gmock_main.cc gmock.a : gmock-all.o gtest-all.o $(AR) $(ARFLAGS) $@ $^ @@ -89,21 +91,8 @@ gmock_main.a : gmock-all.o gtest-all.o gmock_main.o # Builds a sample test. -gmock_link_test.o : $(USER_DIR)/gmock_link_test.cc \ - $(USER_DIR)/gmock_link_test.h $(GMOCK_HEADERS) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/gmock_link_test.cc - -gmock_link2_test.o : $(USER_DIR)/gmock_link2_test.cc \ - $(USER_DIR)/gmock_link_test.h $(GMOCK_HEADERS) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/gmock_link2_test.cc - -gmock_link_test : gmock_link_test.o gmock_link2_test.o gmock_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ -o $@ - -# Builds another sample test. - gmock_test.o : $(USER_DIR)/gmock_test.cc $(GMOCK_HEADERS) $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/gmock_test.cc gmock_test : gmock_test.o gmock_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ -o $@ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ diff --git a/testing/gmock/run_tests.py b/testing/gmock/run_tests.py index 42dc14b..5e7b308 100755 --- a/testing/gmock/run_tests.py +++ b/testing/gmock/run_tests.py @@ -68,7 +68,6 @@ def _Main(): options, args = run_tests_util.ParseArgs('gtest') test_runner = run_tests_util.TestRunner( script_dir=SCRIPT_DIR, - build_dir_var_name='GMOCK_BUILD_DIR', injected_build_dir_finder=GetGmockBuildDir) tests = test_runner.GetTestsToRun(args, options.configurations, diff --git a/testing/gmock/scripts/gmock_doctor.py b/testing/gmock/scripts/gmock_doctor.py index bc814ad..fad4e34 100755 --- a/testing/gmock/scripts/gmock_doctor.py +++ b/testing/gmock/scripts/gmock_doctor.py @@ -203,7 +203,7 @@ def _IncompleteByReferenceArgumentDiagnoser(msg): """Diagnoses the IBRA disease, given the error messages by gcc.""" regex = (_FILE_LINE_RE + r'instantiated from here\n' - r'.*gmock-printers\.h.*error: invalid application of ' + r'.*gtest-printers\.h.*error: invalid application of ' r'\'sizeof\' to incomplete type \'(?P<type>.*)\'') diagnosis = """ In order to mock this function, Google Mock needs to see the definition diff --git a/testing/gmock/scripts/test/Makefile b/testing/gmock/scripts/test/Makefile deleted file mode 100644 index 8edaea0..0000000 --- a/testing/gmock/scripts/test/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -# A Makefile for fusing Google Mock and building a sample test against it. -# -# SYNOPSIS: -# -# make [all] - makes everything. -# make TARGET - makes the given target. -# make check - makes everything and runs the built sample test. -# make clean - removes all files generated by make. - -# Points to the root of fused Google Mock, relative to where this file is. -FUSED_GMOCK_DIR = output - -# Paths to the fused gmock files. -FUSED_GTEST_H = $(FUSED_GMOCK_DIR)/gtest/gtest.h -FUSED_GMOCK_H = $(FUSED_GMOCK_DIR)/gmock/gmock.h -FUSED_GMOCK_GTEST_ALL_CC = $(FUSED_GMOCK_DIR)/gmock-gtest-all.cc - -# Where to find the gmock_test.cc. -GMOCK_TEST_CC = ../../test/gmock_test.cc - -# Where to find gmock_main.cc. -GMOCK_MAIN_CC = ../../src/gmock_main.cc - -# Flags passed to the preprocessor. -CPPFLAGS += -I$(FUSED_GMOCK_DIR) - -# Flags passed to the C++ compiler. -CXXFLAGS += -g - -all : gmock_test - -check : all - ./gmock_test - -clean : - rm -rf $(FUSED_GMOCK_DIR) gmock_test *.o - -$(FUSED_GTEST_H) : - ../fuse_gmock_files.py $(FUSED_GMOCK_DIR) - -$(FUSED_GMOCK_H) : - ../fuse_gmock_files.py $(FUSED_GMOCK_DIR) - -$(FUSED_GMOCK_GTEST_ALL_CC) : - ../fuse_gmock_files.py $(FUSED_GMOCK_DIR) - -gmock-gtest-all.o : $(FUSED_GTEST_H) $(FUSED_GMOCK_H) $(FUSED_GMOCK_GTEST_ALL_CC) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(FUSED_GMOCK_GTEST_ALL_CC) - -gmock_main.o : $(FUSED_GTEST_H) $(FUSED_GMOCK_H) $(GMOCK_MAIN_CC) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GMOCK_MAIN_CC) - -gmock_test.o : $(FUSED_GTEST_H) $(FUSED_GMOCK_H) $(GMOCK_TEST_CC) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GMOCK_TEST_CC) - -gmock_test : gmock_test.o gmock-gtest-all.o gmock_main.o - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ -o $@ diff --git a/testing/gmock/src/gmock-all.cc b/testing/gmock/src/gmock-all.cc index c9223fc..76118d8 100644 --- a/testing/gmock/src/gmock-all.cc +++ b/testing/gmock/src/gmock-all.cc @@ -43,6 +43,5 @@ #include "src/gmock-cardinalities.cc" #include "src/gmock-internal-utils.cc" #include "src/gmock-matchers.cc" -#include "src/gmock-printers.cc" #include "src/gmock-spec-builders.cc" #include "src/gmock.cc" diff --git a/testing/gmock/src/gmock-printers.cc b/testing/gmock/src/gmock-printers.cc deleted file mode 100644 index fd7d305..0000000 --- a/testing/gmock/src/gmock-printers.cc +++ /dev/null @@ -1,318 +0,0 @@ -// 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 a universal value printer that can print a -// value of any type T: -// -// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr); -// -// It uses the << operator when possible, and prints the bytes in the -// object otherwise. A user can override its behavior for a class -// type Foo by defining either operator<<(::std::ostream&, const Foo&) -// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that -// defines Foo. - -#include <gmock/gmock-printers.h> -#include <ctype.h> -#include <stdio.h> -#include <ostream> // NOLINT -#include <string> -#include <gmock/internal/gmock-port.h> - -namespace testing { - -namespace { - -using ::std::ostream; - -#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s. -#define snprintf _snprintf -#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf. -#define snprintf _snprintf_s -#elif _MSC_VER -#define snprintf _snprintf -#endif // GTEST_OS_WINDOWS_MOBILE - -// Prints a segment of bytes in the given object. -void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, - size_t count, ostream* os) { - char text[5] = ""; - for (size_t i = 0; i != count; i++) { - const size_t j = start + i; - if (i != 0) { - // Organizes the bytes into groups of 2 for easy parsing by - // human. - if ((j % 2) == 0) { - *os << " "; - } - } - snprintf(text, sizeof(text), "%02X", obj_bytes[j]); - *os << text; - } -} - -// Prints the bytes in the given value to the given ostream. -void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, - ostream* os) { - // Tells the user how big the object is. - *os << count << "-byte object <"; - - const size_t kThreshold = 132; - const size_t kChunkSize = 64; - // If the object size is bigger than kThreshold, we'll have to omit - // some details by printing only the first and the last kChunkSize - // bytes. - // TODO(wan): let the user control the threshold using a flag. - if (count < kThreshold) { - PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); - } else { - PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); - *os << " ... "; - // Rounds up to 2-byte boundary. - const size_t resume_pos = (count - kChunkSize + 1)/2*2; - PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); - } - *os << ">"; -} - -} // namespace - -namespace internal2 { - -// Delegates to PrintBytesInObjectToImpl() to print the bytes in the -// given object. The delegation simplifies the implementation, which -// uses the << operator and thus is easier done outside of the -// ::testing::internal namespace, which contains a << operator that -// sometimes conflicts with the one in STL. -void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, - ostream* os) { - PrintBytesInObjectToImpl(obj_bytes, count, os); -} - -} // namespace internal2 - -namespace internal { - -// Prints a wide char as a char literal without the quotes, escaping it -// when necessary. -static void PrintAsWideCharLiteralTo(wchar_t c, ostream* os) { - switch (c) { - case L'\0': - *os << "\\0"; - break; - case L'\'': - *os << "\\'"; - break; - case L'\?': - *os << "\\?"; - break; - case L'\\': - *os << "\\\\"; - break; - case L'\a': - *os << "\\a"; - break; - case L'\b': - *os << "\\b"; - break; - case L'\f': - *os << "\\f"; - break; - case L'\n': - *os << "\\n"; - break; - case L'\r': - *os << "\\r"; - break; - case L'\t': - *os << "\\t"; - break; - case L'\v': - *os << "\\v"; - break; - default: - // Checks whether c is printable or not. Printable characters are in - // the range [0x20,0x7E]. - // We test the value of c directly instead of calling isprint(), as - // isprint() is buggy on Windows mobile. - if (0x20 <= c && c <= 0x7E) { - *os << static_cast<char>(c); - } else { - // Buffer size enough for the maximum number of digits and \0. - char text[2 * sizeof(unsigned long) + 1] = ""; - snprintf(text, sizeof(text), "%lX", static_cast<unsigned long>(c)); - *os << "\\x" << text; - } - } -} - -// Prints a char as if it's part of a string literal, escaping it when -// necessary. -static void PrintAsWideStringLiteralTo(wchar_t c, ostream* os) { - switch (c) { - case L'\'': - *os << "'"; - break; - case L'"': - *os << "\\\""; - break; - default: - PrintAsWideCharLiteralTo(c, os); - } -} - -// Prints a char as a char literal without the quotes, escaping it -// when necessary. -static void PrintAsCharLiteralTo(char c, ostream* os) { - PrintAsWideCharLiteralTo(static_cast<unsigned char>(c), os); -} - -// Prints a char as if it's part of a string literal, escaping it when -// necessary. -static void PrintAsStringLiteralTo(char c, ostream* os) { - PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os); -} - -// Prints a char and its code. The '\0' char is printed as "'\\0'", -// other unprintable characters are also properly escaped using the -// standard C++ escape sequence. -void PrintCharTo(char c, int char_code, ostream* os) { - *os << "'"; - PrintAsCharLiteralTo(c, os); - *os << "'"; - if (c != '\0') - *os << " (" << char_code << ")"; -} - -// Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its decimal code (except for L'\0'). -// The L'\0' char is printed as "L'\\0'". The decimal code is printed -// as signed integer when wchar_t is implemented by the compiler -// as a signed type and is printed as an unsigned integer when wchar_t -// is implemented as an unsigned type. -void PrintTo(wchar_t wc, ostream* os) { - *os << "L'"; - PrintAsWideCharLiteralTo(wc, os); - *os << "'"; - if (wc != L'\0') { - // Type Int64 is used because it provides more storage than wchar_t thus - // when the compiler converts signed or unsigned implementation of wchar_t - // to Int64 it fills higher bits with either zeros or the sign bit - // passing it to operator <<() as either signed or unsigned integer. - *os << " (" << static_cast<Int64>(wc) << ")"; - } -} - -// Prints the given array of characters to the ostream. -// The array starts at *begin, the length is len, it may include '\0' characters -// and may not be null-terminated. -static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) { - *os << "\""; - for (size_t index = 0; index < len; ++index) { - PrintAsStringLiteralTo(begin[index], os); - } - *os << "\""; -} - -// Prints a (const) char array of 'len' elements, starting at address 'begin'. -void UniversalPrintArray(const char* begin, size_t len, ostream* os) { - PrintCharsAsStringTo(begin, len, os); -} - -// Prints the given array of wide characters to the ostream. -// The array starts at *begin, the length is len, it may include L'\0' -// characters and may not be null-terminated. -static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len, - ostream* os) { - *os << "L\""; - for (size_t index = 0; index < len; ++index) { - PrintAsWideStringLiteralTo(begin[index], os); - } - *os << "\""; -} - -// Prints the given C string to the ostream. -void PrintTo(const char* s, ostream* os) { - if (s == NULL) { - *os << "NULL"; - } else { - *os << implicit_cast<const void*>(s) << " pointing to "; - PrintCharsAsStringTo(s, strlen(s), os); - } -} - -// MSVC compiler can be configured to define whar_t as a typedef -// of unsigned short. Defining an overload for const wchar_t* in that case -// would cause pointers to unsigned shorts be printed as wide strings, -// possibly accessing more memory than intended and causing invalid -// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when -// wchar_t is implemented as a native type. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) -// Prints the given wide C string to the ostream. -void PrintTo(const wchar_t* s, ostream* os) { - if (s == NULL) { - *os << "NULL"; - } else { - *os << implicit_cast<const void*>(s) << " pointing to "; - PrintWideCharsAsStringTo(s, wcslen(s), os); - } -} -#endif // wchar_t is native - -// Prints a ::string object. -#if GTEST_HAS_GLOBAL_STRING -void PrintStringTo(const ::string& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} -#endif // GTEST_HAS_GLOBAL_STRING - -void PrintStringTo(const ::std::string& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} - -// Prints a ::wstring object. -#if GTEST_HAS_GLOBAL_WSTRING -void PrintWideStringTo(const ::wstring& s, ostream* os) { - PrintWideCharsAsStringTo(s.data(), s.size(), os); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -void PrintWideStringTo(const ::std::wstring& s, ostream* os) { - PrintWideCharsAsStringTo(s.data(), s.size(), os); -} -#endif // GTEST_HAS_STD_WSTRING - -} // namespace internal - -} // namespace testing diff --git a/testing/gmock/test/gmock-actions_test.cc b/testing/gmock/test/gmock-actions_test.cc index a2c6fe1..8391e5f 100644 --- a/testing/gmock/test/gmock-actions_test.cc +++ b/testing/gmock/test/gmock-actions_test.cc @@ -74,9 +74,9 @@ using testing::SetArgumentPointee; using testing::SetErrnoAndReturn; #endif -#if GMOCK_HAS_PROTOBUF_ +#if GTEST_HAS_PROTOBUF_ using testing::internal::TestMessage; -#endif // GMOCK_HAS_PROTOBUF_ +#endif // GTEST_HAS_PROTOBUF_ // Tests that BuiltInDefaultValue<T*>::Get() returns NULL. TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) { @@ -689,7 +689,7 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointee) { EXPECT_EQ('a', ch); } -#if GMOCK_HAS_PROTOBUF_ +#if GTEST_HAS_PROTOBUF_ // Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf // variable pointed to by the N-th (0-based) argument to proto_buffer. @@ -786,7 +786,7 @@ TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) { EXPECT_EQ("hi", dest.string_field()); } -#endif // GMOCK_HAS_PROTOBUF_ +#endif // GTEST_HAS_PROTOBUF_ // Sample functions and functors for testing Invoke() and etc. int Nullary() { return 1; } diff --git a/testing/gmock/test/gmock-generated-matchers_test.cc b/testing/gmock/test/gmock-generated-matchers_test.cc index 12479af..eebca8a 100644 --- a/testing/gmock/test/gmock-generated-matchers_test.cc +++ b/testing/gmock/test/gmock-generated-matchers_test.cc @@ -192,7 +192,8 @@ TEST(ArgsTest, AcceptsTenTemplateArgs) { TEST(ArgsTest, DescirbesSelfCorrectly) { const Matcher<tuple<int, bool, char> > m = Args<2, 0>(Lt()); - EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair (x, y) where x < y", + EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where " + "the first < the second", Describe(m)); } @@ -200,14 +201,14 @@ TEST(ArgsTest, DescirbesNestedArgsCorrectly) { const Matcher<const tuple<int, bool, char, int>&> m = Args<0, 2, 3>(Args<2, 0>(Lt())); EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple " - "whose fields (#2, #0) are a pair (x, y) where x < y", + "whose fields (#2, #0) are a pair where the first < the second", Describe(m)); } TEST(ArgsTest, DescribesNegationCorrectly) { const Matcher<tuple<int, char> > m = Args<1, 0>(Gt()); - EXPECT_EQ("are a tuple whose fields (#1, #0) are a pair (x, y) " - "where x > y is false", + EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair " + "where the first > the second", DescribeNegation(m)); } diff --git a/testing/gmock/test/gmock-internal-utils_test.cc b/testing/gmock/test/gmock-internal-utils_test.cc index fc5d9e5..4309f7c 100644 --- a/testing/gmock/test/gmock-internal-utils_test.cc +++ b/testing/gmock/test/gmock-internal-utils_test.cc @@ -96,102 +96,6 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { ConvertIdentifierNameToWords("_Chapter11Section_1_")); } -// 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 GMOCK_REMOVE_REFERENCE_. - -template <typename T1, typename T2> -void TestGMockRemoveReference() { - CompileAssertTypesEqual<T1, GMOCK_REMOVE_REFERENCE_(T2)>(); -} - -TEST(RemoveReferenceTest, MacroVersion) { - TestGMockRemoveReference<int, int>(); - TestGMockRemoveReference<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 GMOCK_REMOVE_CONST_. - -template <typename T1, typename T2> -void TestGMockRemoveConst() { - CompileAssertTypesEqual<T1, GMOCK_REMOVE_CONST_(T2)>(); -} - -TEST(RemoveConstTest, MacroVersion) { - TestGMockRemoveConst<int, int>(); - TestGMockRemoveConst<double&, double&>(); - TestGMockRemoveConst<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 GMOCK_ADD_REFERENCE_. - -template <typename T1, typename T2> -void TestGMockAddReference() { - CompileAssertTypesEqual<T1, GMOCK_ADD_REFERENCE_(T2)>(); -} - -TEST(AddReferenceTest, MacroVersion) { - TestGMockAddReference<int&, int>(); - TestGMockAddReference<const char&, const char&>(); -} - -// Tests GMOCK_REFERENCE_TO_CONST_. - -template <typename T1, typename T2> -void TestGMockReferenceToConst() { - CompileAssertTypesEqual<T1, GMOCK_REFERENCE_TO_CONST_(T2)>(); -} - -TEST(GMockReferenceToConstTest, Works) { - TestGMockReferenceToConst<const char&, char>(); - TestGMockReferenceToConst<const int&, const int>(); - TestGMockReferenceToConst<const double&, double>(); - TestGMockReferenceToConst<const string&, const string&>(); -} - TEST(PointeeOfTest, WorksForSmartPointers) { CompileAssertTypesEqual<const char, PointeeOf<internal::linked_ptr<const char> >::type>(); @@ -217,38 +121,11 @@ TEST(GetRawPointerTest, WorksForRawPointers) { EXPECT_EQ(&n, GetRawPointer(&n)); } +// Tests KindOf<T>. + class Base {}; class Derived : public Base {}; -// Tests that ImplicitlyConvertible<T1, T2>::value is a compile-time constant. -TEST(ImplicitlyConvertibleTest, ValueIsCompileTimeConstant) { - GMOCK_COMPILE_ASSERT_((ImplicitlyConvertible<int, int>::value), const_true); - GMOCK_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<Derived&, const Base&>::value)); - EXPECT_TRUE((ImplicitlyConvertible<const Base, Base>::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<Base&, Derived&>::value)); -} - -// Tests KindOf<T>. - TEST(KindOfTest, Bool) { EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool)); // NOLINT } @@ -382,46 +259,6 @@ TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { } } -// Tests that IsAProtocolMessage<T>::value is a compile-time constant. -TEST(IsAProtocolMessageTest, ValueIsCompileTimeConstant) { - GMOCK_COMPILE_ASSERT_(IsAProtocolMessage<ProtocolMessage>::value, const_true); - GMOCK_COMPILE_ASSERT_(!IsAProtocolMessage<int>::value, const_false); -} - -// Tests that IsAProtocolMessage<T>::value is true when T is -// ProtocolMessage or a sub-class of it. -TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { - EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); - EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value); -#if GMOCK_HAS_PROTOBUF_ - EXPECT_TRUE(IsAProtocolMessage<const TestMessage>::value); -#endif // GMOCK_HAS_PROTOBUF_ -} - -// 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 Base>::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 the TupleMatches() template function. TEST(TupleMatchesTest, WorksForSize0) { @@ -565,10 +402,12 @@ void TestLogWithSeverity(const string& verbosity, LogSeverity severity, // Tests that when the stack_frames_to_skip parameter is negative, // Log() doesn't include the stack trace in the output. TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { + const string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = kInfoVerbosity; CaptureStdout(); Log(INFO, "Test log.\n", -1); EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str()); + GMOCK_FLAG(verbose) = saved_flag; } // Tests that in opt mode, a positive stack_frames_to_skip argument is @@ -735,148 +574,6 @@ TEST(OnCallTest, LogsAnythingArgument) { #endif // GTEST_HAS_STREAM_REDIRECTION_ -// Tests ArrayEq(). - -TEST(ArrayEqTest, WorksForDegeneratedArrays) { - EXPECT_TRUE(ArrayEq(5, 5L)); - EXPECT_FALSE(ArrayEq('a', 0)); -} - -TEST(ArrayEqTest, WorksForOneDimensionalArrays) { - 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]; - CopyArray(a, &b); - EXPECT_TRUE(ArrayEq(a, b)); - - 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]; - CopyArray(a, &b); - EXPECT_TRUE(ArrayEq(a, b)); - - 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, kReference); - 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, kCopy); - 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, kCopy); - 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_THAT(na, Eq(na)); - - NativeArray<int> na2(a, 3, kReference); - EXPECT_THAT(na, Eq(na2)); - - const int b1[3] = { 0, 1, 1 }; - const int b2[4] = { 0, 1, 2, 3 }; - EXPECT_THAT(na, Not(Eq(NativeArray<int>(b1, 3, kReference)))); - EXPECT_THAT(na, Not(Eq(NativeArray<int>(b2, 4, kCopy)))); -} - -TEST(NativeArrayTest, WorksForTwoDimensionalArray) { - const char a[2][3] = { "hi", "lo" }; - NativeArray<char[3]> na(a, 2, kReference); - ASSERT_EQ(2U, na.size()); - EXPECT_EQ(a, na.begin()); -} - // Tests StlContainerView. TEST(StlContainerViewTest, WorksForStlContainer) { diff --git a/testing/gmock/test/gmock-matchers_test.cc b/testing/gmock/test/gmock-matchers_test.cc index 6d784f1..3b151db 100644 --- a/testing/gmock/test/gmock-matchers_test.cc +++ b/testing/gmock/test/gmock-matchers_test.cc @@ -61,12 +61,19 @@ bool SkipPrefix(const char* prefix, const char** pstr); namespace gmock_matchers_test { +using std::list; using std::make_pair; using std::map; using std::multimap; +using std::multiset; +using std::ostream; using std::pair; +using std::set; using std::stringstream; +using std::tr1::get; using std::tr1::make_tuple; +using std::tr1::tuple; +using std::vector; using testing::A; using testing::AllArgs; using testing::AllOf; @@ -102,6 +109,7 @@ using testing::Not; using testing::NotNull; using testing::Pair; using testing::Pointee; +using testing::Pointwise; using testing::PolymorphicMatcher; using testing::Property; using testing::Ref; @@ -142,7 +150,7 @@ class GreaterThanMatcher : public MatcherInterface<int> { public: explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} - virtual void DescribeTo(::std::ostream* os) const { + virtual void DescribeTo(ostream* os) const { *os << "is > " << rhs_; } @@ -187,9 +195,9 @@ string DescribeNegation(const Matcher<T>& m) { // Returns the reason why x matches, or doesn't match, m. template <typename MatcherType, typename Value> string Explain(const MatcherType& m, const Value& x) { - stringstream ss; - m.ExplainMatchResultTo(x, &ss); - return ss.str(); + StringMatchResultListener listener; + ExplainMatchResult(m, x, &listener); + return listener.str(); } TEST(MatchResultListenerTest, StreamingWorks) { @@ -226,7 +234,7 @@ class EvenMatcherImpl : public MatcherInterface<int> { return x % 2 == 0; } - virtual void DescribeTo(::std::ostream* os) const { + virtual void DescribeTo(ostream* os) const { *os << "is an even number"; } @@ -256,7 +264,7 @@ class NewEvenMatcherImpl : public MatcherInterface<int> { return match; } - virtual void DescribeTo(::std::ostream* os) const { + virtual void DescribeTo(ostream* os) const { *os << "is an even number"; } }; @@ -363,20 +371,20 @@ TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { // Tests that MakePolymorphicMatcher() can construct a polymorphic // matcher from its implementation using the old API. -const int bar = 1; +const int g_bar = 1; class ReferencesBarOrIsZeroImpl { public: template <typename T> bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const { const void* p = &x; - return p == &bar || x == 0; + return p == &g_bar || x == 0; } - void DescribeTo(::std::ostream* os) const { *os << "bar or zero"; } + void DescribeTo(ostream* os) const { *os << "g_bar or zero"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't reference bar and is not zero"; + void DescribeNegationTo(ostream* os) const { + *os << "doesn't reference g_bar and is not zero"; } }; @@ -391,24 +399,24 @@ TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { Matcher<const int&> m1 = ReferencesBarOrIsZero(); EXPECT_TRUE(m1.Matches(0)); // Verifies that the identity of a by-reference argument is preserved. - EXPECT_TRUE(m1.Matches(bar)); + EXPECT_TRUE(m1.Matches(g_bar)); EXPECT_FALSE(m1.Matches(1)); - EXPECT_EQ("bar or zero", Describe(m1)); + EXPECT_EQ("g_bar or zero", Describe(m1)); // Using a polymorphic matcher to match a value type. Matcher<double> m2 = ReferencesBarOrIsZero(); EXPECT_TRUE(m2.Matches(0.0)); EXPECT_FALSE(m2.Matches(0.1)); - EXPECT_EQ("bar or zero", Describe(m2)); + EXPECT_EQ("g_bar or zero", Describe(m2)); } // Tests implementing a polymorphic matcher using MatchAndExplain(). class PolymorphicIsEvenImpl { public: - void DescribeTo(::std::ostream* os) const { *os << "is even"; } + void DescribeTo(ostream* os) const { *os << "is even"; } - void DescribeNegationTo(::std::ostream* os) const { + void DescribeNegationTo(ostream* os) const { *os << "is odd"; } @@ -1148,7 +1156,7 @@ TEST(KeyTest, SafelyCastsInnerMatcher) { } TEST(KeyTest, InsideContainsUsingMap) { - std::map<int, char> container; + map<int, char> container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); @@ -1157,7 +1165,7 @@ TEST(KeyTest, InsideContainsUsingMap) { } TEST(KeyTest, InsideContainsUsingMultimap) { - std::multimap<int, char> container; + multimap<int, char> container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); @@ -1266,7 +1274,7 @@ TEST(PairTest, SafelyCastsInnerMatchers) { } TEST(PairTest, InsideContainsUsingMap) { - std::map<int, char> container; + map<int, char> container; container.insert(make_pair(1, 'a')); container.insert(make_pair(2, 'b')); container.insert(make_pair(4, 'c')); @@ -1759,7 +1767,7 @@ TEST(Eq2Test, MatchesEqualArguments) { // Tests that Eq() describes itself properly. TEST(Eq2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Eq(); - EXPECT_EQ("are a pair (x, y) where x == y", Describe(m)); + EXPECT_EQ("are an equal pair", Describe(m)); } // Tests that Ge() matches a 2-tuple where the first field >= the @@ -1774,7 +1782,7 @@ TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) { // Tests that Ge() describes itself properly. TEST(Ge2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Ge(); - EXPECT_EQ("are a pair (x, y) where x >= y", Describe(m)); + EXPECT_EQ("are a pair where the first >= the second", Describe(m)); } // Tests that Gt() matches a 2-tuple where the first field > the @@ -1789,7 +1797,7 @@ TEST(Gt2Test, MatchesGreaterThanArguments) { // Tests that Gt() describes itself properly. TEST(Gt2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Gt(); - EXPECT_EQ("are a pair (x, y) where x > y", Describe(m)); + EXPECT_EQ("are a pair where the first > the second", Describe(m)); } // Tests that Le() matches a 2-tuple where the first field <= the @@ -1804,7 +1812,7 @@ TEST(Le2Test, MatchesLessThanOrEqualArguments) { // Tests that Le() describes itself properly. TEST(Le2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Le(); - EXPECT_EQ("are a pair (x, y) where x <= y", Describe(m)); + EXPECT_EQ("are a pair where the first <= the second", Describe(m)); } // Tests that Lt() matches a 2-tuple where the first field < the @@ -1819,7 +1827,7 @@ TEST(Lt2Test, MatchesLessThanArguments) { // Tests that Lt() describes itself properly. TEST(Lt2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Lt(); - EXPECT_EQ("are a pair (x, y) where x < y", Describe(m)); + EXPECT_EQ("are a pair where the first < the second", Describe(m)); } // Tests that Ne() matches a 2-tuple where the first field != the @@ -1834,7 +1842,7 @@ TEST(Ne2Test, MatchesUnequalArguments) { // Tests that Ne() describes itself properly. TEST(Ne2Test, CanDescribeSelf) { Matcher<const Tuple2&> m = Ne(); - EXPECT_EQ("are a pair (x, y) where x != y", Describe(m)); + EXPECT_EQ("are an unequal pair", Describe(m)); } // Tests that Not(m) matches any value that doesn't match m. @@ -3336,11 +3344,11 @@ class DivisibleByImpl { return (n % divider_) == 0; } - void DescribeTo(::std::ostream* os) const { + void DescribeTo(ostream* os) const { *os << "is divisible by " << divider_; } - void DescribeNegationTo(::std::ostream* os) const { + void DescribeNegationTo(ostream* os) const { *os << "is not divisible by " << divider_; } @@ -3442,10 +3450,10 @@ template <typename T> class ContainerEqTest : public testing::Test {}; typedef testing::Types< - std::set<int>, - std::vector<size_t>, - std::multiset<size_t>, - std::list<int> > + set<int>, + vector<size_t>, + multiset<size_t>, + list<int> > ContainerEqTestTypes; TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes); @@ -3513,9 +3521,9 @@ TYPED_TEST(ContainerEqTest, DuplicateDifference) { TEST(ContainerEqExtraTest, MultipleValuesMissing) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {2, 1, 5}; - std::vector<int> my_set(vals, vals + 6); - std::vector<int> test_set(test_vals, test_vals + 3); - const Matcher<std::vector<int> > m = ContainerEq(my_set); + vector<int> my_set(vals, vals + 6); + vector<int> test_set(test_vals, test_vals + 3); + const Matcher<vector<int> > m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which doesn't have these expected elements: 3, 8", Explain(m, test_set)); @@ -3526,9 +3534,9 @@ TEST(ContainerEqExtraTest, MultipleValuesMissing) { TEST(ContainerEqExtraTest, MultipleValuesAdded) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; - std::list<size_t> my_set(vals, vals + 6); - std::list<size_t> test_set(test_vals, test_vals + 7); - const Matcher<const std::list<size_t>&> m = ContainerEq(my_set); + list<size_t> my_set(vals, vals + 6); + list<size_t> test_set(test_vals, test_vals + 7); + const Matcher<const list<size_t>&> m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 92, 46", Explain(m, test_set)); @@ -3538,9 +3546,9 @@ TEST(ContainerEqExtraTest, MultipleValuesAdded) { TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 92, 46}; - std::list<size_t> my_set(vals, vals + 6); - std::list<size_t> test_set(test_vals, test_vals + 5); - const Matcher<const std::list<size_t> > m = ContainerEq(my_set); + list<size_t> my_set(vals, vals + 6); + list<size_t> test_set(test_vals, test_vals + 5); + const Matcher<const list<size_t> > m = ContainerEq(my_set); EXPECT_FALSE(m.Matches(test_set)); EXPECT_EQ("which has these unexpected elements: 92, 46,\n" "and doesn't have these expected elements: 5, 8", @@ -3552,9 +3560,9 @@ TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { static const int vals[] = {1, 1, 2, 3, 5, 8}; static const int test_vals[] = {1, 2, 3, 5, 8}; - std::vector<int> my_set(vals, vals + 6); - std::vector<int> test_set(test_vals, test_vals + 5); - const Matcher<std::vector<int> > m = ContainerEq(my_set); + vector<int> my_set(vals, vals + 6); + vector<int> test_set(test_vals, test_vals + 5); + const Matcher<vector<int> > m = ContainerEq(my_set); EXPECT_TRUE(m.Matches(my_set)); EXPECT_FALSE(m.Matches(test_set)); // There is nothing to report when both sets contain all the same values. @@ -3564,15 +3572,15 @@ TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { // Tests that ContainerEq works for non-trivial associative containers, // like maps. TEST(ContainerEqExtraTest, WorksForMaps) { - std::map<int, std::string> my_map; + map<int, std::string> my_map; my_map[0] = "a"; my_map[1] = "b"; - std::map<int, std::string> test_map; + map<int, std::string> test_map; test_map[0] = "aa"; test_map[1] = "b"; - const Matcher<const std::map<int, std::string>&> m = ContainerEq(my_map); + const Matcher<const map<int, std::string>&> m = ContainerEq(my_map); EXPECT_TRUE(m.Matches(my_map)); EXPECT_FALSE(m.Matches(test_map)); @@ -3984,5 +3992,209 @@ TEST(MatcherTupleTest, ExplainsMatchFailure) { // explanation. } +// Tests Each(). + +TEST(EachTest, ExplainsMatchResultCorrectly) { + set<int> a; // empty + + Matcher<set<int> > m = Each(2); + EXPECT_EQ("", Explain(m, a)); + + Matcher<const int(&)[1]> n = Each(1); + + const int b[1] = { 1 }; + EXPECT_EQ("", Explain(n, b)); + + n = Each(3); + EXPECT_EQ("whose element #0 doesn't match", Explain(n, b)); + + a.insert(1); + a.insert(2); + a.insert(3); + m = Each(GreaterThan(0)); + EXPECT_EQ("", Explain(m, a)); + + m = Each(GreaterThan(10)); + EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10", + Explain(m, a)); +} + +TEST(EachTest, DescribesItselfCorrectly) { + Matcher<vector<int> > m = Each(1); + EXPECT_EQ("only contains elements that is equal to 1", Describe(m)); + + Matcher<vector<int> > m2 = Not(m); + EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2)); +} + +TEST(EachTest, MatchesVectorWhenAllElementsMatch) { + vector<int> some_vector; + EXPECT_THAT(some_vector, Each(1)); + some_vector.push_back(3); + EXPECT_THAT(some_vector, Not(Each(1))); + EXPECT_THAT(some_vector, Each(3)); + some_vector.push_back(1); + some_vector.push_back(2); + EXPECT_THAT(some_vector, Not(Each(3))); + EXPECT_THAT(some_vector, Each(Lt(3.5))); + + vector<string> another_vector; + another_vector.push_back("fee"); + EXPECT_THAT(another_vector, Each(string("fee"))); + another_vector.push_back("fie"); + another_vector.push_back("foe"); + another_vector.push_back("fum"); + EXPECT_THAT(another_vector, Not(Each(string("fee")))); +} + +TEST(EachTest, MatchesMapWhenAllElementsMatch) { + map<const char*, int> my_map; + const char* bar = "a string"; + my_map[bar] = 2; + EXPECT_THAT(my_map, Each(make_pair(bar, 2))); + + map<string, int> another_map; + EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + another_map["fee"] = 1; + EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1))); + another_map["fie"] = 2; + another_map["foe"] = 3; + another_map["fum"] = 4; + EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1)))); + EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1)))); + EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); +} + +TEST(EachTest, AcceptsMatcher) { + const int a[] = { 1, 2, 3 }; + EXPECT_THAT(a, Each(Gt(0))); + EXPECT_THAT(a, Not(Each(Gt(1)))); +} + +TEST(EachTest, WorksForNativeArrayAsTuple) { + const int a[] = { 1, 2 }; + const int* const pointer = a; + EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0))); + EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1)))); +} + +// For testing Pointwise(). +class IsHalfOfMatcher { + public: + template <typename T1, typename T2> + bool MatchAndExplain(const tuple<T1, T2>& a_pair, + MatchResultListener* listener) const { + if (get<0>(a_pair) == get<1>(a_pair)/2) { + *listener << "where the second is " << get<1>(a_pair); + return true; + } else { + *listener << "where the second/2 is " << get<1>(a_pair)/2; + return false; + } + } + + void DescribeTo(ostream* os) const { + *os << "are a pair where the first is half of the second"; + } + + void DescribeNegationTo(ostream* os) const { + *os << "are a pair where the first isn't half of the second"; + } +}; + +PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() { + return MakePolymorphicMatcher(IsHalfOfMatcher()); +} + +TEST(PointwiseTest, DescribesSelf) { + vector<int> rhs; + rhs.push_back(1); + rhs.push_back(2); + rhs.push_back(3); + const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs); + EXPECT_EQ("contains 3 values, where each value and its corresponding value " + "in { 1, 2, 3 } are a pair where the first is half of the second", + Describe(m)); + EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " + "index i where x and the i-th value of { 1, 2, 3 } are a pair " + "where the first isn't half of the second", + DescribeNegation(m)); +} + +TEST(PointwiseTest, MakesCopyOfRhs) { + list<signed char> rhs; + rhs.push_back(2); + rhs.push_back(4); + + int lhs[] = { 1, 2 }; + const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs); + EXPECT_THAT(lhs, m); + + // Changing rhs now shouldn't affect m, which made a copy of rhs. + rhs.push_back(6); + EXPECT_THAT(lhs, m); +} + +TEST(PointwiseTest, WorksForLhsNativeArray) { + const int lhs[] = { 1, 2, 3 }; + vector<int> rhs; + rhs.push_back(2); + rhs.push_back(4); + rhs.push_back(6); + EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); + EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); +} + +TEST(PointwiseTest, WorksForRhsNativeArray) { + const int rhs[] = { 1, 2, 3 }; + vector<int> lhs; + lhs.push_back(2); + lhs.push_back(4); + lhs.push_back(6); + EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); + EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); +} + +TEST(PointwiseTest, RejectsWrongSize) { + const double lhs[2] = { 1, 2 }; + const int rhs[1] = { 0 }; + EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); + EXPECT_EQ("which contains 2 values", + Explain(Pointwise(Gt(), rhs), lhs)); + + const int rhs2[3] = { 0, 1, 2 }; + EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); +} + +TEST(PointwiseTest, RejectsWrongContent) { + const double lhs[3] = { 1, 2, 3 }; + const int rhs[3] = { 2, 6, 4 }; + EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); + EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " + "where the second/2 is 3", + Explain(Pointwise(IsHalfOf(), rhs), lhs)); +} + +TEST(PointwiseTest, AcceptsCorrectContent) { + const double lhs[3] = { 1, 2, 3 }; + const int rhs[3] = { 2, 4, 6 }; + EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); + EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs)); +} + +TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { + const double lhs[3] = { 1, 2, 3 }; + const int rhs[3] = { 2, 4, 6 }; + const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf(); + EXPECT_THAT(lhs, Pointwise(m1, rhs)); + EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs)); + + // This type works as a tuple<const double&, const int&> can be + // implicitly cast to tuple<double, int>. + const Matcher<tuple<double, int> > m2 = IsHalfOf(); + EXPECT_THAT(lhs, Pointwise(m2, rhs)); + EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs)); +} + } // namespace gmock_matchers_test } // namespace testing diff --git a/testing/gmock/test/gmock-nice-strict_test.cc b/testing/gmock/test/gmock-nice-strict_test.cc index f6f278e..0e52450 100644 --- a/testing/gmock/test/gmock-nice-strict_test.cc +++ b/testing/gmock/test/gmock-nice-strict_test.cc @@ -137,6 +137,7 @@ TEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) { TEST(NiceMockTest, InfoForUninterestingCall) { NiceMock<MockFoo> nice_foo; + const string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = "info"; CaptureStdout(); nice_foo.DoThis(); @@ -147,6 +148,7 @@ TEST(NiceMockTest, InfoForUninterestingCall) { nice_foo.DoThat(true); EXPECT_THAT(GetCapturedStdout(), HasSubstr("Uninteresting mock function call")); + GMOCK_FLAG(verbose) = saved_flag; } #endif // GTEST_HAS_STREAM_REDIRECTION_ diff --git a/testing/gmock/test/gmock-port_test.cc b/testing/gmock/test/gmock-port_test.cc index 054313b..a84eb9e 100644 --- a/testing/gmock/test/gmock-port_test.cc +++ b/testing/gmock/test/gmock-port_test.cc @@ -39,126 +39,5 @@ // NOTE: if this file is left without tests for some reason, put a dummy // test here to make references to symbols in the gtest library and avoid // 'undefined symbol' linker errors in gmock_main: -// -// TEST(DummyTest, Dummy) {} - -namespace testing { -namespace internal { -// Needed to avoid name collisions in gmock_all_test.cc. -namespace gmock_port_test { - -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::implicit_cast<Base*>(&derived)); -} - -TEST(ImplicitCastTest, CanUseInheritance) { - Derived derived(1); - Base base = ::testing::internal::implicit_cast<Base>(derived); - EXPECT_EQ(derived.member(), base.member()); -} - -class Castable { - public: - 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::implicit_cast<Base>(castable); - EXPECT_TRUE(converted); -} - -class ConstCastable { - public: - 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::implicit_cast<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::implicit_cast<Base>(castable); - EXPECT_TRUE(converted); - EXPECT_FALSE(const_converted); - - converted = false; - const_converted = false; - const ConstAndNonConstCastable const_castable(&converted, &const_converted); - base = ::testing::internal::implicit_cast<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::implicit_cast<To>(&converted); - EXPECT_TRUE(converted); -} -} // namespace gmock_port_test -} // namespace internal -} // namespace testing +TEST(DummyTest, Dummy) {} diff --git a/testing/gmock/test/gmock-printers_test.cc b/testing/gmock/test/gmock-printers_test.cc deleted file mode 100644 index 92c8413..0000000 --- a/testing/gmock/test/gmock-printers_test.cc +++ /dev/null @@ -1,1118 +0,0 @@ -// 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 universal value printer. - -#include <gmock/gmock-printers.h> - -#include <ctype.h> -#include <limits.h> -#include <string.h> -#include <algorithm> -#include <deque> -#include <list> -#include <map> -#include <set> -#include <sstream> -#include <string> -#include <utility> -#include <vector> -#include <gmock/gmock-generated-matchers.h> -#include <gmock/gmock-matchers.h> -#include <gmock/internal/gmock-port.h> -#include <gtest/gtest.h> - -// hash_map and hash_set are available on Windows. -#if GTEST_OS_WINDOWS -#define GMOCK_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. -#include <hash_map> // NOLINT -#define GMOCK_HAS_HASH_SET_ 1 // Indicates that hash_set is available. -#include <hash_set> // NOLINT -#endif // GTEST_OS_WINDOWS - -// Some user-defined types for testing the universal value printer. - -// A user-defined unprintable class template in the global namespace. -template <typename T> -class UnprintableTemplateInGlobal { - public: - UnprintableTemplateInGlobal() : value_() {} - private: - T value_; -}; - -// A user-defined streamable type in the global namespace. -class StreamableInGlobal { - public: - virtual ~StreamableInGlobal() {} -}; - -inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) { - os << "StreamableInGlobal"; -} - -namespace foo { - -// A user-defined unprintable type in a user namespace. -class UnprintableInFoo { - public: - UnprintableInFoo() : x_(0x12EF), y_(0xAB34), z_(0) {} - private: - testing::internal::Int32 x_; - testing::internal::Int32 y_; - double z_; -}; - -// A user-defined printable type in a user-chosen namespace. -struct PrintableViaPrintTo { - PrintableViaPrintTo() : value() {} - int value; -}; - -void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) { - *os << "PrintableViaPrintTo: " << x.value; -} - -// A user-defined printable class template in a user-chosen namespace. -template <typename T> -class PrintableViaPrintToTemplate { - public: - explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template <typename T> -void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) { - *os << "PrintableViaPrintToTemplate: " << x.value(); -} - -// A user-defined streamable class template in a user namespace. -template <typename T> -class StreamableTemplateInFoo { - public: - StreamableTemplateInFoo() : value_() {} - - const T& value() const { return value_; } - private: - T value_; -}; - -template <typename T> -inline ::std::ostream& operator<<(::std::ostream& os, - const StreamableTemplateInFoo<T>& x) { - return os << "StreamableTemplateInFoo: " << x.value(); -} - -} // namespace foo - -namespace testing { -namespace gmock_printers_test { - -using ::std::deque; -using ::std::list; -using ::std::make_pair; -using ::std::map; -using ::std::multimap; -using ::std::multiset; -using ::std::pair; -using ::std::set; -using ::std::tr1::make_tuple; -using ::std::tr1::tuple; -using ::std::vector; -using ::testing::ElementsAre; -using ::testing::PrintToString; -using ::testing::StartsWith; -using ::testing::internal::NativeArray; -using ::testing::internal::Strings; -using ::testing::internal::UniversalTersePrint; -using ::testing::internal::UniversalPrint; -using ::testing::internal::UniversalTersePrintTupleFieldsToStrings; -using ::testing::internal::UniversalPrinter; -using ::testing::internal::kReference; -using ::testing::internal::string; - -#if GTEST_OS_WINDOWS -// MSVC defines the following classes in the ::stdext namespace while -// gcc defines them in the :: namespace. Note that they are not part -// of the C++ standard. - -using ::stdext::hash_map; -using ::stdext::hash_set; -using ::stdext::hash_multimap; -using ::stdext::hash_multiset; - -#endif // GTEST_OS_WINDOWS - -// Prints a value to a string using the universal value printer. This -// is a helper for testing UniversalPrinter<T>::Print() for various types. -template <typename T> -string Print(const T& value) { - ::std::stringstream ss; - UniversalPrinter<T>::Print(value, &ss); - return ss.str(); -} - -// Prints a value passed by reference to a string, using the universal -// value printer. This is a helper for testing -// UniversalPrinter<T&>::Print() for various types. -template <typename T> -string PrintByRef(const T& value) { - ::std::stringstream ss; - UniversalPrinter<T&>::Print(value, &ss); - return ss.str(); -} - -// Tests printing various char types. - -// char. -TEST(PrintCharTest, PlainChar) { - EXPECT_EQ("'\\0'", Print('\0')); - EXPECT_EQ("'\\'' (39)", Print('\'')); - EXPECT_EQ("'\"' (34)", Print('"')); - EXPECT_EQ("'\\?' (63)", Print('\?')); - EXPECT_EQ("'\\\\' (92)", Print('\\')); - EXPECT_EQ("'\\a' (7)", Print('\a')); - EXPECT_EQ("'\\b' (8)", Print('\b')); - EXPECT_EQ("'\\f' (12)", Print('\f')); - EXPECT_EQ("'\\n' (10)", Print('\n')); - EXPECT_EQ("'\\r' (13)", Print('\r')); - EXPECT_EQ("'\\t' (9)", Print('\t')); - EXPECT_EQ("'\\v' (11)", Print('\v')); - EXPECT_EQ("'\\x7F' (127)", Print('\x7F')); - EXPECT_EQ("'\\xFF' (255)", Print('\xFF')); - EXPECT_EQ("' ' (32)", Print(' ')); - EXPECT_EQ("'a' (97)", Print('a')); -} - -// signed char. -TEST(PrintCharTest, SignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0'))); - EXPECT_EQ("'\\xCE' (-50)", - Print(static_cast<signed char>(-50))); -} - -// unsigned char. -TEST(PrintCharTest, UnsignedChar) { - EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0'))); - EXPECT_EQ("'b' (98)", - Print(static_cast<unsigned char>('b'))); -} - -// Tests printing other simple, built-in types. - -// bool. -TEST(PrintBuiltInTypeTest, Bool) { - EXPECT_EQ("false", Print(false)); - EXPECT_EQ("true", Print(true)); -} - -// wchar_t. -TEST(PrintBuiltInTypeTest, Wchar_t) { - EXPECT_EQ("L'\\0'", Print(L'\0')); - EXPECT_EQ("L'\\'' (39)", Print(L'\'')); - EXPECT_EQ("L'\"' (34)", Print(L'"')); - EXPECT_EQ("L'\\?' (63)", Print(L'\?')); - EXPECT_EQ("L'\\\\' (92)", Print(L'\\')); - EXPECT_EQ("L'\\a' (7)", Print(L'\a')); - EXPECT_EQ("L'\\b' (8)", Print(L'\b')); - EXPECT_EQ("L'\\f' (12)", Print(L'\f')); - EXPECT_EQ("L'\\n' (10)", Print(L'\n')); - EXPECT_EQ("L'\\r' (13)", Print(L'\r')); - EXPECT_EQ("L'\\t' (9)", Print(L'\t')); - EXPECT_EQ("L'\\v' (11)", Print(L'\v')); - EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F')); - EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF')); - EXPECT_EQ("L' ' (32)", Print(L' ')); - EXPECT_EQ("L'a' (97)", Print(L'a')); - EXPECT_EQ("L'\\x576' (1398)", Print(L'\x576')); - EXPECT_EQ("L'\\xC74D' (51021)", Print(L'\xC74D')); -} - -// Test that Int64 provides more storage than wchar_t. -TEST(PrintTypeSizeTest, Wchar_t) { - EXPECT_LT(sizeof(wchar_t), sizeof(testing::internal::Int64)); -} - -// Various integer types. -TEST(PrintBuiltInTypeTest, Integer) { - EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255))); // uint8 - EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128))); // int8 - EXPECT_EQ("65535", Print(USHRT_MAX)); // uint16 - EXPECT_EQ("-32768", Print(SHRT_MIN)); // int16 - EXPECT_EQ("4294967295", Print(UINT_MAX)); // uint32 - EXPECT_EQ("-2147483648", Print(INT_MIN)); // int32 - EXPECT_EQ("18446744073709551615", - Print(static_cast<testing::internal::UInt64>(-1))); // uint64 - EXPECT_EQ("-9223372036854775808", - Print(static_cast<testing::internal::Int64>(1) << 63)); // int64 -} - -// Size types. -TEST(PrintBuiltInTypeTest, Size_t) { - EXPECT_EQ("1", Print(sizeof('a'))); // size_t. -#if !GTEST_OS_WINDOWS - // Windows has no ssize_t type. - EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2))); // ssize_t. -#endif // !GTEST_OS_WINDOWS -} - -// Floating-points. -TEST(PrintBuiltInTypeTest, FloatingPoints) { - EXPECT_EQ("1.5", Print(1.5f)); // float - EXPECT_EQ("-2.5", Print(-2.5)); // double -} - -// Since ::std::stringstream::operator<<(const void *) formats the pointer -// output differently with different compilers, we have to create the expected -// output first and use it as our expectation. -static string PrintPointer(const void *p) { - ::std::stringstream expected_result_stream; - expected_result_stream << p; - return expected_result_stream.str(); -} - -// Tests printing C strings. - -// const char*. -TEST(PrintCStringTest, Const) { - const char* p = "World"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p)); -} - -// char*. -TEST(PrintCStringTest, NonConst) { - char p[] = "Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"", - Print(static_cast<char*>(p))); -} - -// NULL C string. -TEST(PrintCStringTest, Null) { - const char* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that C strings are escaped properly. -TEST(PrintCStringTest, EscapesProperly) { - const char* p = "'\"\?\\\a\b\f\n\r\t\v\x7F\xFF a"; - EXPECT_EQ(PrintPointer(p) + " pointing to \"'\\\"\\?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\x7F\\xFF a\"", - Print(p)); -} - - - -// MSVC compiler can be configured to define whar_t as a typedef -// of unsigned short. Defining an overload for const wchar_t* in that case -// would cause pointers to unsigned shorts be printed as wide strings, -// possibly accessing more memory than intended and causing invalid -// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when -// wchar_t is implemented as a native type. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) - -// const wchar_t*. -TEST(PrintWideCStringTest, Const) { - const wchar_t* p = L"World"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p)); -} - -// wchar_t*. -TEST(PrintWideCStringTest, NonConst) { - wchar_t p[] = L"Hi"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"", - Print(static_cast<wchar_t*>(p))); -} - -// NULL wide C string. -TEST(PrintWideCStringTest, Null) { - const wchar_t* p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests that wide C strings are escaped properly. -TEST(PrintWideCStringTest, EscapesProperly) { - const wchar_t* p = L"'\"\?\\\a\b\f\n\r\t\v\xD3\x576\x8D3\xC74D a"; - EXPECT_EQ(PrintPointer(p) + " pointing to L\"'\\\"\\?\\\\\\a\\b\\f" - "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"", - Print(p)); -} -#endif // native wchar_t - -// Tests printing pointers to other char types. - -// signed char*. -TEST(PrintCharPointerTest, SignedChar) { - signed char* p = reinterpret_cast<signed char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const signed char*. -TEST(PrintCharPointerTest, ConstSignedChar) { - signed char* p = reinterpret_cast<signed char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// unsigned char*. -TEST(PrintCharPointerTest, UnsignedChar) { - unsigned char* p = reinterpret_cast<unsigned char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const unsigned char*. -TEST(PrintCharPointerTest, ConstUnsignedChar) { - const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to simple, built-in types. - -// bool*. -TEST(PrintPointerToBuiltInTypeTest, Bool) { - bool* p = reinterpret_cast<bool*>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// void*. -TEST(PrintPointerToBuiltInTypeTest, Void) { - void* p = reinterpret_cast<void*>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// const void*. -TEST(PrintPointerToBuiltInTypeTest, ConstVoid) { - const void* p = reinterpret_cast<const void*>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing pointers to pointers. -TEST(PrintPointerToPointerTest, IntPointerPointer) { - int** p = reinterpret_cast<int**>(0xABCD); - EXPECT_EQ(PrintPointer(p), Print(p)); - p = NULL; - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing (non-member) function pointers. - -void MyFunction(int /* n */) {} - -TEST(PrintPointerTest, NonMemberFunctionPointer) { - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - EXPECT_EQ( - PrintPointer(reinterpret_cast<const void*>( - reinterpret_cast<internal::BiggestInt>(&MyFunction))), - Print(&MyFunction)); - int (*p)(bool) = NULL; // NOLINT - EXPECT_EQ("NULL", Print(p)); -} - -// Tests printing member variable pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. - -struct Foo { - public: - virtual ~Foo() {} - int MyMethod(char x) { return x + 1; } - virtual char MyVirtualMethod(int /* n */) { return 'a'; } - - int value; -}; - -TEST(PrintPointerTest, MemberVariablePointer) { - EXPECT_THAT(Print(&Foo::value), - StartsWith(Print(sizeof(&Foo::value)) + "-byte object ")); - int (Foo::*p) = NULL; // NOLINT - EXPECT_THAT(Print(p), - StartsWith(Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing member function pointers. Although they are called -// pointers, they don't point to a location in the address space. -// Their representation is implementation-defined. Thus they will be -// printed as raw bytes. -TEST(PrintPointerTest, MemberFunctionPointer) { - EXPECT_THAT(Print(&Foo::MyMethod), - StartsWith(Print(sizeof(&Foo::MyMethod)) + "-byte object ")); - EXPECT_THAT(Print(&Foo::MyVirtualMethod), - StartsWith(Print(sizeof((&Foo::MyVirtualMethod))) - + "-byte object ")); - int (Foo::*p)(char) = NULL; // NOLINT - EXPECT_THAT(Print(p), - StartsWith(Print(sizeof(p)) + "-byte object ")); -} - -// Tests printing C arrays. - -// The difference between this and Print() is that it ensures that the -// argument is a reference to an array. -template <typename T, size_t N> -string PrintArrayHelper(T (&a)[N]) { - return Print(a); -} - -// One-dimensional array. -TEST(PrintArrayTest, OneDimensionalArray) { - int a[5] = { 1, 2, 3, 4, 5 }; - EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a)); -} - -// Two-dimensional array. -TEST(PrintArrayTest, TwoDimensionalArray) { - int a[2][5] = { - { 1, 2, 3, 4, 5 }, - { 6, 7, 8, 9, 0 } - }; - EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a)); -} - -// Array of const elements. -TEST(PrintArrayTest, ConstArray) { - const bool a[1] = { false }; - EXPECT_EQ("{ false }", PrintArrayHelper(a)); -} - -// Char array. -TEST(PrintArrayTest, CharArray) { - // Array a contains '\0' in the middle and doesn't end with '\0'. - char a[3] = { 'H', '\0', 'i' }; - EXPECT_EQ("\"H\\0i\"", PrintArrayHelper(a)); -} - -// Const char array. -TEST(PrintArrayTest, ConstCharArray) { - const char a[4] = "\0Hi"; - EXPECT_EQ("\"\\0Hi\\0\"", PrintArrayHelper(a)); -} - -// Array of objects. -TEST(PrintArrayTest, ObjectArray) { - string a[3] = { "Hi", "Hello", "Ni hao" }; - EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a)); -} - -// Array with many elements. -TEST(PrintArrayTest, BigArray) { - int a[100] = { 1, 2, 3 }; - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }", - PrintArrayHelper(a)); -} - -// Tests printing ::string and ::std::string. - -#if GTEST_HAS_GLOBAL_STRING -// ::string. -TEST(PrintStringTest, StringInGlobalNamespace) { - const char s[] = "'\"\?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_STRING - -// ::std::string. -TEST(PrintStringTest, StringInStdNamespace) { - const char s[] = "'\"\?\\\a\b\f\n\0\r\t\v\x7F\xFF a"; - const ::std::string str(s, sizeof(s)); - EXPECT_EQ("\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"", - Print(str)); -} - -// Tests printing ::wstring and ::std::wstring. - -#if GTEST_HAS_GLOBAL_WSTRING -// ::wstring. -TEST(PrintWideStringTest, StringInGlobalNamespace) { - const wchar_t s[] = L"'\"\?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_GLOBAL_WSTRING - -#if GTEST_HAS_STD_WSTRING -// ::std::wstring. -TEST(PrintWideStringTest, StringInStdNamespace) { - const wchar_t s[] = L"'\"\?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a"; - const ::std::wstring str(s, sizeof(s)/sizeof(wchar_t)); - EXPECT_EQ("L\"'\\\"\\?\\\\\\a\\b\\f\\n\\0\\r\\t\\v" - "\\xD3\\x576\\x8D3\\xC74D a\\0\"", - Print(str)); -} -#endif // GTEST_HAS_STD_WSTRING - -// Tests printing types that support generic streaming (i.e. streaming -// to std::basic_ostream<Char, CharTraits> for any valid Char and -// CharTraits types). - -// Tests printing a non-template type that supports generic streaming. - -class AllowsGenericStreaming {}; - -template <typename Char, typename CharTraits> -std::basic_ostream<Char, CharTraits>& operator<<( - std::basic_ostream<Char, CharTraits>& os, - const AllowsGenericStreaming& /* a */) { - return os << "AllowsGenericStreaming"; -} - -TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) { - AllowsGenericStreaming a; - EXPECT_EQ("AllowsGenericStreaming", Print(a)); -} - -// Tests printing a template type that supports generic streaming. - -template <typename T> -class AllowsGenericStreamingTemplate {}; - -template <typename Char, typename CharTraits, typename T> -std::basic_ostream<Char, CharTraits>& operator<<( - std::basic_ostream<Char, CharTraits>& os, - const AllowsGenericStreamingTemplate<T>& /* a */) { - return os << "AllowsGenericStreamingTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TemplateType) { - AllowsGenericStreamingTemplate<int> a; - EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a)); -} - -// Tests printing a type that supports generic streaming and can be -// implicitly converted to another printable type. - -template <typename T> -class AllowsGenericStreamingAndImplicitConversionTemplate { - public: - operator bool() const { return false; } -}; - -template <typename Char, typename CharTraits, typename T> -std::basic_ostream<Char, CharTraits>& operator<<( - std::basic_ostream<Char, CharTraits>& os, - const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) { - return os << "AllowsGenericStreamingAndImplicitConversionTemplate"; -} - -TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) { - AllowsGenericStreamingAndImplicitConversionTemplate<int> a; - EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a)); -} - -// Tests printing STL containers. - -TEST(PrintStlContainerTest, EmptyDeque) { - deque<char> empty; - EXPECT_EQ("{}", Print(empty)); -} - -TEST(PrintStlContainerTest, NonEmptyDeque) { - deque<int> non_empty; - non_empty.push_back(1); - non_empty.push_back(3); - EXPECT_EQ("{ 1, 3 }", Print(non_empty)); -} - -#if GMOCK_HAS_HASH_MAP_ - -TEST(PrintStlContainerTest, OneElementHashMap) { - hash_map<int, char> map1; - map1[1] = 'a'; - EXPECT_EQ("{ (1, 'a' (97)) }", Print(map1)); -} - -TEST(PrintStlContainerTest, HashMultiMap) { - hash_multimap<int, bool> map1; - map1.insert(make_pair(5, true)); - map1.insert(make_pair(5, false)); - - // Elements of hash_multimap can be printed in any order. - const string result = Print(map1); - EXPECT_TRUE(result == "{ (5, true), (5, false) }" || - result == "{ (5, false), (5, true) }") - << " where Print(map1) returns \"" << result << "\"."; -} - -#endif // GMOCK_HAS_HASH_MAP_ - -#if GMOCK_HAS_HASH_SET_ - -TEST(PrintStlContainerTest, HashSet) { - hash_set<string> set1; - set1.insert("hello"); - EXPECT_EQ("{ \"hello\" }", Print(set1)); -} - -TEST(PrintStlContainerTest, HashMultiSet) { - const int kSize = 5; - int a[kSize] = { 1, 1, 2, 5, 1 }; - hash_multiset<int> set1(a, a + kSize); - - // Elements of hash_multiset can be printed in any order. - const string result = Print(set1); - const string expected_pattern = "{ d, d, d, d, d }"; // d means a digit. - - // Verifies the result matches the expected pattern; also extracts - // the numbers in the result. - ASSERT_EQ(expected_pattern.length(), result.length()); - std::vector<int> numbers; - for (size_t i = 0; i != result.length(); i++) { - if (expected_pattern[i] == 'd') { - ASSERT_TRUE(isdigit(result[i]) != 0); - numbers.push_back(result[i] - '0'); - } else { - EXPECT_EQ(expected_pattern[i], result[i]) << " where result is " - << result; - } - } - - // Makes sure the result contains the right numbers. - std::sort(numbers.begin(), numbers.end()); - std::sort(a, a + kSize); - EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin())); -} - -#endif // GMOCK_HAS_HASH_SET_ - -TEST(PrintStlContainerTest, List) { - const char* a[] = { - "hello", - "world" - }; - const list<string> strings(a, a + 2); - EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings)); -} - -TEST(PrintStlContainerTest, Map) { - map<int, bool> map1; - map1[1] = true; - map1[5] = false; - map1[3] = true; - EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1)); -} - -TEST(PrintStlContainerTest, MultiMap) { - multimap<bool, int> map1; - map1.insert(make_pair(true, 0)); - map1.insert(make_pair(true, 1)); - map1.insert(make_pair(false, 2)); - EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1)); -} - -TEST(PrintStlContainerTest, Set) { - const unsigned int a[] = { 3, 0, 5 }; - set<unsigned int> set1(a, a + 3); - EXPECT_EQ("{ 0, 3, 5 }", Print(set1)); -} - -TEST(PrintStlContainerTest, MultiSet) { - const int a[] = { 1, 1, 2, 5, 1 }; - multiset<int> set1(a, a + 5); - EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1)); -} - -TEST(PrintStlContainerTest, Pair) { - pair<const bool, int> p(true, 5); - EXPECT_EQ("(true, 5)", Print(p)); -} - -TEST(PrintStlContainerTest, Vector) { - vector<int> v; - v.push_back(1); - v.push_back(2); - EXPECT_EQ("{ 1, 2 }", Print(v)); -} - -TEST(PrintStlContainerTest, LongSequence) { - const int a[100] = { 1, 2, 3 }; - const vector<int> v(a, a + 100); - EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " - "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }", Print(v)); -} - -TEST(PrintStlContainerTest, NestedContainer) { - const int a1[] = { 1, 2 }; - const int a2[] = { 3, 4, 5 }; - const list<int> l1(a1, a1 + 2); - const list<int> l2(a2, a2 + 3); - - vector<list<int> > v; - v.push_back(l1); - v.push_back(l2); - EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v)); -} - -TEST(PrintStlContainerTest, OneDimensionalNativeArray) { - const int a[3] = { 1, 2, 3 }; - NativeArray<int> b(a, 3, kReference); - EXPECT_EQ("{ 1, 2, 3 }", Print(b)); -} - -TEST(PrintStlContainerTest, TwoDimensionalNativeArray) { - const int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; - NativeArray<int[3]> b(a, 2, kReference); - EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b)); -} - -// Tests printing tuples. - -// Tuples of various arities. -TEST(PrintTupleTest, VariousSizes) { - tuple<> t0; - EXPECT_EQ("()", Print(t0)); - - tuple<int> t1(5); - EXPECT_EQ("(5)", Print(t1)); - - tuple<char, bool> t2('a', true); - EXPECT_EQ("('a' (97), true)", Print(t2)); - - tuple<bool, int, int> t3(false, 2, 3); - EXPECT_EQ("(false, 2, 3)", Print(t3)); - - tuple<bool, int, int, int> t4(false, 2, 3, 4); - EXPECT_EQ("(false, 2, 3, 4)", Print(t4)); - - tuple<bool, int, int, int, bool> t5(false, 2, 3, 4, true); - EXPECT_EQ("(false, 2, 3, 4, true)", Print(t5)); - - tuple<bool, int, int, int, bool, int> t6(false, 2, 3, 4, true, 6); - EXPECT_EQ("(false, 2, 3, 4, true, 6)", Print(t6)); - - tuple<bool, int, int, int, bool, int, int> t7(false, 2, 3, 4, true, 6, 7); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7)", Print(t7)); - - tuple<bool, int, int, int, bool, int, int, bool> t8( - false, 2, 3, 4, true, 6, 7, true); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true)", Print(t8)); - - tuple<bool, int, int, int, bool, int, int, bool, int> t9( - false, 2, 3, 4, true, 6, 7, true, 9); - EXPECT_EQ("(false, 2, 3, 4, true, 6, 7, true, 9)", Print(t9)); - - const char* const str = "8"; - tuple<bool, char, short, testing::internal::Int32, // NOLINT - testing::internal::Int64, float, double, const char*, void*, string> - t10(false, 'a', 3, 4, 5, 1.5F, -2.5, str, NULL, "10"); - EXPECT_EQ("(false, 'a' (97), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) + - " pointing to \"8\", NULL, \"10\")", - Print(t10)); -} - -// Nested tuples. -TEST(PrintTupleTest, NestedTuple) { - tuple<tuple<int, bool>, char> nested(make_tuple(5, true), 'a'); - EXPECT_EQ("((5, true), 'a' (97))", Print(nested)); -} - -// Tests printing user-defined unprintable types. - -// Unprintable types in the global namespace. -TEST(PrintUnprintableTypeTest, InGlobalNamespace) { - EXPECT_EQ("1-byte object <00>", - Print(UnprintableTemplateInGlobal<bool>())); -} - -// Unprintable types in a user namespace. -TEST(PrintUnprintableTypeTest, InUserNamespace) { - EXPECT_EQ("16-byte object <EF12 0000 34AB 0000 0000 0000 0000 0000>", - Print(::foo::UnprintableInFoo())); -} - -// Unprintable types are that too big to be printed completely. - -struct Big { - Big() { memset(array, 0, sizeof(array)); } - char array[257]; -}; - -TEST(PrintUnpritableTypeTest, BigObject) { - EXPECT_EQ("257-byte object <0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 ... 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 " - "0000 0000 0000 0000 0000 0000 0000 0000 00>", - Print(Big())); -} - -// Tests printing user-defined streamable types. - -// Streamable types in the global namespace. -TEST(PrintStreamableTypeTest, InGlobalNamespace) { - EXPECT_EQ("StreamableInGlobal", - Print(StreamableInGlobal())); -} - -// Printable template types in a user namespace. -TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) { - EXPECT_EQ("StreamableTemplateInFoo: 0", - Print(::foo::StreamableTemplateInFoo<int>())); -} - -// Tests printing user-defined types that have a PrintTo() function. -TEST(PrintPrintableTypeTest, InUserNamespace) { - EXPECT_EQ("PrintableViaPrintTo: 0", - Print(::foo::PrintableViaPrintTo())); -} - -// Tests printing user-defined class template that have a PrintTo() function. -TEST(PrintPrintableTypeTest, TemplateInUserNamespace) { - EXPECT_EQ("PrintableViaPrintToTemplate: 5", - Print(::foo::PrintableViaPrintToTemplate<int>(5))); -} - -#if GMOCK_HAS_PROTOBUF_ - -// Tests printing a protocol message. -TEST(PrintProtocolMessageTest, PrintsShortDebugString) { - testing::internal::TestMessage msg; - msg.set_member("yes"); - EXPECT_EQ("<member:\"yes\">", Print(msg)); -} - -// Tests printing a short proto2 message. -TEST(PrintProto2MessageTest, PrintsShortDebugStringWhenItIsShort) { - testing::internal::FooMessage msg; - msg.set_int_field(2); - msg.set_string_field("hello"); - EXPECT_PRED2(RE::FullMatch, Print(msg), - "<int_field:\\s*2\\s+string_field:\\s*\"hello\">"); -} - -// Tests printing a long proto2 message. -TEST(PrintProto2MessageTest, PrintsDebugStringWhenItIsLong) { - testing::internal::FooMessage msg; - msg.set_int_field(2); - msg.set_string_field("hello"); - msg.add_names("peter"); - msg.add_names("paul"); - msg.add_names("mary"); - EXPECT_PRED2(RE::FullMatch, Print(msg), - "<\n" - "int_field:\\s*2\n" - "string_field:\\s*\"hello\"\n" - "names:\\s*\"peter\"\n" - "names:\\s*\"paul\"\n" - "names:\\s*\"mary\"\n" - ">"); -} - -#endif // GMOCK_HAS_PROTOBUF_ - -// Tests that the universal printer prints both the address and the -// value of a reference. -TEST(PrintReferenceTest, PrintsAddressAndValue) { - int n = 5; - EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n)); - - int a[2][3] = { - { 0, 1, 2 }, - { 3, 4, 5 } - }; - EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }", - PrintByRef(a)); - - const ::foo::UnprintableInFoo x; - EXPECT_EQ("@" + PrintPointer(&x) + " 16-byte object " - "<EF12 0000 34AB 0000 0000 0000 0000 0000>", - PrintByRef(x)); -} - -// Tests that the universal printer prints a function pointer passed by -// reference. -TEST(PrintReferenceTest, HandlesFunctionPointer) { - void (*fp)(int n) = &MyFunction; - const string fp_pointer_string = - PrintPointer(reinterpret_cast<const void*>(&fp)); - // We cannot directly cast &MyFunction to const void* because the - // standard disallows casting between pointers to functions and - // pointers to objects, and some compilers (e.g. GCC 3.4) enforce - // this limitation. - const string fp_string = PrintPointer(reinterpret_cast<const void*>( - reinterpret_cast<internal::BiggestInt>(fp))); - EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, - PrintByRef(fp)); -} - -// Tests that the universal printer prints a member function pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberFunctionPointer) { - int (Foo::*p)(char ch) = &Foo::MyMethod; - EXPECT_THAT(PrintByRef(p), - StartsWith("@" + PrintPointer(reinterpret_cast<const void*>(&p)) - + " " + Print(sizeof(p)) + "-byte object ")); - - char (Foo::*p2)(int n) = &Foo::MyVirtualMethod; - EXPECT_THAT(PrintByRef(p2), - StartsWith("@" + PrintPointer(reinterpret_cast<const void*>(&p2)) - + " " + Print(sizeof(p2)) + "-byte object ")); -} - -// Tests that the universal printer prints a member variable pointer -// passed by reference. -TEST(PrintReferenceTest, HandlesMemberVariablePointer) { - int (Foo::*p) = &Foo::value; // NOLINT - EXPECT_THAT(PrintByRef(p), - StartsWith("@" + PrintPointer(&p) - + " " + Print(sizeof(p)) + "-byte object ")); -} - -TEST(PrintToStringTest, WorksForScalar) { - EXPECT_EQ("123", PrintToString(123)); -} - -TEST(PrintToStringTest, WorksForPointerToConstChar) { - const char* p = "hello"; - EXPECT_EQ("\"hello\"", PrintToString(p)); -} - -TEST(PrintToStringTest, WorksForPointerToNonConstChar) { - char s[] = "hello"; - char* p = s; - EXPECT_EQ("\"hello\"", PrintToString(p)); -} - -TEST(PrintToStringTest, WorksForArray) { - int n[3] = { 1, 2, 3 }; - EXPECT_EQ("{ 1, 2, 3 }", PrintToString(n)); -} - -TEST(UniversalTersePrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalTersePrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalTersePrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalTersePrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalTersePrint(s1, &ss1); - EXPECT_EQ("\"abc\"", ss1.str()); - - char* s2 = const_cast<char*>(s1); - ::std::stringstream ss2; - UniversalTersePrint(s2, &ss2); - EXPECT_EQ("\"abc\"", ss2.str()); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalTersePrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - -TEST(UniversalPrintTest, WorksForNonReference) { - ::std::stringstream ss; - UniversalPrint(123, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForReference) { - const int& n = 123; - ::std::stringstream ss; - UniversalPrint(n, &ss); - EXPECT_EQ("123", ss.str()); -} - -TEST(UniversalPrintTest, WorksForCString) { - const char* s1 = "abc"; - ::std::stringstream ss1; - UniversalPrint(s1, &ss1); - EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", string(ss1.str())); - - char* s2 = const_cast<char*>(s1); - ::std::stringstream ss2; - UniversalPrint(s2, &ss2); - EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", string(ss2.str())); - - const char* s3 = NULL; - ::std::stringstream ss3; - UniversalPrint(s3, &ss3); - EXPECT_EQ("NULL", ss3.str()); -} - - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsEmptyTuple) { - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings(make_tuple()), - ElementsAre()); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsOneTuple) { - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings(make_tuple(1)), - ElementsAre("1")); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTwoTuple) { - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings(make_tuple(1, 'a')), - ElementsAre("1", "'a' (97)")); -} - -TEST(UniversalTersePrintTupleFieldsToStringsTest, PrintsTersely) { - const int n = 1; - EXPECT_THAT(UniversalTersePrintTupleFieldsToStrings( - tuple<const int&, const char*>(n, "a")), - ElementsAre("1", "\"a\"")); -} - -} // namespace gmock_printers_test -} // namespace testing diff --git a/testing/gmock/test/gmock-spec-builders_test.cc b/testing/gmock/test/gmock-spec-builders_test.cc index e5fc2ec..ff30f02 100644 --- a/testing/gmock/test/gmock-spec-builders_test.cc +++ b/testing/gmock/test/gmock-spec-builders_test.cc @@ -1783,6 +1783,25 @@ class MockC { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC); }; +class VerboseFlagPreservingFixture : public testing::Test { + protected: + // The code needs to work when both ::string and ::std::string are defined + // and the flag is implemented as a testing::internal::String. In this + // case, without the call to c_str(), the compiler will complain that it + // cannot figure out what overload of string constructor to use. + // TODO(vladl@google.com): Use internal::string instead of String for + // string flags in Google Test. + VerboseFlagPreservingFixture() + : saved_verbose_flag_(GMOCK_FLAG(verbose).c_str()) {} + + ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; } + + private: + const string saved_verbose_flag_; + + GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture); +}; + #if GTEST_HAS_STREAM_REDIRECTION_ // Tests that an uninteresting mock function call generates a warning @@ -1842,7 +1861,7 @@ TEST(FunctionCallMessageTest, UninterestingCallPrintsArgumentsAndReturnValue) { // Tests how the --gmock_verbose flag affects Google Mock's output. -class GMockVerboseFlagTest : public testing::Test { +class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { public: // Verifies that the given Google Mock output is correct. (When // should_print is true, the output should match the given regex and @@ -1982,22 +2001,9 @@ class LogTestHelper { GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper); }; -class GMockLogTest : public ::testing::Test { +class GMockLogTest : public VerboseFlagPreservingFixture { protected: - virtual void SetUp() { - // The code needs to work when both ::string and ::std::string are - // defined and the flag is implemented as a - // testing::internal::String. In this case, without the call to - // c_str(), the compiler will complain that it cannot figure out - // whether the String flag should be converted to a ::string or an - // ::std::string before being assigned to original_verbose_. - original_verbose_ = GMOCK_FLAG(verbose).c_str(); - } - - virtual void TearDown() { GMOCK_FLAG(verbose) = original_verbose_; } - LogTestHelper helper_; - string original_verbose_; }; TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { @@ -2358,9 +2364,23 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { // action or as a default action without causing a dead lock. It // verifies that the action is not performed inside the critical // section. +TEST(SynchronizationTest, CanCallMockMethodInAction) { + MockA a; + MockC c; + ON_CALL(a, DoA(_)) + .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c, + &MockC::NonVoidMethod))); + EXPECT_CALL(a, DoA(1)); + EXPECT_CALL(a, DoA(1)) + .WillOnce(Invoke(&a, &MockA::DoA)) + .RetiresOnSaturation(); + EXPECT_CALL(c, NonVoidMethod()); -void Helper(MockC* c) { - c->NonVoidMethod(); + a.DoA(1); + // This will match the second EXPECT_CALL() and trigger another a.DoA(1), + // which will in turn match the first EXPECT_CALL() and trigger a call to + // c.NonVoidMethod() that was specified by the ON_CALL() since the first + // EXPECT_CALL() did not specify an action. } } // namespace diff --git a/testing/gmock/test/gmock_all_test.cc b/testing/gmock/test/gmock_all_test.cc index 7361259..691aac8 100644 --- a/testing/gmock/test/gmock_all_test.cc +++ b/testing/gmock/test/gmock_all_test.cc @@ -44,6 +44,5 @@ #include "test/gmock-more-actions_test.cc" #include "test/gmock-nice-strict_test.cc" #include "test/gmock-port_test.cc" -#include "test/gmock-printers_test.cc" #include "test/gmock-spec-builders_test.cc" #include "test/gmock_test.cc" diff --git a/testing/gmock/test/gmock_output_test.py b/testing/gmock/test/gmock_output_test.py index 614a58f..eced8a8 100755 --- a/testing/gmock/test/gmock_output_test.py +++ b/testing/gmock/test/gmock_output_test.py @@ -32,7 +32,7 @@ """Tests the text output of Google C++ Mocking Framework. SYNOPSIS - gmock_output_test.py --gmock_build_dir=BUILD/DIR --gengolden + gmock_output_test.py --build_dir=BUILD/DIR --gengolden # where BUILD/DIR contains the built gmock_output_test_ file. gmock_output_test.py --gengolden gmock_output_test.py diff --git a/testing/gmock/test/gmock_output_test_golden.txt b/testing/gmock/test/gmock_output_test_golden.txt index 382dc8c..a7ff563 100644 --- a/testing/gmock/test/gmock_output_test_golden.txt +++ b/testing/gmock/test/gmock_output_test_golden.txt @@ -151,7 +151,7 @@ FILE:#: pre-requisite #1 [ RUN ] GMockOutputTest.UnsatisfiedWith FILE:#: Failure Actual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))... - Expected args: are a pair (x, y) where x >= y + Expected args: are a pair where the first >= the second Expected: to be called once Actual: never called - unsatisfied and active [ FAILED ] GMockOutputTest.UnsatisfiedWith @@ -190,7 +190,7 @@ Unexpected mock function call - returning default value. Google Mock tried the following 1 expectation, but it didn't match: FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))... - Expected args: are a pair (x, y) where x >= y + Expected args: are a pair where the first >= the second Actual: don't match Expected: to be called once Actual: never called - unsatisfied and active @@ -206,7 +206,7 @@ Google Mock tried the following 1 expectation, but it didn't match: FILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))... Expected arg #0: is >= 2 Actual: 1 - Expected args: are a pair (x, y) where x >= y + Expected args: are a pair where the first >= the second Actual: don't match Expected: to be called once Actual: never called - unsatisfied and active diff --git a/testing/gmock/test/gmock_test_utils.py b/testing/gmock/test/gmock_test_utils.py index fa896a4..ac3d67a 100755 --- a/testing/gmock/test/gmock_test_utils.py +++ b/testing/gmock/test/gmock_test_utils.py @@ -51,62 +51,10 @@ sys.path.append(GTEST_TESTS_UTIL_DIR) import gtest_test_utils # pylint: disable-msg=C6204 -# Initially maps a flag to its default value. After -# _ParseAndStripGMockFlags() is called, maps a flag to its actual -# value. -_flag_map = {'gmock_source_dir': os.path.dirname(sys.argv[0]), - 'gmock_build_dir': os.path.dirname(sys.argv[0])} -_gmock_flags_are_parsed = False - - -def _ParseAndStripGMockFlags(argv): - """Parses and strips Google Test flags from argv. This is idempotent.""" - - global _gmock_flags_are_parsed - if _gmock_flags_are_parsed: - return - - _gmock_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 --gmock_* 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 - # _ParseAndStripGMockFlags() here to make sure the --gmock_* flags - # are parsed. - _ParseAndStripGMockFlags(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('gmock_source_dir')) - - -def GetBuildDir(): - """Returns the absolute path of the directory where the test binaries are.""" - - return os.path.abspath(GetFlag('gmock_build_dir')) + return gtest_test_utils.GetSourceDir() def GetTestExecutablePath(executable_name): @@ -122,7 +70,7 @@ def GetTestExecutablePath(executable_name): The absolute path of the test binary. """ - return gtest_test_utils.GetTestExecutablePath(executable_name, GetBuildDir()) + return gtest_test_utils.GetTestExecutablePath(executable_name) def GetExitStatus(exit_code): @@ -160,8 +108,4 @@ TestCase = gtest_test_utils.TestCase def Main(): """Runs the unit test.""" - # We must call _ParseAndStripGMockFlags() before calling - # gtest_test_utils.Main(). Otherwise unittest.main it calls will be - # confused by the --gmock_* flags. - _ParseAndStripGMockFlags(sys.argv) gtest_test_utils.Main() diff --git a/testing/gmockmain.target.mk b/testing/gmockmain.target.mk index b406484..229e244 100644 --- a/testing/gmockmain.target.mk +++ b/testing/gmockmain.target.mk @@ -18,6 +18,7 @@ CFLAGS_Debug := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O0 \ -g @@ -50,6 +51,7 @@ CFLAGS_Release := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O2 \ -fno-ident \ @@ -94,11 +96,12 @@ $(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD # End of this set of suffix rules ### Rules for final target. LDFLAGS_Debug := -pthread \ - -Wl,-z,noexecstack \ - -rdynamic + -Wl,-z,noexecstack LDFLAGS_Release := -pthread \ -Wl,-z,noexecstack \ + -Wl,-O1 \ + -Wl,--as-needed \ -Wl,--gc-sections LIBS := diff --git a/testing/gtest.gyp b/testing/gtest.gyp index c8f64e5..da95f42 100644 --- a/testing/gtest.gyp +++ b/testing/gtest.gyp @@ -9,10 +9,10 @@ 'type': '<(library)', 'msvs_guid': 'BFE8E2A7-3B3B-43B0-A994-3058B852DB8B', 'sources': [ - # Sources based on files in r267 of gmock. 'gtest/include/gtest/gtest-death-test.h', 'gtest/include/gtest/gtest-message.h', 'gtest/include/gtest/gtest-param-test.h', + 'gtest/include/gtest/gtest-printers.h', 'gtest/include/gtest/gtest-spi.h', 'gtest/include/gtest/gtest-test-part.h', 'gtest/include/gtest/gtest-typed-test.h', @@ -34,6 +34,7 @@ 'gtest/src/gtest-filepath.cc', 'gtest/src/gtest-internal-inl.h', 'gtest/src/gtest-port.cc', + 'gtest/src/gtest-printers.cc', 'gtest/src/gtest-test-part.cc', 'gtest/src/gtest-typed-test.cc', 'gtest/src/gtest.cc', @@ -51,6 +52,8 @@ 'conditions': [ ['OS == "mac"', { 'sources': [ + 'gtest_mac.h', + 'gtest_mac.mm', 'platform_test_mac.mm' ], 'link_settings': { @@ -76,6 +79,20 @@ ], }, }], + ['clang==1', { + # We want gtest features that use tr1::tuple, but clang currently + # doesn't support the variadic templates used by libstdc++'s + # implementation. gtest supports this scenario by providing its + # own implementation but we must opt in to it. + 'defines': [ + 'GTEST_USE_OWN_TR1_TUPLE=1', + ], + 'direct_dependent_settings': { + 'defines': [ + 'GTEST_USE_OWN_TR1_TUPLE=1', + ], + }, + }], ], 'direct_dependent_settings': { 'defines': [ diff --git a/testing/gtest.target.mk b/testing/gtest.target.mk index 07503b6..1db9611 100644 --- a/testing/gtest.target.mk +++ b/testing/gtest.target.mk @@ -17,6 +17,7 @@ CFLAGS_Debug := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O0 \ -g @@ -48,6 +49,7 @@ CFLAGS_Release := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O2 \ -fno-ident \ @@ -68,6 +70,7 @@ INCS_Release := -Itesting/gtest \ OBJS := $(obj).target/$(TARGET)/testing/gtest/src/gtest-death-test.o \ $(obj).target/$(TARGET)/testing/gtest/src/gtest-filepath.o \ $(obj).target/$(TARGET)/testing/gtest/src/gtest-port.o \ + $(obj).target/$(TARGET)/testing/gtest/src/gtest-printers.o \ $(obj).target/$(TARGET)/testing/gtest/src/gtest-test-part.o \ $(obj).target/$(TARGET)/testing/gtest/src/gtest-typed-test.o \ $(obj).target/$(TARGET)/testing/gtest/src/gtest.o \ @@ -98,11 +101,12 @@ $(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD # End of this set of suffix rules ### Rules for final target. LDFLAGS_Debug := -pthread \ - -Wl,-z,noexecstack \ - -rdynamic + -Wl,-z,noexecstack LDFLAGS_Release := -pthread \ -Wl,-z,noexecstack \ + -Wl,-O1 \ + -Wl,--as-needed \ -Wl,--gc-sections LIBS := diff --git a/testing/gtest/CMakeLists.txt b/testing/gtest/CMakeLists.txt index 4c80bde..4a978a1 100644 --- a/testing/gtest/CMakeLists.txt +++ b/testing/gtest/CMakeLists.txt @@ -8,12 +8,25 @@ # ctest. You can select which tests to run using 'ctest -R regex'. # For more options, run 'ctest --help'. -# For hermetic builds, we may need to tell CMake to use compiler in a -# specific location. -if (gtest_compiler) - include(CMakeForceCompiler) - cmake_force_c_compiler("${gtest_compiler}" "") - cmake_force_cxx_compiler("${gtest_compiler}" "") +# 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) + +include(cmake/hermetic_build.cmake OPTIONAL) + +if (COMMAND pre_project_set_up_hermetic_build) + pre_project_set_up_hermetic_build() endif() ######################################################################## @@ -27,122 +40,35 @@ endif() # ${gtest_BINARY_DIR}. # Language "C" is required for find_package(Threads). project(gtest CXX C) -cmake_minimum_required(VERSION 2.6.4) - -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) - # In hermetic build environments, tests may not have access to MS runtime - # DLLs, so this replaces /MD (CRT libraries in DLLs) with /MT (static CRT - # libraries). - string(REPLACE "/MD" "-MT" ${flag_var} "${${flag_var}}") - # 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() +cmake_minimum_required(VERSION 2.6.2) + +if (COMMAND set_up_hermetic_build) + set_up_hermetic_build() endif() -# Where gtest's .h files can be found. +# Defines functions and variables used by Google Test. +include(cmake/internal_utils.cmake) + +fix_default_settings() # Defined in internal_utils.cmake. + +# Where Google Test's .h files can be found. include_directories( ${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR}) -# Where the gtest libraries can be found. -link_directories( - ${gtest_BINARY_DIR}/src) - -# Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT. -find_package(Threads) - -# Defines the compiler/linker flags used to build gtest. You can -# tweak these definitions to suit your need. A variable's value is -# empty before it's explicitly assigned to. - -if (MSVC) - # Newlines inside flags variables break CMake's NMake generator. - set(cxx_base_flags "-GS -W4 -WX -wd4275 -nologo -J -Zi") - 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") -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") - 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") -endif() - -if (CMAKE_USE_PTHREADS_INIT) # The pthreads library is available. - set(cxx_base_flags "${cxx_base_flags} -DGTEST_HAS_PTHREAD=1") -endif() - -# 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}") +# Where Google Test's libraries can be found. +link_directories(${gtest_BINARY_DIR}/src) ######################################################################## # # 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 (CMAKE_USE_PTHREADS_INIT) - target_link_libraries(${name} ${CMAKE_THREAD_LIBS_INIT}) - endif() -endfunction() - -function(cxx_static_library name cxx_flags) - cxx_library_with_type(${name} STATIC "${cxx_flags}" ${ARGN}) -endfunction() - -function(cxx_shared_library name cxx_flags) - cxx_library_with_type(${name} SHARED "${cxx_flags}" ${ARGN}) -endfunction() - -function(cxx_library name cxx_flags) - # TODO(vladl@google.com): Make static/shared a user option. - cxx_static_library(${name} "${cxx_flags}" ${ARGN}) -endfunction() - -# Static versions of 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_static_library(gtest "${cxx_strict}" src/gtest-all.cc) -cxx_static_library(gtest_main "${cxx_strict}" src/gtest_main.cc) + +# 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) ######################################################################## @@ -150,36 +76,10 @@ target_link_libraries(gtest_main gtest) # Samples on how to link user tests with gtest or gtest_main. # # They are not built by default. To build them, set the -# build_gtest_samples option to ON. You can do it by running ccmake +# gtest_build_samples option to ON. You can do it by running ccmake # or specifying the -Dbuild_gtest_samples=ON flag when running cmake. -option(build_gtest_samples "Build gtest's sample programs." OFF) - -# cxx_executable_with_flags(name cxx_flags lib srcs...) -# -# creates a named C++ executable that depends on the given library and -# is built from the given source files with the given compiler flags. -function(cxx_executable_with_flags name cxx_flags lib) - add_executable(${name} ${ARGN}) - if (cxx_flags) - set_target_properties(${name} - PROPERTIES - COMPILE_FLAGS "${cxx_flags}") - endif() - target_link_libraries(${name} ${lib}) -endfunction() - -# cxx_executable(name dir lib srcs...) -# -# creates a named target that depends on the given lib and is built -# from the given source files. dir/name.cc is implicitly included in -# the source file list. -function(cxx_executable name dir lib) - cxx_executable_with_flags( - ${name} "${cxx_default}" ${lib} "${dir}/${name}.cc" ${ARGN}) -endfunction() - -if (build_gtest_samples) +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) @@ -199,52 +99,18 @@ endif() # You can skip this section if you aren't interested in testing # Google Test itself. # -# Most of the tests are not built by default. To build them, set the -# build_all_gtest_tests option to ON. You can do it by running ccmake -# or specifying the -Dbuild_all_gtest_tests=ON flag when running cmake. - -option(build_all_gtest_tests "Build all of gtest's own tests." OFF) - -# This must be set in the root directory for the tests to be run by -# 'make test' or ctest. -enable_testing() +# 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. -# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE. -find_package(PythonInterp) +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. + ############################################################ + # C++ tests built with standard compiler flags. -# 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) - add_executable(${name} ${ARGN}) - set_target_properties(${name} - PROPERTIES - COMPILE_FLAGS "${cxx_flags}") - # 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() - 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() - -cxx_test(gtest_unittest gtest_main) - -if (build_all_gtest_tests) cxx_test(gtest-death-test_test gtest_main) cxx_test(gtest_environment_test gtest) cxx_test(gtest-filepath_test gtest_main) @@ -258,6 +124,7 @@ if (build_all_gtest_tests) test/gtest-param-test2_test.cc) cxx_test(gtest-port_test gtest_main) cxx_test(gtest_pred_impl_unittest gtest_main) + cxx_test(gtest-printers_test gtest_main) cxx_test(gtest_prod_test gtest_main test/production.cc) cxx_test(gtest_repeat_test gtest) @@ -267,13 +134,12 @@ if (build_all_gtest_tests) 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) -endif() -############################################################ -# C++ tests built with non-standard compiler flags. + ############################################################ + # C++ tests built with non-standard compiler flags. -if (build_all_gtest_tests) cxx_library(gtest_no_exception "${cxx_no_exception}" src/gtest-all.cc) cxx_library(gtest_main_no_rtti "${cxx_no_rtti}" @@ -282,26 +148,16 @@ if (build_all_gtest_tests) cxx_test_with_flags(gtest_no_rtti_unittest "${cxx_no_rtti}" gtest_main_no_rtti test/gtest_unittest.cc) - set(cxx_use_shared_gtest "${cxx_default} -DGTEST_LINKED_AS_SHARED_LIBRARY=1") - set(cxx_build_shared_gtest "${cxx_default} -DGTEST_CREATE_SHARED_LIBRARY=1") - if (MSVC) - # Disables the "class 'X' needs to have dll-interface to be used - # by clients of class 'Y'" warning. This particularly concerns generic - # classes like vector that MS doesn't mark as exported. - set(cxx_use_shared_gtest "${cxx_use_shared_gtest} -wd4251") - set(cxx_build_shared_gtest "${cxx_build_shared_gtest} -wd4251") - endif() - - cxx_shared_library(gtest_dll "${cxx_build_shared_gtest}" - src/gtest-all.cc) + cxx_shared_library(gtest_dll "${cxx_default}" + src/gtest-all.cc src/gtest_main.cc) - # TODO(vladl): This and the next tests may not run in the hermetic - # environment on Windows. Re-evaluate and possibly make them - # platform-conditional after implementing hermetic builds. - cxx_executable_with_flags(gtest_dll_test_ "${cxx_use_shared_gtest}" + 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 AND (MSVC_VERSION EQUAL 1600))) + if (NOT MSVC OR NOT MSVC_VERSION EQUAL 1600) # The C++ Standard specifies tuple_element<int, class>. # Yet MSVC 10's <utility> declares tuple_element<size_t, class>. # That declaration conflicts with our own standard-conforming @@ -318,28 +174,9 @@ if (build_all_gtest_tests) test/gtest-param-test_test.cc test/gtest-param-test2_test.cc) endif() -endif() - -############################################################ -# Python tests. - -# 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) - if (PYTHONINTERP_FOUND) - # ${gtest_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. - add_test(${name} - ${PYTHON_EXECUTABLE} ${gtest_SOURCE_DIR}/test/${name}.py - --gtest_build_dir=${gtest_BINARY_DIR}/\${CTEST_CONFIGURATION_TYPE}) - endif() -endfunction() + ############################################################ + # Python tests. -if (build_all_gtest_tests) cxx_executable(gtest_break_on_failure_unittest_ test gtest) py_test(gtest_break_on_failure_unittest) diff --git a/testing/gtest/Makefile.am b/testing/gtest/Makefile.am index 2ac14ca..c661db0 100644 --- a/testing/gtest/Makefile.am +++ b/testing/gtest/Makefile.am @@ -1,6 +1,6 @@ # Automake file -# TODO(chandlerc@google.com): automate the generation of *.h from *.h.pump. +ACLOCAL_AMFLAGS = -I m4 # Nonstandard package files for distribution EXTRA_DIST = \ @@ -16,16 +16,20 @@ EXTRA_DIST = \ scripts/pump.py \ scripts/test/Makefile -# gtest source files that we don't compile directly. -EXTRA_DIST += \ +# gtest source files that we don't compile directly. They are +# #included by gtest-all.cc. +GTEST_SRC = \ src/gtest.cc \ 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 +EXTRA_DIST += $(GTEST_SRC) + # Sample files that we don't compile. EXTRA_DIST += \ samples/prime_tables.h \ @@ -51,6 +55,7 @@ EXTRA_DIST += \ test/gtest-param-test2_test.cc \ test/gtest-param-test_test.h \ test/gtest-port_test.cc \ + test/gtest-printers_test.cc \ test/gtest_pred_impl_unittest.cc \ test/gtest_prod_test.cc \ test/production.cc \ @@ -154,11 +159,6 @@ EXTRA_DIST += \ codegear/gtest_unittest.cbproj \ codegear/gtest.groupproj -# TODO(wan@google.com): integrate scripts/gen_gtest_pred_impl.py into -# the build system such that a user can specify the maximum predicate -# arity here and have the script automatically generate the -# corresponding .h and .cc files. - # Scripts and utilities bin_SCRIPTS = scripts/gtest-config CLEANFILES = $(bin_SCRIPTS) @@ -190,6 +190,7 @@ pkginclude_HEADERS = include/gtest/gtest.h \ include/gtest/gtest-message.h \ include/gtest/gtest-param-test.h \ include/gtest/gtest_pred_impl.h \ + include/gtest/gtest-printers.h \ include/gtest/gtest_prod.h \ include/gtest/gtest-spi.h \ include/gtest/gtest-test-part.h \ @@ -254,35 +255,35 @@ test_gtest_all_test_SOURCES = test/gtest_all_test.cc test_gtest_all_test_LDADD = lib/libgtest_main.la # Tests that fused gtest files compile and work. -TESTS += test/gtest_fused_test -check_PROGRAMS += test/gtest_fused_test -test_gtest_fused_test_SOURCES = fused-src/gtest/gtest-all.cc \ - fused-src/gtest/gtest_main.cc \ - fused-src/gtest/gtest.h \ +FUSED_GTEST_SRC = \ + fused-src/gtest/gtest-all.cc \ + fused-src/gtest/gtest_main.cc \ + fused-src/gtest/gtest.h + +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_gtest_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src" +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. -$(srcdir)/fused-src/gtest/gtest-all.cc: fused-gtest-internal - -$(srcdir)/fused-src/gtest/gtest.h: fused-gtest-internal +$(test_fused_gtest_test_SOURCES): fused-gtest -fused-gtest-internal: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \ - $(lib_libgtest_la_SOURCES) \ - scripts/fuse_gtest_files.py - mkdir -p "$(srcdir)/fused-src/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" - -$(srcdir)/fused-src/gtest/gtest_main.cc: src/gtest_main.cc - mkdir -p "$(srcdir)/fused-src/gtest" - chmod -R u+w "$(srcdir)/fused-src" - cp -f "$(srcdir)/src/gtest_main.cc" "$(srcdir)/fused-src/gtest" + cp -f "$(srcdir)/src/gtest_main.cc" "$(srcdir)/fused-src/gtest/" maintainer-clean-local: - chmod -R u+w "$(srcdir)/fused-src" - rm -rf "$(srcdir)/fused-src/gtest" + rm -rf "$(srcdir)/fused-src" + +# Death tests may produce core dumps in the build directory. In case +# this happens, clean them to keep distcleancheck happy. +CLEANFILES += core diff --git a/testing/gtest/README b/testing/gtest/README index 5205303..792abf3 100644 --- a/testing/gtest/README +++ b/testing/gtest/README @@ -1,273 +1,395 @@ Google C++ Testing Framework ============================ + http://code.google.com/p/googletest/ Overview -------- -Google's framework for writing C++ tests on a variety of platforms (Linux, Mac -OS X, Windows, Windows CE, Symbian, and etc). Based on the xUnit architecture. -Supports automatic test discovery, a rich set of assertions, user-defined -assertions, death tests, fatal and non-fatal failures, various options for -running the tests, and XML test report generation. - -Please see the project page above for more information as well as mailing lists -for questions, discussions, and development. There is also an IRC channel on -OFTC (irc.oftc.net) #gtest available. Please join us! - -Requirements ------------- + +Google's framework for writing C++ tests on a variety of platforms +(Linux, Mac OS X, Windows, Windows CE, Symbian, etc). Based on the +xUnit architecture. Supports automatic test discovery, a rich set of +assertions, user-defined assertions, death tests, fatal and non-fatal +failures, various options for running the tests, and XML test report +generation. + +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! + +Requirements for End Users +-------------------------- + Google Test is designed to have fairly minimal requirements to build -and use with your projects, but there are some. Currently, we support -building Google Test on Linux, Windows, Mac OS X, and Cygwin. We will -also make our best effort to support other platforms (e.g. Solaris and -IBM z/OS). However, since core members of the Google Test project -have no access to them, Google Test may have outstanding issues on -these platforms. If you notice any problems on your platform, please -notify googletestframework@googlegroups.com (patches for fixing them -are even more welcome!). +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 +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" + * GNU-compatible Make or gmake * POSIX-standard shell * POSIX(-2) Regular Expressions (regex.h) - * A C++98 standards compliant compiler - -Furthermore, if you are building Google Test from a VCS Checkout (also -described below), there are further requirements: - * Automake version 1.9 or newer - * Autoconf version 2.59 or newer - * Libtool / Libtoolize - * Python version 2.4 or newer + * A C++98-standard-compliant compiler ### Windows Requirements ### - * Microsoft Visual Studio 7.1 or newer + + * Microsoft Visual C++ 7.1 or newer ### Cygwin Requirements ### + * Cygwin 1.5.25-14 or newer ### Mac OS X Requirements ### + * Mac OS X 10.4 Tiger or newer * Developer Tools Installed - * Optional: Xcode 2.5 or later for univeral-binary framework; see note below. + +Also, you'll need CMake 2.6.4 or higher if you want to build the +samples using the provided CMake script, regardless of the platform. + +Requirements for Contributors +----------------------------- + +We welcome patches. If you plan to contribute a patch, you need to +build Google Test and its own tests from an SVN checkout (described +below), which has further requirements: + + * Python version 2.3 or newer (for running some of the tests and + re-generating certain source files from templates) + * CMake 2.6.4 or newer Getting the Source ------------------ -There are two primary ways of getting Google Test's source code: you can -download a source release in your preferred archive format, or directly check -out the source from a Version Control System (VCS, we use Google Code's -Subversion hosting). The VCS checkout requires a few extra steps and some extra -software packages on your system, but lets you track development, and make -patches to contribute much more easily, so we highly encourage it. - -### VCS Checkout: ### -The first step is to select whether you want to check out the main line of -development on Google Test, or one of the released branches. The former will be -much more active and have the latest features, but the latter provides much -more stability and predictability. Choose whichever fits your needs best, and -proceed with the following Subversion commands: + +There are two primary ways of getting Google Test's source code: you +can download a stable source release in your preferred archive format, +or directly check out the source from our Subversion (SVN) repositary. +The SVN checkout requires a few extra steps and some extra software +packages on your system, but lets you track the latest development and +make patches much more easily, so we highly encourage it. + +### Source Package ### + +Google Test is released in versioned source packages which can be +downloaded from the download page [1]. Several different archive +formats are provided, but the only difference is the tools used to +manipulate them, and the size of the resulting file. Download +whichever you are most comfortable with. + + [1] http://code.google.com/p/googletest/downloads/list + +Once the package is downloaded, expand it using whichever tools you +prefer for that type. This will result in a new directory with the +name "gtest-X.Y.Z" which contains all of the source code. Here are +some examples on Linux: + + tar -xvzf gtest-X.Y.Z.tar.gz + tar -xvjf gtest-X.Y.Z.tar.bz2 + unzip gtest-X.Y.Z.zip + +### SVN Checkout ### + +To check out the main branch (also known as the "trunk") of Google +Test, run the following Subversion command: svn checkout http://googletest.googlecode.com/svn/trunk/ gtest-svn -or for a release version X.Y.*'s branch: +Setting up the Build +-------------------- - svn checkout http://googletest.googlecode.com/svn/branches/release-X.Y/ \ - gtest-X.Y-svn +To build Google Test and your tests that use it, you need to tell your +build system where to find its headers and source files. The exact +way to do it depends on which build system you use, and is usually +straightforward. -Next you will need to prepare the GNU Autotools build system, if you -are using Linux, Mac OS X, or Cygwin. Enter the target directory of -the checkout command you used ('gtest-svn' or 'gtest-X.Y-svn' above) -and proceed with the following command: +### Generic Build Instructions ### - autoreconf -fvi +Suppose you put Google Test in directory ${GTEST_DIR}. To build it, +create a library build target (or a project as called by Visual Studio +and Xcode) to compile -Once you have completed this step, you are ready to build the library. Note -that you should only need to complete this step once. The subsequent `make' -invocations will automatically re-generate the bits of the build system that -need to be changed. + ${GTEST_DIR}/src/gtest-all.cc -If your system uses older versions of the autotools, the above command will -fail. You may need to explicitly specify a version to use. For instance, if you -have both GNU Automake 1.4 and 1.9 installed and `automake' would invoke the -1.4, use instead: +with - AUTOMAKE=automake-1.9 ACLOCAL=aclocal-1.9 autoreconf -fvi + ${GTEST_DIR}/include and ${GTEST_DIR} -Make sure you're using the same version of automake and aclocal. +in the header search path. Assuming a Linux-like system and gcc, +something like the following will do: -### Source Package: ### -Google Test is also released in source packages which can be downloaded from -its Google Code download page[1]. Several different archive formats are -provided, but the only difference is the tools used to manipulate them, and the -size of the resulting file. Download whichever you are most comfortable with. + g++ -I${GTEST_DIR}/include -I${GTEST_DIR} -c ${GTEST_DIR}/src/gtest-all.cc + ar -rv libgtest.a gtest-all.o - [1] Google Test Downloads: http://code.google.com/p/googletest/downloads/list +Next, you should compile your test source file with +${GTEST_DIR}/include in the header search path, and link it with gtest +and any other necessary libraries: -Once downloaded expand the archive using whichever tools you prefer for that -type. This will always result in a new directory with the name "gtest-X.Y.Z" -which contains all of the source code. Here are some examples in Linux: + g++ -I${GTEST_DIR}/include path/to/your_test.cc libgtest.a -o your_test - tar -xvzf gtest-X.Y.Z.tar.gz - tar -xvjf gtest-X.Y.Z.tar.bz2 - unzip gtest-X.Y.Z.zip +As an example, the make/ directory contains a Makefile that you can +use to build Google Test on systems where GNU make is available +(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google +Test's own tests. Instead, it just builds the Google Test library and +a sample test. You can use it as a starting point for your own build +script. + +If the default settings are correct for your environment, the +following commands should succeed: + + cd ${GTEST_DIR}/make + make + ./sample1_unittest + +If you see errors, try to tweak the contents of make/Makefile to make +them go away. There are instructions in make/Makefile on how to do +it. + +### Using CMake ### + +Google Test comes with a CMake build script (CMakeLists.txt) that can +be used on a wide range of platforms ("C" stands for cross-platofrm.). +If you don't have CMake installed already, you can download it for +free from http://www.cmake.org/. + +CMake works by generating native makefiles or build projects that can +be used in the compiler environment of your choice. The typical +workflow starts with: + + mkdir mybuild # Create a directory to hold the build output. + cd mybuild + cmake ${GTEST_DIR} # Generate native build scripts. + +If you want to build Google Test's samples, you should replace the +last command with + + cmake -Dgtest_build_samples=ON ${GTEST_DIR} + +If you are on a *nix system, you should now see a Makefile in the +current directory. Just type 'make' to build gtest. + +If you use Windows and have Vistual Studio installed, a gtest.sln file +and several .vcproj files will be created. You can then build them +using Visual Studio. + +On Mac OS X with Xcode installed, a .xcodeproj file will be generated. + +### Legacy Build Scripts ### + +Before settling on CMake, we have been providing hand-maintained build +projects/scripts for Visual Studio, Xcode, and Autotools. While we +continue to provide them for convenience, they are not actively +maintained any more. We highly recommend that you follow the +instructions in the previous two sections to integrate Google Test +with your existing build system. + +If you still need to use the legacy build scripts, here's how: + +The msvc\ folder contains two solutions with Visual C++ projects. +Open the gtest.sln or gtest-md.sln file using Visual Studio, and you +are ready to build Google Test the same way you build any Visual +Studio project. Files that have names ending with -md use DLL +versions of Microsoft runtime libraries (the /MD or the /MDd compiler +option). Files without that suffix use static versions of the runtime +libraries (the /MT or the /MTd option). Please note that one must use +the same option to compile both gtest and the test code. If you use +Visual Studio 2005 or above, we recommend the -md version as /MD is +the default for new projects in these versions of Visual Studio. + +On Mac OS X, open the gtest.xcodeproj in the xcode/ folder using +Xcode. Build the "gtest" target. The universal binary framework will +end up in your selected build directory (selected in the Xcode +"Preferences..." -> "Building" pane and defaults to xcode/build). +Alternatively, at the command line, enter: + + xcodebuild + +This will build the "Release" configuration of gtest.framework in your +default build location. See the "xcodebuild" man page for more +information about building different configurations and building in +different locations. + +Tweaking Google Test +-------------------- + +Google Test can be used in diverse environments. The default +configuration may not work (or may not work well) out of the box in +some environments. However, you can easily tweak Google Test by +defining control macros on the compiler command line. Generally, +these macros are named like GTEST_XYZ and you define them to either 1 +or 0 to enable or disable a certain feature. + +We list the most frequently used macros below. For a complete list, +see file include/gtest/internal/gtest-port.h. + +### Choosing a TR1 Tuple Library ### -Choosing a TR1 Tuple Library ----------------------------- Some Google Test features require the C++ Technical Report 1 (TR1) -tuple library, which is not yet widely available with all compilers. -The good news is that Google Test implements a subset of TR1 tuple -that's enough for its own need, and will automatically use this when -the compiler doesn't provide TR1 tuple. +tuple library, which is not yet available with all compilers. The +good news is that Google Test implements a subset of TR1 tuple that's +enough for its own need, and will automatically use this when the +compiler doesn't provide TR1 tuple. Usually you don't need to care about which tuple library Google Test uses. However, if your project already uses TR1 tuple, you need to tell Google Test to use the same TR1 tuple library the rest of your -project uses (this requirement is new in Google Test 1.4.0, so you may -need to take care of it when upgrading from an earlier version), or -the two tuple implementations will clash. To do that, add +project uses, or the two tuple implementations will clash. To do +that, add -DGTEST_USE_OWN_TR1_TUPLE=0 -to the compiler flags while compiling Google Test and your tests. +to the compiler flags while compiling Google Test and your tests. If +you want to force Google Test to use its own tuple library, just add + + -DGTEST_USE_OWN_TR1_TUPLE=1 + +to the compiler flags instead. If you don't want Google Test to use tuple at all, add -DGTEST_HAS_TR1_TUPLE=0 -to the compiler flags. All features using tuple will be disabled in -this mode. - -Building the Source -------------------- -### Linux, Mac OS X (without Xcode), and Cygwin ### -There are two primary options for building the source at this point: build it -inside the source code tree, or in a separate directory. We recommend building -in a separate directory as that tends to produce both more consistent results -and be easier to clean up should anything go wrong, but both patterns are -supported. The only hard restriction is that while the build directory can be -a subdirectory of the source directory, the opposite is not possible and will -result in errors. Once you have selected where you wish to build Google Test, -create the directory if necessary, and enter it. The following steps apply for -either approach by simply substituting the shell variable SRCDIR with "." for -building inside the source directory, and the relative path to the source -directory otherwise. - - ${SRCDIR}/configure # Standard GNU configure script, --help for more info - make # Standard makefile following GNU conventions - make check # Builds and runs all tests - all should pass - -### Windows ### -The msvc\ folder contains two solutions with Visual C++ projects. Open the -gtest.sln or gtest-md.sln file using Visual Studio, and you are ready to -build Google Test the same way you build any Visual Studio project. Files -that have names ending with -md use DLL versions of Microsoft runtime -libraries (the /MD or the /MDd compiler option). Files without that suffix -use static versions of the runtime libraries (the /MT or the /MTd option). -Please note that one must use the same option to compile both gtest and his -test code. If you use Visual Studio 2005 or above, we recommend the -md -version as /MD is the default for new projects in these versions of Visual -Studio. - -### Mac OS X (universal-binary framework) ### -Open the gtest.xcodeproj in the xcode/ folder using Xcode. Build the "gtest" -target. The universal binary framework will end up in your selected build -directory (selected in the Xcode "Preferences..." -> "Building" pane and -defaults to xcode/build). Alternatively, at the command line, enter: +and all features using tuple will be disabled. - xcodebuild +### Multi-threaded Tests ### -This will build the "Release" configuration of gtest.framework in your -default build location. See the "xcodebuild" man page for more information about -building different configurations and building in different locations. +Google Test is thread-safe where the pthread library is available. +After #include <gtest/gtest.h>, you can check the GTEST_IS_THREADSAFE +macro to see whether this is the case (yes if the macro is #defined to +1, no if it's undefined.). -To test the gtest.framework in Xcode, change the active target to "Check" and -then build. This target builds all of the tests and then runs them. Don't worry -if you see some errors. Xcode reports all test failures (even the intentional -ones) as errors. However, you should see a "Build succeeded" message at the end -of the build log. To run all of the tests from the command line, enter: +If Google Test doesn't correctly detect whether pthread is available +in your environment, you can force it with - xcodebuild -target Check + -DGTEST_HAS_PTHREAD=1 -Installation with xcodebuild requires specifying an installation desitination -directory, known as the DSTROOT. Three items will be installed when using -xcodebuild: +or - $DSTROOT/Library/Frameworks/gtest.framework - $DSTROOT/usr/local/lib/libgtest.a - $DSTROOT/usr/local/lib/libgtest_main.a + -DGTEST_HAS_PTHREAD=0 -You specify the installation directory on the command line with the other -xcodebuild options. Here's how you would install in a user-visible location: +When Google Test uses pthread, you may need to add flags to your +compiler and/or linker to select the pthread library, or you'll get +link errors. If you use the CMake script or the deprecated Autotools +script, this is taken care of for you. If you use your own build +script, you'll need to read your compiler and linker's manual to +figure out what flags to add. - xcodebuild install DSTROOT=~ +### As a Shared Library (DLL) ### -To perform a system-wide inistall, escalate to an administrator and specify -the file system root as the DSTROOT: +Google Test is compact, so most users can build and link it as a +static library for the simplicity. You can choose to use Google Test +as a shared library (known as a DLL on Windows) if you prefer. - sudo xcodebuild install DSTROOT=/ +To compile gtest as a shared library, add -To uninstall gtest.framework via the command line, you need to delete the three -items listed above. Remember to escalate to an administrator if deleting these -from the system-wide location using the commands listed below: + -DGTEST_CREATE_SHARED_LIBRARY=1 - sudo rm -r /Library/Frameworks/gtest.framework - sudo rm /usr/local/lib/libgtest.a - sudo rm /usr/local/lib/libgtest_main.a +to the compiler flags. You'll also need to tell the linker to produce +a shared library instead - consult your linker's manual for how to do +it. -It is also possible to build and execute individual tests within Xcode. Each -test has its own Xcode "Target" and Xcode "Executable". To build any of the -tests, change the active target and the active executable to the test of -interest and then build and run. +To compile your tests that use the gtest shared library, add -Individual tests can be built from the command line using: + -DGTEST_LINKED_AS_SHARED_LIBRARY=1 - xcodebuild -target <test_name> +to the compiler flags. -These tests can be executed from the command line by moving to the build -directory and then (in bash) +### Avoiding Macro Name Clashes ### - export DYLD_FRAMEWORK_PATH=`pwd` - ./<test_name> # (e.g. ./gtest_unittest) +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. -To use gtest.framework for your own tests, first, install the framework using -the steps described above. Then add it to your Xcode project by selecting -Project->Add to Project... from the main menu. Next, add libgtest_main.a from -gtest.framework/Resources directory using the same menu command. Finally, -create a new executable target and add gtest.framework and libgtest_main.a to -the "Link Binary With Libraries" build phase. +Specifically, if both Google Test and some other code define macro +FOO, you can add -### Using GNU Make ### -The make/ directory contains a Makefile that you can use to build -Google Test on systems where GNU make is available (e.g. Linux, Mac OS -X, and Cygwin). It doesn't try to build Google Test's own tests. -Instead, it just builds the Google Test library and a sample test. -You can use it as a starting point for your own Makefile. + -DGTEST_DONT_DEFINE_FOO=1 -If the default settings are correct for your environment, the -following commands should succeed: +to the compiler flags to tell Google Test to change the macro's name +from FOO to GTEST_FOO. Currently FOO can be FAIL, SUCCEED, or TEST. +For example, with -DGTEST_DONT_DEFINE_TEST=1, you'll need to write - cd ${SRCDIR}/make - make - ./sample1_unittest + GTEST_TEST(SomeTest, DoesThis) { ... } -If you see errors, try to tweak the contents of make/Makefile to make -them go away. There are instructions in make/Makefile on how to do -it. +instead of -### Using Your Own Build System ### -If none of the build solutions we provide works for you, or if you -prefer your own build system, you just need to compile -src/gtest-all.cc into a library and link your tests with it. Assuming -a Linux-like system and gcc, something like the following will do: + TEST(SomeTest, DoesThis) { ... } - cd ${SRCDIR} - g++ -I. -I./include -c src/gtest-all.cc - ar -rv libgtest.a gtest-all.o - g++ -I. -I./include path/to/your_test.cc libgtest.a -o your_test +in order to define a test. + +Upgrating from an Earlier Version +--------------------------------- + +We strive to keep Google Test 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 Test. + +### Upgrading from 1.3.0 or Earlier ### + +You may need to explicitly enable or disable Google Test's own TR1 +tuple library. See the instructions in section "Choosing a TR1 Tuple +Library". + +### Upgrading from 1.4.0 or Earlier ### + +The Autotools build script (configure + make) is no longer officially +supportted. You are encouraged to migrate to your own build system or +use CMake. If you still need to use Autotools, you can find +instructions in the README file from Google Test 1.4.0. + +On platforms where the pthread library is available, Google Test uses +it in order to be thread-safe. See the "Multi-threaded Tests" section +for what this means to your build script. + +If you use Microsoft Visual C++ 7.1 with exceptions disabled, Google +Test will no longer compile. This should affect very few people, as a +large portion of STL (including <string>) doesn't compile in this mode +anyway. We decided to stop supporting it in order to greatly simplify +Google Test's implementation. + +Developing Google Test +---------------------- + +This section discusses how to make your own changes to Google Test. + +### Testing Google Test Itself ### + +To make sure your changes work as intended and don't break existing +functionality, you'll want to compile and run Google Test's own tests. +For that you can use CMake: + + mkdir mybuild + cd mybuild + cmake -Dgtest_build_tests=ON ${GTEST_DIR} + +Make sure you have Python installed, as some of Google Test's tests +are written in Python. If the cmake command complains about not being +able to find Python ("Could NOT find PythonInterp (missing: +PYTHON_EXECUTABLE)"), try telling it explicitly where your Python +executable can be found: + + cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} + +Next, you can build Google Test and all of its own tests. On *nix, +this is usually done by 'make'. To run the tests, do + + make test + +All tests should pass. + +### Regenerating Source Files ### -Regenerating Source Files -------------------------- Some of Google Test's source files are generated from templates (not in the C++ sense) using a script. A template file is named FOO.pump, where FOO is the name of the file it will generate. For example, the @@ -275,12 +397,20 @@ file include/gtest/internal/gtest-type-util.h.pump is used to generate gtest-type-util.h in the same directory. Normally you don't need to worry about regenerating the source files, -unless you need to modify them (e.g. if you are working on a patch for -Google Test). In that case, you should modify the corresponding .pump -files instead and run the 'pump' script (for Pump is Useful for Meta -Programming) to regenerate them. We are still working on releasing -the script and its documentation. If you need it now, please email -googletestframework@googlegroups.com such that we know to make it -happen sooner. +unless you need to modify them. In that case, you should modify the +corresponding .pump files instead and run the pump.py Python script to +regenerate them. You can find pump.py in the scripts/ directory. +Read the Pump manual [2] for how to use it. + + [2] http://code.google.com/p/googletest/wiki/PumpManual + +### Contributing a Patch ### + +We welcome patches. Please read the Google Test developer's guide [3] +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. + + [3] http://code.google.com/p/googletest/wiki/GoogleTestDevGuide Happy testing! diff --git a/testing/gtest/codegear/gtest.groupproj b/testing/gtest/codegear/gtest.groupproj index 8b650f8..faf31ca 100644 --- a/testing/gtest/codegear/gtest.groupproj +++ b/testing/gtest/codegear/gtest.groupproj @@ -23,15 +23,6 @@ <Target Name="gtest:Make">
<MSBuild Projects="gtest.cbproj" Targets="Make" />
</Target>
- <Target Name="gtest_unittest">
- <MSBuild Projects="gtest_unittest.cbproj" Targets="" />
- </Target>
- <Target Name="gtest_unittest:Clean">
- <MSBuild Projects="gtest_unittest.cbproj" Targets="Clean" />
- </Target>
- <Target Name="gtest_unittest:Make">
- <MSBuild Projects="gtest_unittest.cbproj" Targets="Make" />
- </Target>
<Target Name="gtest_main">
<MSBuild Projects="gtest_main.cbproj" Targets="" />
</Target>
@@ -41,14 +32,23 @@ <Target Name="gtest_main:Make">
<MSBuild Projects="gtest_main.cbproj" Targets="Make" />
</Target>
+ <Target Name="gtest_unittest">
+ <MSBuild Projects="gtest_unittest.cbproj" Targets="" />
+ </Target>
+ <Target Name="gtest_unittest:Clean">
+ <MSBuild Projects="gtest_unittest.cbproj" Targets="Clean" />
+ </Target>
+ <Target Name="gtest_unittest:Make">
+ <MSBuild Projects="gtest_unittest.cbproj" Targets="Make" />
+ </Target>
<Target Name="Build">
- <CallTarget Targets="gtest;gtest_unittest;gtest_main" />
+ <CallTarget Targets="gtest;gtest_main;gtest_unittest" />
</Target>
<Target Name="Clean">
- <CallTarget Targets="gtest:Clean;gtest_unittest:Clean;gtest_main:Clean" />
+ <CallTarget Targets="gtest:Clean;gtest_main:Clean;gtest_unittest:Clean" />
</Target>
<Target Name="Make">
- <CallTarget Targets="gtest:Make;gtest_unittest:Make;gtest_main:Make" />
+ <CallTarget Targets="gtest:Make;gtest_main:Make;gtest_unittest:Make" />
</Target>
<Import Condition="Exists('$(MSBuildBinPath)\Borland.Group.Targets')" Project="$(MSBuildBinPath)\Borland.Group.Targets" />
</Project>
\ No newline at end of file diff --git a/testing/gtest/codegear/gtest_unittest.cbproj b/testing/gtest/codegear/gtest_unittest.cbproj index d3823c9..dc5db8e 100644 --- a/testing/gtest/codegear/gtest_unittest.cbproj +++ b/testing/gtest/codegear/gtest_unittest.cbproj @@ -18,27 +18,27 @@ <CfgParent>Base</CfgParent>
</PropertyGroup>
<PropertyGroup Condition="'$(Base)'!=''">
- <BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>
<OutputExt>exe</OutputExt>
- <DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>
+ <BCC_OptimizeForSpeed>true</BCC_OptimizeForSpeed>
<Defines>NO_STRICT</Defines>
+ <DCC_CBuilderOutput>JPHNE</DCC_CBuilderOutput>
<DynamicRTL>true</DynamicRTL>
- <UsePackages>true</UsePackages>
<ILINK_ObjectSearchPath>..\test</ILINK_ObjectSearchPath>
- <NoVCL>true</NoVCL>
+ <UsePackages>true</UsePackages>
<ProjectType>CppConsoleApplication</ProjectType>
+ <NoVCL>true</NoVCL>
<BCC_CPPCompileAlways>true</BCC_CPPCompileAlways>
- <PackageImports>rtl.bpi;vcl.bpi;bcbie.bpi;vclx.bpi;vclactnband.bpi;xmlrtl.bpi;bcbsmp.bpi;dbrtl.bpi;vcldb.bpi;bdertl.bpi;vcldbx.bpi;dsnap.bpi;dsnapcon.bpi;vclib.bpi;ibxpress.bpi;adortl.bpi;dbxcds.bpi;dbexpress.bpi;DbxCommonDriver.bpi;websnap.bpi;vclie.bpi;webdsnap.bpi;inet.bpi;inetdbbde.bpi;inetdbxpress.bpi;soaprtl.bpi;Rave75VCL.bpi;teeUI.bpi;tee.bpi;teedb.bpi;IndyCore.bpi;IndySystem.bpi;IndyProtocols.bpi;IntrawebDB_90_100.bpi;Intraweb_90_100.bpi;dclZipForged11.bpi;vclZipForged11.bpi;Jcl.bpi;JclVcl.bpi;JvCoreD11R.bpi;JvSystemD11R.bpi;JvStdCtrlsD11R.bpi;JvAppFrmD11R.bpi;JvBandsD11R.bpi;JvDBD11R.bpi;JvDlgsD11R.bpi;JvBDED11R.bpi;JvCmpD11R.bpi;JvCryptD11R.bpi;JvCtrlsD11R.bpi;JvCustomD11R.bpi;JvDockingD11R.bpi;JvDotNetCtrlsD11R.bpi;JvEDID11R.bpi;JvGlobusD11R.bpi;JvHMID11R.bpi;JvInterpreterD11R.bpi;JvJansD11R.bpi;JvManagedThreadsD11R.bpi;JvMMD11R.bpi;JvNetD11R.bpi;JvPageCompsD11R.bpi;JvPluginD11R.bpi;JvPrintPreviewD11R.bpi;JvRuntimeDesignD11R.bpi;JvTimeFrameworkD11R.bpi;JvValidatorsD11R.bpi;JvWizardD11R.bpi;JvXPCtrlsD11R.bpi;VclSmp.bpi</PackageImports>
+ <PackageImports>rtl.bpi;vcl.bpi;bcbie.bpi;vclx.bpi;vclactnband.bpi;xmlrtl.bpi;bcbsmp.bpi;dbrtl.bpi;vcldb.bpi;bdertl.bpi;vcldbx.bpi;dsnap.bpi;dsnapcon.bpi;vclib.bpi;ibxpress.bpi;adortl.bpi;dbxcds.bpi;dbexpress.bpi;DbxCommonDriver.bpi;websnap.bpi;vclie.bpi;webdsnap.bpi;inet.bpi;inetdbbde.bpi;inetdbxpress.bpi;soaprtl.bpi;Rave75VCL.bpi;teeUI.bpi;tee.bpi;teedb.bpi;IndyCore.bpi;IndySystem.bpi;IndyProtocols.bpi;IntrawebDB_90_100.bpi;Intraweb_90_100.bpi;Jcl.bpi;JclVcl.bpi;JvCoreD11R.bpi;JvSystemD11R.bpi;JvStdCtrlsD11R.bpi;JvAppFrmD11R.bpi;JvBandsD11R.bpi;JvDBD11R.bpi;JvDlgsD11R.bpi;JvBDED11R.bpi;JvCmpD11R.bpi;JvCryptD11R.bpi;JvCtrlsD11R.bpi;JvCustomD11R.bpi;JvDockingD11R.bpi;JvDotNetCtrlsD11R.bpi;JvEDID11R.bpi;JvGlobusD11R.bpi;JvHMID11R.bpi;JvInterpreterD11R.bpi;JvJansD11R.bpi;JvManagedThreadsD11R.bpi;JvMMD11R.bpi;JvNetD11R.bpi;JvPageCompsD11R.bpi;JvPluginD11R.bpi;JvPrintPreviewD11R.bpi;JvRuntimeDesignD11R.bpi;JvTimeFrameworkD11R.bpi;JvValidatorsD11R.bpi;JvWizardD11R.bpi;JvXPCtrlsD11R.bpi;VclSmp.bpi</PackageImports>
<BCC_wpar>false</BCC_wpar>
<IncludePath>$(BDS)\include;$(BDS)\include\dinkumware;$(BDS)\include\vcl;..\include;..\test;..</IncludePath>
<ILINK_LibraryPath>$(BDS)\lib;$(BDS)\lib\obj;$(BDS)\lib\psdk;..\test</ILINK_LibraryPath>
<Multithreaded>true</Multithreaded>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1)'!=''">
- <DCC_Optimize>false</DCC_Optimize>
<BCC_OptimizeForSpeed>false</BCC_OptimizeForSpeed>
- <Defines>_DEBUG;$(Defines)</Defines>
+ <DCC_Optimize>false</DCC_Optimize>
<DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>
+ <Defines>_DEBUG;$(Defines)</Defines>
<ILINK_FullDebugInfo>true</ILINK_FullDebugInfo>
<BCC_InlineFunctionExpansion>false</BCC_InlineFunctionExpansion>
<ILINK_DisableIncrementalLinking>true</ILINK_DisableIncrementalLinking>
@@ -48,8 +48,8 @@ <IntermediateOutputDir>Debug</IntermediateOutputDir>
<TASM_DisplaySourceLines>true</TASM_DisplaySourceLines>
<BCC_StackFrames>true</BCC_StackFrames>
- <ILINK_LibraryPath>$(BDS)\lib\debug;$(ILINK_LibraryPath)</ILINK_LibraryPath>
<BCC_DisableOptimizations>true</BCC_DisableOptimizations>
+ <ILINK_LibraryPath>$(BDS)\lib\debug;$(ILINK_LibraryPath)</ILINK_LibraryPath>
<TASM_Debugging>Full</TASM_Debugging>
<BCC_SourceDebuggingOn>true</BCC_SourceDebuggingOn>
</PropertyGroup>
diff --git a/testing/gtest/configure.ac b/testing/gtest/configure.ac index 1b91237..de2d1e7 100644 --- a/testing/gtest/configure.ac +++ b/testing/gtest/configure.ac @@ -12,6 +12,7 @@ AC_INIT([Google C++ Testing Framework], # Provide various options to initialize the Autoconf and configure processes. AC_PREREQ([2.59]) AC_CONFIG_SRCDIR([./COPYING]) +AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_HEADERS([build-aux/config.h]) AC_CONFIG_FILES([Makefile]) diff --git a/testing/gtest/include/gtest/gtest.h b/testing/gtest/include/gtest/gtest.h index ee7a8d5..937f476 100644 --- a/testing/gtest/include/gtest/gtest.h +++ b/testing/gtest/include/gtest/gtest.h @@ -59,6 +59,7 @@ #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_prod.h> #include <gtest/gtest-test-part.h> #include <gtest/gtest-typed-test.h> @@ -1651,10 +1652,22 @@ const T* TestWithParam<T>::parameter_ = NULL; #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") // Generates a fatal failure with a generic message. -#define FAIL() GTEST_FATAL_FAILURE_("Failed") +#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") + +// Define this macro to 1 to omit the definition of FAIL(), which is a +// generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_FAIL +#define FAIL() GTEST_FAIL() +#endif // Generates a success with a generic message. -#define SUCCEED() GTEST_SUCCESS_("Succeeded") +#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") + +// Define this macro to 1 to omit the definition of SUCCEED(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_SUCCEED +#define SUCCEED() GTEST_SUCCEED() +#endif // Macros for testing exceptions. // @@ -1914,17 +1927,6 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ __FILE__, __LINE__, ::testing::Message() << (message)) -namespace internal { - -// This template is declared, but intentionally undefined. -template <typename T1, typename T2> -struct StaticAssertTypeEqHelper; - -template <typename T> -struct StaticAssertTypeEqHelper<T, T> {}; - -} // namespace internal - // Compile-time assertion for type equality. // StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are // the same type. The value it returns is not interesting. @@ -1957,7 +1959,7 @@ struct StaticAssertTypeEqHelper<T, T> {}; // to cause a compiler error. template <typename T1, typename T2> bool StaticAssertTypeEq() { - internal::StaticAssertTypeEqHelper<T1, T2>(); + (void)internal::StaticAssertTypeEqHelper<T1, T2>(); return true; } @@ -1986,10 +1988,15 @@ bool StaticAssertTypeEq() { // code. GetTestTypeId() is guaranteed to always return the same // value, as it always calls GetTypeId<>() from the Google Test // framework. -#define TEST(test_case_name, test_name)\ +#define GTEST_TEST(test_case_name, test_name)\ GTEST_TEST_(test_case_name, test_name, \ ::testing::Test, ::testing::internal::GetTestTypeId()) +// Define this macro to 1 to omit the definition of TEST(), which +// is a generic name and clashes with some other libraries. +#if !GTEST_DONT_DEFINE_TEST +#define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) +#endif // Defines a test that uses a test fixture. // diff --git a/testing/gtest/include/gtest/internal/gtest-internal.h b/testing/gtest/include/gtest/internal/gtest-internal.h index 31a66e9..bf8412b 100644 --- a/testing/gtest/include/gtest/internal/gtest-internal.h +++ b/testing/gtest/include/gtest/internal/gtest-internal.h @@ -97,6 +97,9 @@ inline void GTestStreamToHelper(std::ostream* os, const T& val) { *os << val; } +class ProtocolMessage; +namespace proto2 { class Message; } + namespace testing { // Forward declaration of classes. @@ -762,6 +765,15 @@ GTEST_API_ bool AlwaysTrue(); // Always returns false. inline bool AlwaysFalse() { return !AlwaysTrue(); } +// Helper for suppressing false warning from Clang on a const char* +// variable declared in a conditional expression always being NULL in +// the else branch. +struct GTEST_API_ ConstCharPtr { + ConstCharPtr(const char* str) : value(str) {} + operator bool() const { return true; } + const char* value; +}; + // A simple Linear Congruential Generator for generating random // numbers with a uniform distribution. Unlike rand() and srand(), it // doesn't use global state (and therefore can't interfere with user @@ -784,6 +796,296 @@ class GTEST_API_ Random { GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); }; +// Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a +// compiler error iff T1 and T2 are different types. +template <typename T1, typename T2> +struct CompileAssertTypesEqual; + +template <typename T> +struct CompileAssertTypesEqual<T, T> { +}; + +// Removes the reference from a type if it is a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::remove_reference, which is not widely available yet. +template <typename T> +struct RemoveReference { typedef T type; }; // NOLINT +template <typename T> +struct RemoveReference<T&> { typedef T type; }; // NOLINT + +// A handy wrapper around RemoveReference that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_REFERENCE_(T) \ + typename ::testing::internal::RemoveReference<T>::type + +// Removes const from a type if it is a const type, otherwise leaves +// it unchanged. This is the same as tr1::remove_const, which is not +// widely available yet. +template <typename T> +struct RemoveConst { typedef T type; }; // NOLINT +template <typename T> +struct RemoveConst<const T> { typedef T type; }; // NOLINT + +// MSVC 8.0 has a bug which causes the above definition to fail to +// remove the const in 'const int[3]'. The following specialization +// works around the bug. However, it causes trouble with gcc and thus +// needs to be conditionally compiled. +#ifdef _MSC_VER +template <typename T, size_t N> +struct RemoveConst<T[N]> { + typedef typename RemoveConst<T>::type type[N]; +}; +#endif // _MSC_VER + +// A handy wrapper around RemoveConst that works when the argument +// T depends on template parameters. +#define GTEST_REMOVE_CONST_(T) \ + typename ::testing::internal::RemoveConst<T>::type + +// Turns const U&, U&, const U, and U all into U. +#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ + GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) + +// Adds reference to a type if it is not a reference type, +// otherwise leaves it unchanged. This is the same as +// tr1::add_reference, which is not widely available yet. +template <typename T> +struct AddReference { typedef T& type; }; // NOLINT +template <typename T> +struct AddReference<T&> { typedef T& type; }; // NOLINT + +// A handy wrapper around AddReference that works when the argument T +// depends on template parameters. +#define GTEST_ADD_REFERENCE_(T) \ + typename ::testing::internal::AddReference<T>::type + +// Adds a reference to const on top of T as necessary. For example, +// it transforms +// +// char ==> const char& +// const char ==> const char& +// char& ==> const char& +// const char& ==> const char& +// +// The argument T must depend on some template parameters. +#define GTEST_REFERENCE_TO_CONST_(T) \ + GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) + +// ImplicitlyConvertible<From, To>::value is a compile-time bool +// constant that's true iff type From can be implicitly converted to +// type To. +template <typename From, typename To> +class ImplicitlyConvertible { + private: + // We need the following helper functions only for their types. + // They have no implementations. + + // MakeFrom() is an expression whose type is From. We cannot simply + // use From(), as the type From may not have a public default + // constructor. + static From MakeFrom(); + + // These two functions are overloaded. Given an expression + // Helper(x), the compiler will pick the first version if x can be + // implicitly converted to type To; otherwise it will pick the + // second version. + // + // The first version returns a value of size 1, and the second + // version returns a value of size 2. Therefore, by checking the + // size of Helper(x), which can be done at compile time, we can tell + // which version of Helper() is used, and hence whether x can be + // implicitly converted to type To. + static char Helper(To); + static char (&Helper(...))[2]; // NOLINT + + // We have to put the 'public' section after the 'private' section, + // or MSVC refuses to compile the code. + public: + // MSVC warns about implicitly converting from double to int for + // possible loss of data, so we need to temporarily disable the + // warning. +#ifdef _MSC_VER +#pragma warning(push) // Saves the current warning state. +#pragma warning(disable:4244) // Temporarily disables warning 4244. + static const bool value = + sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; +#pragma warning(pop) // Restores the warning state. +#else + static const bool value = + sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; +#endif // _MSV_VER +}; +template <typename From, typename To> +const bool ImplicitlyConvertible<From, To>::value; + +// IsAProtocolMessage<T>::value is a compile-time bool constant that's +// true iff T is type ProtocolMessage, proto2::Message, or a subclass +// of those. +template <typename T> +struct IsAProtocolMessage + : public bool_constant< + ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value || + ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> { +}; + +// When the compiler sees expression IsContainerTest<C>(0), the first +// overload of IsContainerTest will be picked if C is an STL-style +// container class (since C::const_iterator* is a valid type and 0 can +// be converted to it), while the second overload will be picked +// otherwise (since C::const_iterator will be an invalid type in this +// case). Therefore, we can determine whether C is a container class +// by checking the type of IsContainerTest<C>(0). The value of the +// expression is insignificant. +typedef int IsContainer; +template <class C> +IsContainer IsContainerTest(typename C::const_iterator*) { return 0; } + +typedef char IsNotContainer; +template <class C> +IsNotContainer IsContainerTest(...) { return '\0'; } + +// Utilities for native arrays. + +// ArrayEq() compares two k-dimensional native arrays using the +// elements' operator==, where k can be any integer >= 0. When k is +// 0, ArrayEq() degenerates into comparing a single pair of values. + +template <typename T, typename U> +bool ArrayEq(const T* lhs, size_t size, const U* rhs); + +// This generic version is used when k is 0. +template <typename T, typename U> +inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } + +// This overload is used when k >= 1. +template <typename T, typename U, size_t N> +inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { + return internal::ArrayEq(lhs, N, rhs); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous ArrayEq() function, arrays with different sizes would +// lead to different copies of the template code. +template <typename T, typename U> +bool ArrayEq(const T* lhs, size_t size, const U* rhs) { + for (size_t i = 0; i != size; i++) { + if (!internal::ArrayEq(lhs[i], rhs[i])) + return false; + } + return true; +} + +// Finds the first element in the iterator range [begin, end) that +// equals elem. Element may be a native array type itself. +template <typename Iter, typename Element> +Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { + for (Iter it = begin; it != end; ++it) { + if (internal::ArrayEq(*it, elem)) + return it; + } + return end; +} + +// CopyArray() copies a k-dimensional native array using the elements' +// operator=, where k can be any integer >= 0. When k is 0, +// CopyArray() degenerates into copying a single value. + +template <typename T, typename U> +void CopyArray(const T* from, size_t size, U* to); + +// This generic version is used when k is 0. +template <typename T, typename U> +inline void CopyArray(const T& from, U* to) { *to = from; } + +// This overload is used when k >= 1. +template <typename T, typename U, size_t N> +inline void CopyArray(const T(&from)[N], U(*to)[N]) { + internal::CopyArray(from, N, *to); +} + +// This helper reduces code bloat. If we instead put its logic inside +// the previous CopyArray() function, arrays with different sizes +// would lead to different copies of the template code. +template <typename T, typename U> +void CopyArray(const T* from, size_t size, U* to) { + for (size_t i = 0; i != size; i++) { + internal::CopyArray(from[i], to + i); + } +} + +// The relation between an NativeArray object (see below) and the +// native array it represents. +enum RelationToSource { + kReference, // The NativeArray references the native array. + kCopy // The NativeArray makes a copy of the native array and + // owns the copy. +}; + +// Adapts a native array to a read-only STL-style container. Instead +// of the complete STL container concept, this adaptor only implements +// members useful for Google Mock's container matchers. New members +// should be added as needed. To simplify the implementation, we only +// support Element being a raw type (i.e. having no top-level const or +// reference modifier). It's the client's responsibility to satisfy +// this requirement. Element can be an array type itself (hence +// multi-dimensional arrays are supported). +template <typename Element> +class NativeArray { + public: + // STL-style container typedefs. + typedef Element value_type; + typedef const Element* const_iterator; + + // Constructs from a native array. + NativeArray(const Element* array, size_t count, RelationToSource relation) { + Init(array, count, relation); + } + + // Copy constructor. + NativeArray(const NativeArray& rhs) { + Init(rhs.array_, rhs.size_, rhs.relation_to_source_); + } + + ~NativeArray() { + // Ensures that the user doesn't instantiate NativeArray with a + // const or reference type. + static_cast<void>(StaticAssertTypeEqHelper<Element, + GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>()); + if (relation_to_source_ == kCopy) + delete[] array_; + } + + // STL-style container methods. + size_t size() const { return size_; } + const_iterator begin() const { return array_; } + const_iterator end() const { return array_ + size_; } + bool operator==(const NativeArray& rhs) const { + return size() == rhs.size() && + ArrayEq(begin(), size(), rhs.begin()); + } + + private: + // Initializes this object; makes a copy of the input array if + // 'relation' is kCopy. + void Init(const Element* array, size_t a_size, RelationToSource relation) { + if (relation == kReference) { + array_ = array; + } else { + Element* const copy = new Element[a_size]; + CopyArray(array, a_size, copy); + array_ = copy; + } + size_ = a_size; + relation_to_source_ = relation; + } + + const Element* array_; + size_t size_; + RelationToSource relation_to_source_; + + GTEST_DISALLOW_ASSIGN_(NativeArray); +}; + } // namespace internal } // namespace testing @@ -808,7 +1110,7 @@ class GTEST_API_ Random { #define GTEST_TEST_THROW_(statement, expected_exception, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const char* gtest_msg = "") { \ + if (::testing::internal::ConstCharPtr gtest_msg = "") { \ bool gtest_caught_expected = false; \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ @@ -817,38 +1119,38 @@ class GTEST_API_ Random { gtest_caught_expected = true; \ } \ catch (...) { \ - gtest_msg = "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws a different " \ - "type."; \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws a different type."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ if (!gtest_caught_expected) { \ - gtest_msg = "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws nothing."; \ + gtest_msg.value = \ + "Expected: " #statement " throws an exception of type " \ + #expected_exception ".\n Actual: it throws nothing."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ - fail(gtest_msg) + fail(gtest_msg.value) #define GTEST_TEST_NO_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const char* gtest_msg = "") { \ + if (::testing::internal::AlwaysTrue()) { \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (...) { \ - gtest_msg = "Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: it throws."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail(gtest_msg) + fail("Expected: " #statement " doesn't throw an exception.\n" \ + " Actual: it throws.") #define GTEST_TEST_ANY_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const char* gtest_msg = "") { \ + if (::testing::internal::AlwaysTrue()) { \ bool gtest_caught_any = false; \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ @@ -857,13 +1159,12 @@ class GTEST_API_ Random { gtest_caught_any = true; \ } \ if (!gtest_caught_any) { \ - gtest_msg = "Expected: " #statement " throws an exception.\n" \ - " Actual: it doesn't."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ - fail(gtest_msg) + fail("Expected: " #statement " throws an exception.\n" \ + " Actual: it doesn't.") // Implements Boolean test assertions such as EXPECT_TRUE. expression can be @@ -880,18 +1181,17 @@ class GTEST_API_ Random { #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const char* gtest_msg = "") { \ + if (::testing::internal::AlwaysTrue()) { \ ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - gtest_msg = "Expected: " #statement " doesn't generate new fatal " \ - "failures in the current thread.\n" \ - " Actual: it does."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ - fail(gtest_msg) + fail("Expected: " #statement " doesn't generate new fatal " \ + "failures in the current thread.\n" \ + " Actual: it does.") // Expands to the name of the class that implements the given test. #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ diff --git a/testing/gtest/include/gtest/internal/gtest-param-util.h b/testing/gtest/include/gtest/internal/gtest-param-util.h index 0cbb58c..98bcca7 100644 --- a/testing/gtest/include/gtest/internal/gtest-param-util.h +++ b/testing/gtest/include/gtest/internal/gtest-param-util.h @@ -44,6 +44,7 @@ #include <gtest/internal/gtest-internal.h> #include <gtest/internal/gtest-linked_ptr.h> #include <gtest/internal/gtest-port.h> +#include <gtest/gtest-printers.h> #if GTEST_HAS_PARAM_TEST @@ -171,7 +172,7 @@ class ParamGenerator { iterator end() const { return iterator(impl_->End()); } private: - ::testing::internal::linked_ptr<const ParamGeneratorInterface<T> > impl_; + linked_ptr<const ParamGeneratorInterface<T> > impl_; }; // Generates values from a range of two comparable values. Can be used to @@ -285,7 +286,7 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { public: Iterator(const ParamGeneratorInterface<T>* base, typename ContainerType::const_iterator iterator) - : base_(base), iterator_(iterator) {} + : base_(base), iterator_(iterator) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface<T>* BaseGenerator() const { @@ -504,12 +505,12 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { param_it != generator.end(); ++param_it, ++i) { Message test_name_stream; test_name_stream << test_info->test_base_name.c_str() << "/" << i; - ::testing::internal::MakeAndRegisterTestInfo( + std::string comment = "GetParam() = " + PrintToString(*param_it); + MakeAndRegisterTestInfo( test_case_name_stream.GetString().c_str(), test_name_stream.GetString().c_str(), "", // test_case_comment - "", // comment; TODO(vladl@google.com): provide parameter value - // representation. + comment.c_str(), GetTestCaseTypeId(), TestCase::SetUpTestCase, TestCase::TearDownTestCase, diff --git a/testing/gtest/include/gtest/internal/gtest-port.h b/testing/gtest/include/gtest/internal/gtest-port.h index a2a62be..f2c80f3 100644 --- a/testing/gtest/include/gtest/internal/gtest-port.h +++ b/testing/gtest/include/gtest/internal/gtest-port.h @@ -609,6 +609,91 @@ namespace internal { class String; +// 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_(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, +// content_type_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. + +template <bool> +struct CompileAssert { +}; + +#define GTEST_COMPILE_ASSERT_(expr, msg) \ + typedef ::testing::internal::CompileAssert<(bool(expr))> \ + msg[bool(expr) ? 1 : -1] + +// Implementation details of GTEST_COMPILE_ASSERT_: +// +// - 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> {}; + +#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 + typedef ::std::stringstream StrStream; // A helper for suppressing warnings on constant condition. It just @@ -790,6 +875,58 @@ inline void FlushInfoLog() { fflush(NULL); } // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // +// Use implicit_cast 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 implicit_cast, the compiler checks that +// the cast is safe. Such explicit implicit_casts 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 implicit_cast is the same as for static_cast: +// +// implicit_cast<ToType>(expr) +// +// implicit_cast 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. +template<typename To> +inline To implicit_cast(To x) { return x; } + +// When you upcast (that is, cast a pointer from type Foo to type +// SuperclassOfFoo), it's fine to use implicit_cast<>, 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. +template<typename To, typename From> // use like this: down_cast<T*>(foo); +inline To down_cast(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. + if (false) { + const To to = NULL; + ::testing::internal::implicit_cast<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. diff --git a/testing/gtest/include/gtest/internal/gtest-string.h b/testing/gtest/include/gtest/internal/gtest-string.h index d1d0297..aff093d 100644 --- a/testing/gtest/include/gtest/internal/gtest-string.h +++ b/testing/gtest/include/gtest/internal/gtest-string.h @@ -41,6 +41,11 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ +#ifdef __BORLANDC__ +// string.h is not guaranteed to provide strcpy on C++ Builder. +#include <mem.h> +#endif + #include <string.h> #include <gtest/internal/gtest-port.h> diff --git a/testing/gtest/make/Makefile b/testing/gtest/make/Makefile index 2d8806e..5b27b6a 100644 --- a/testing/gtest/make/Makefile +++ b/testing/gtest/make/Makefile @@ -20,7 +20,7 @@ GTEST_DIR = .. USER_DIR = ../samples # Flags passed to the preprocessor. -CPPFLAGS += -I$(GTEST_DIR) -I$(GTEST_DIR)/include +CPPFLAGS += -I$(GTEST_DIR)/include # Flags passed to the C++ compiler. CXXFLAGS += -g -Wall -Wextra @@ -52,10 +52,12 @@ GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) # conservative and not optimized. This is fine as Google Test # compiles fast and for ordinary users its source rarely changes. gtest-all.o : $(GTEST_SRCS_) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GTEST_DIR)/src/gtest-all.cc + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ + $(GTEST_DIR)/src/gtest-all.cc gtest_main.o : $(GTEST_SRCS_) - $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(GTEST_DIR)/src/gtest_main.cc + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ + $(GTEST_DIR)/src/gtest_main.cc gtest.a : gtest-all.o $(AR) $(ARFLAGS) $@ $^ @@ -75,4 +77,4 @@ sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc sample1_unittest : sample1.o sample1_unittest.o gtest_main.a - $(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ -o $@ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ diff --git a/testing/gtest/src/gtest-all.cc b/testing/gtest/src/gtest-all.cc index fe34765..f3e22dd 100644 --- a/testing/gtest/src/gtest-all.cc +++ b/testing/gtest/src/gtest-all.cc @@ -43,5 +43,6 @@ #include "src/gtest-death-test.cc" #include "src/gtest-filepath.cc" #include "src/gtest-port.cc" +#include "src/gtest-printers.cc" #include "src/gtest-test-part.cc" #include "src/gtest-typed-test.cc" diff --git a/testing/gtest/src/gtest-death-test.cc b/testing/gtest/src/gtest-death-test.cc index 3b73b01..66bf189 100644 --- a/testing/gtest/src/gtest-death-test.cc +++ b/testing/gtest/src/gtest-death-test.cc @@ -418,7 +418,14 @@ void DeathTestImpl::Abort(AbortReason reason) { const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); - GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(write_fd())); + // 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) } diff --git a/testing/gtest/src/gtest-internal-inl.h b/testing/gtest/src/gtest-internal-inl.h index 855b215..9e63aed 100644 --- a/testing/gtest/src/gtest-internal-inl.h +++ b/testing/gtest/src/gtest-internal-inl.h @@ -739,11 +739,11 @@ class GTEST_API_ UnitTestImpl { } // Registers all parameterized tests defined using TEST_P and - // INSTANTIATE_TEST_P, creating regular tests for each test/parameter - // combination. This method can be called more then once; it has - // guards protecting from registering the tests more then once. - // If value-parameterized tests are disabled, RegisterParameterizedTests - // is present but does nothing. + // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter + // combination. This method can be called more then once; it has guards + // protecting from registering the tests more then once. If + // value-parameterized tests are disabled, RegisterParameterizedTests is + // present but does nothing. void RegisterParameterizedTests(); // Runs all tests in this UnitTest object, prints the result, and @@ -977,7 +977,7 @@ GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); // Returns the message describing the last system error, regardless of the // platform. -String GetLastErrnoDescription(); +GTEST_API_ String GetLastErrnoDescription(); #if GTEST_OS_WINDOWS // Provides leak-safe Windows kernel handle ownership. diff --git a/testing/gtest/src/gtest.cc b/testing/gtest/src/gtest.cc index 342d458..e136a18 100644 --- a/testing/gtest/src/gtest.cc +++ b/testing/gtest/src/gtest.cc @@ -2592,6 +2592,7 @@ bool ShouldUseColor(bool stdout_is_tty) { String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-256color") || + String::CStringEquals(term, "screen") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; @@ -2657,6 +2658,19 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_end(args); } +void PrintFullTestCommentIfPresent(const TestInfo& test_info) { + const char* const comment = test_info.comment(); + const char* const test_case_comment = test_info.test_case_comment(); + + if (test_case_comment[0] != '\0' || comment[0] != '\0') { + printf(", where %s", test_case_comment); + if (test_case_comment[0] != '\0' && comment[0] != '\0') { + printf(" and "); + } + printf("%s", comment); + } +} + // This class implements the TestEventListener interface. // // Class PrettyUnitTestResultPrinter is copyable. @@ -2747,11 +2761,7 @@ void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(COLOR_GREEN, "[ RUN ] "); PrintTestName(test_case_name_.c_str(), test_info.name()); - if (test_info.comment()[0] == '\0') { - printf("\n"); - } else { - printf(", where %s\n", test_info.comment()); - } + printf("\n"); fflush(stdout); } @@ -2774,6 +2784,9 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } PrintTestName(test_case_name_.c_str(), 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()); @@ -2822,15 +2835,8 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { } ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s.%s", test_case.name(), test_info.name()); - if (test_case.comment()[0] != '\0' || - test_info.comment()[0] != '\0') { - printf(", where %s", test_case.comment()); - if (test_case.comment()[0] != '\0' && - test_info.comment()[0] != '\0') { - printf(" and "); - } - } - printf("%s\n", test_info.comment()); + PrintFullTestCommentIfPresent(test_info); + printf("\n"); } } } diff --git a/testing/gtest/src/gtest_main.cc b/testing/gtest/src/gtest_main.cc index d20c02f..6d4d22d 100644 --- a/testing/gtest/src/gtest_main.cc +++ b/testing/gtest/src/gtest_main.cc @@ -31,7 +31,7 @@ #include <gtest/gtest.h> -int main(int argc, char **argv) { +GTEST_API_ int main(int argc, char **argv) { std::cout << "Running main() from gtest_main.cc\n"; testing::InitGoogleTest(&argc, argv); diff --git a/testing/gtest/test/gtest-param-test_test.cc b/testing/gtest/test/gtest-param-test_test.cc index d0a0e73..26acce4 100644 --- a/testing/gtest/test/gtest-param-test_test.cc +++ b/testing/gtest/test/gtest-param-test_test.cc @@ -792,19 +792,50 @@ INSTANTIATE_TEST_CASE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4)); // sequence element used to instantiate the test. class NamingTest : public TestWithParam<int> {}; -TEST_P(NamingTest, TestsAreNamedAppropriately) { +TEST_P(NamingTest, TestsAreNamedAndCommentedCorrectly) { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); EXPECT_STREQ("ZeroToFiveSequence/NamingTest", test_info->test_case_name()); - Message msg; - msg << "TestsAreNamedAppropriately/" << GetParam(); - EXPECT_STREQ(msg.GetString().c_str(), test_info->name()); + Message index_stream; + index_stream << "TestsAreNamedAndCommentedCorrectly/" << GetParam(); + EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name()); + + const ::std::string comment = + "GetParam() = " + ::testing::PrintToString(GetParam()); + EXPECT_EQ(comment, test_info->comment()); } INSTANTIATE_TEST_CASE_P(ZeroToFiveSequence, NamingTest, Range(0, 5)); +// Class that cannot be streamed into an ostream. It needs to be copyable +// (and, in case of MSVC, also assignable) in order to be a test parameter +// type. Its default copy constructor and assignment operator do exactly +// what we need. +class Unstreamable { + public: + explicit Unstreamable(int value) : value_(value) {} + + private: + int value_; +}; + +class CommentTest : public TestWithParam<Unstreamable> {}; + +TEST_P(CommentTest, TestsWithUnstreamableParamsCommentedCorrectly) { + const ::testing::TestInfo* const test_info = + ::testing::UnitTest::GetInstance()->current_test_info(); + + const ::std::string comment = + "GetParam() = " + ::testing::PrintToString(GetParam()); + EXPECT_EQ(comment, test_info->comment()); +} + +INSTANTIATE_TEST_CASE_P(InstantiationWithComments, + CommentTest, + Values(Unstreamable(1))); + #endif // GTEST_HAS_PARAM_TEST TEST(CompileTest, CombineIsDefinedOnlyWhenGtestHasParamTestIsDefined) { diff --git a/testing/gtest/test/gtest-port_test.cc b/testing/gtest/test/gtest-port_test.cc index 3725860..6f1512c 100644 --- a/testing/gtest/test/gtest-port_test.cc +++ b/testing/gtest/test/gtest-port_test.cc @@ -59,6 +59,118 @@ using std::pair; namespace testing { namespace internal { +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::implicit_cast<Base*>(&derived)); +} + +TEST(ImplicitCastTest, CanUseInheritance) { + Derived derived(1); + Base base = ::testing::internal::implicit_cast<Base>(derived); + EXPECT_EQ(derived.member(), base.member()); +} + +class Castable { + public: + 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::implicit_cast<Base>(castable); + EXPECT_TRUE(converted); +} + +class ConstCastable { + public: + 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::implicit_cast<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::implicit_cast<Base>(castable); + EXPECT_TRUE(converted); + EXPECT_FALSE(const_converted); + + converted = false; + const_converted = false; + const ConstAndNonConstCastable const_castable(&converted, &const_converted); + base = ::testing::internal::implicit_cast<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::implicit_cast<To>(&converted); + EXPECT_TRUE(converted); +} + // Tests that the element_type typedef is available in scoped_ptr and refers // to the parameter type. TEST(ScopedPtrTest, DefinesElementType) { @@ -149,8 +261,10 @@ TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) { const char regex[] = #ifdef _MSC_VER "gtest-port_test\\.cc\\(\\d+\\):" -#else +#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.*"; diff --git a/testing/gtest/test/gtest_all_test.cc b/testing/gtest/test/gtest_all_test.cc index e1edb08..955aa62 100644 --- a/testing/gtest/test/gtest_all_test.cc +++ b/testing/gtest/test/gtest_all_test.cc @@ -45,4 +45,3 @@ #include "test/gtest-typed-test2_test.cc" #include "test/gtest_unittest.cc" #include "test/production.cc" -#include "src/gtest_main.cc" diff --git a/testing/gtest/test/gtest_filter_unittest.py b/testing/gtest/test/gtest_filter_unittest.py index 89171e0..0d1a770 100755 --- a/testing/gtest/test/gtest_filter_unittest.py +++ b/testing/gtest/test/gtest_filter_unittest.py @@ -108,6 +108,14 @@ TEST_CASE_REGEX = re.compile(r'^\[\-+\] \d+ tests? from (\w+(/\w+)?)') # Regex for parsing test names from Google Test's output. TEST_REGEX = re.compile(r'^\[\s*RUN\s*\].*\.(\w+(/\w+)?)') +# The command line flag to tell Google Test to output the list of tests it +# will run. +LIST_TESTS_FLAG = '--gtest_list_tests' + +# Indicates whether Google Test supports death tests. +SUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess( + [COMMAND, LIST_TESTS_FLAG]).output + # Full names of all tests in gtest_filter_unittests_. PARAM_TESTS = [ 'SeqP/ParamTest.TestX/0', @@ -129,6 +137,14 @@ DISABLED_TESTS = [ 'DISABLED_FoobarbazTest.TestA', ] +if SUPPORTS_DEATH_TESTS: + DEATH_TESTS = [ + 'HasDeathTest.Test1', + 'HasDeathTest.Test2', + ] +else: + DEATH_TESTS = [] + # All the non-disabled tests. ACTIVE_TESTS = [ 'FooTest.Abc', @@ -141,10 +157,7 @@ ACTIVE_TESTS = [ 'BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB', - - 'HasDeathTest.Test1', - 'HasDeathTest.Test2', - ] + PARAM_TESTS + ] + DEATH_TESTS + PARAM_TESTS param_tests_present = None @@ -210,7 +223,7 @@ def RunWithSharding(total_shards, shard_index, command): class GTestFilterUnitTest(gtest_test_utils.TestCase): - """Tests GTEST_FILTER env variable or --gtest_filter flag to filter tests.""" + """Tests the env variable or the command line flag to filter tests.""" # Utilities. @@ -242,17 +255,17 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): return tests_to_run def RunAndVerify(self, gtest_filter, tests_to_run): - """Checks that the binary runs correct set of tests for the given filter.""" + """Checks that the binary runs correct set of tests for a given filter.""" tests_to_run = self.AdjustForParameterizedTests(tests_to_run) - # First, tests using GTEST_FILTER. + # First, tests using the environment variable. # Windows removes empty variables from the environment when passing it - # to a new process. This means it is impossible to pass an empty filter - # into a process using the GTEST_FILTER environment variable. However, - # we can still test the case when the variable is not supplied (i.e., - # gtest_filter is None). + # to a new process. This means it is impossible to pass an empty filter + # into a process using the environment variable. However, we can still + # test the case when the variable is not supplied (i.e., gtest_filter is + # None). # pylint: disable-msg=C6403 if CAN_TEST_EMPTY_FILTER or gtest_filter != '': SetEnvVar(FILTER_ENV_VAR, gtest_filter) @@ -261,7 +274,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): self.AssertSetEqual(tests_run, tests_to_run) # pylint: enable-msg=C6403 - # Next, tests using --gtest_filter. + # Next, tests using the command line flag. if gtest_filter is None: args = [] @@ -291,10 +304,10 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): tests_to_run = self.AdjustForParameterizedTests(tests_to_run) # Windows removes empty variables from the environment when passing it - # to a new process. This means it is impossible to pass an empty filter - # into a process using the GTEST_FILTER environment variable. However, - # we can still test the case when the variable is not supplied (i.e., - # gtest_filter is None). + # to a new process. This means it is impossible to pass an empty filter + # into a process using the environment variable. However, we can still + # test the case when the variable is not supplied (i.e., gtest_filter is + # None). # pylint: disable-msg=C6403 if CAN_TEST_EMPTY_FILTER or gtest_filter != '': SetEnvVar(FILTER_ENV_VAR, gtest_filter) @@ -435,10 +448,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): 'BazTest.TestOne', 'BazTest.TestA', - 'BazTest.TestB', - - 'HasDeathTest.Test1', - 'HasDeathTest.Test2', ] + PARAM_TESTS) + 'BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS) def testWildcardInTestName(self): """Tests using wildcard in the test name.""" @@ -499,7 +509,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): ]) def testNegativeFilters(self): - self.RunAndVerify('*-HasDeathTest.Test1', [ + self.RunAndVerify('*-BazTest.TestOne', [ 'FooTest.Abc', 'FooTest.Xyz', @@ -507,24 +517,17 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): 'BarTest.TestTwo', 'BarTest.TestThree', - 'BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB', + ] + DEATH_TESTS + PARAM_TESTS) - 'HasDeathTest.Test2', - ] + PARAM_TESTS) - - self.RunAndVerify('*-FooTest.Abc:HasDeathTest.*', [ + self.RunAndVerify('*-FooTest.Abc:BazTest.*', [ 'FooTest.Xyz', 'BarTest.TestOne', 'BarTest.TestTwo', 'BarTest.TestThree', - - 'BazTest.TestOne', - 'BazTest.TestA', - 'BazTest.TestB', - ] + PARAM_TESTS) + ] + DEATH_TESTS + PARAM_TESTS) self.RunAndVerify('BarTest.*-BarTest.TestOne', [ 'BarTest.TestTwo', @@ -532,15 +535,11 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): ]) # Tests without leading '*'. - self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:HasDeathTest.*', [ + self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:BazTest.*', [ 'BarTest.TestOne', 'BarTest.TestTwo', 'BarTest.TestThree', - - 'BazTest.TestOne', - 'BazTest.TestA', - 'BazTest.TestB', - ] + PARAM_TESTS) + ] + DEATH_TESTS + PARAM_TESTS) # Value parameterized tests. self.RunAndVerify('*/*', PARAM_TESTS) @@ -586,7 +585,7 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): os.remove(shard_status_file) def testShardStatusFileIsCreatedWithListTests(self): - """Tests that the shard file is created with --gtest_list_tests.""" + """Tests that the shard file is created with the "list_tests" flag.""" shard_status_file = os.path.join(gtest_test_utils.GetTempDir(), 'shard_status_file2') @@ -594,32 +593,41 @@ class GTestFilterUnitTest(gtest_test_utils.TestCase): extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file} try: - InvokeWithModifiedEnv(extra_env, - RunAndReturnOutput, - ['--gtest_list_tests']) + output = InvokeWithModifiedEnv(extra_env, + RunAndReturnOutput, + [LIST_TESTS_FLAG]) finally: + # This assertion ensures that Google Test enumerated the tests as + # opposed to running them. + self.assert_('[==========]' not in output, + 'Unexpected output during test enumeration.\n' + 'Please ensure that LIST_TESTS_FLAG is assigned the\n' + 'correct flag value for listing Google Test tests.') + self.assert_(os.path.exists(shard_status_file)) os.remove(shard_status_file) - def testShardingWorksWithDeathTests(self): - """Tests integration with death tests and sharding.""" - gtest_filter = 'HasDeathTest.*:SeqP/*' - expected_tests = [ - 'HasDeathTest.Test1', - 'HasDeathTest.Test2', - - 'SeqP/ParamTest.TestX/0', - 'SeqP/ParamTest.TestX/1', - 'SeqP/ParamTest.TestY/0', - 'SeqP/ParamTest.TestY/1', - ] - - for flag in ['--gtest_death_test_style=threadsafe', - '--gtest_death_test_style=fast']: - self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests, - check_exit_0=True, args=[flag]) - self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests, - check_exit_0=True, args=[flag]) + if SUPPORTS_DEATH_TESTS: + def testShardingWorksWithDeathTests(self): + """Tests integration with death tests and sharding.""" + + gtest_filter = 'HasDeathTest.*:SeqP/*' + expected_tests = [ + 'HasDeathTest.Test1', + 'HasDeathTest.Test2', + + 'SeqP/ParamTest.TestX/0', + 'SeqP/ParamTest.TestX/1', + 'SeqP/ParamTest.TestY/0', + 'SeqP/ParamTest.TestY/1', + ] + + for flag in ['--gtest_death_test_style=threadsafe', + '--gtest_death_test_style=fast']: + self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests, + check_exit_0=True, args=[flag]) + self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests, + check_exit_0=True, args=[flag]) if __name__ == '__main__': gtest_test_utils.Main() diff --git a/testing/gtest/test/gtest_help_test.py b/testing/gtest/test/gtest_help_test.py index 7883c1c..dc67ed3 100755 --- a/testing/gtest/test/gtest_help_test.py +++ b/testing/gtest/test/gtest_help_test.py @@ -32,7 +32,7 @@ """Tests the --help flag of Google C++ Testing Framework. SYNOPSIS - gtest_help_test.py --gtest_build_dir=BUILD/DIR + gtest_help_test.py --build_dir=BUILD/DIR # where BUILD/DIR contains the built gtest_help_test_ file. gtest_help_test.py """ @@ -51,11 +51,15 @@ FLAG_PREFIX = '--gtest_' CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions' DEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style' UNKNOWN_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing' -INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', DEATH_TEST_STYLE_FLAG), - re.sub('^--', '/', DEATH_TEST_STYLE_FLAG), - re.sub('_', '-', DEATH_TEST_STYLE_FLAG)] +LIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests' +INCORRECT_FLAG_VARIANTS = [re.sub('^--', '-', LIST_TESTS_FLAG), + re.sub('^--', '/', LIST_TESTS_FLAG), + re.sub('_', '-', LIST_TESTS_FLAG)] INTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing' +SUPPORTS_DEATH_TESTS = "DeathTest" in gtest_test_utils.Subprocess( + [PROGRAM_PATH, LIST_TESTS_FLAG]).output + # The help message must match this regex. HELP_REGEX = re.compile( FLAG_PREFIX + r'list_tests.*' + @@ -107,10 +111,13 @@ class GTestHelpTest(gtest_test_utils.TestCase): self.assert_(HELP_REGEX.search(output), output) if IS_WINDOWS: self.assert_(CATCH_EXCEPTIONS_FLAG in output, output) - self.assert_(DEATH_TEST_STYLE_FLAG not in output, output) else: self.assert_(CATCH_EXCEPTIONS_FLAG not in output, output) + + if SUPPORTS_DEATH_TESTS and not IS_WINDOWS: self.assert_(DEATH_TEST_STYLE_FLAG in output, output) + else: + self.assert_(DEATH_TEST_STYLE_FLAG not in output, output) def TestNonHelpFlag(self, flag): """Verifies correct behavior when no help flag is specified. diff --git a/testing/gtest/test/gtest_help_test_.cc b/testing/gtest/test/gtest_help_test_.cc index 0282bc8..aad0d72 100644 --- a/testing/gtest/test/gtest_help_test_.cc +++ b/testing/gtest/test/gtest_help_test_.cc @@ -40,3 +40,7 @@ TEST(HelpFlagTest, ShouldNotBeRun) { ASSERT_TRUE(false) << "Tests shouldn't be run when --help is specified."; } + +#if GTEST_HAS_DEATH_TEST +TEST(DeathTest, UsedByPythonScriptToDetectSupportForDeathTestsInThisBinary) {} +#endif diff --git a/testing/gtest/test/gtest_output_test.py b/testing/gtest/test/gtest_output_test.py index 192030a..425d9da 100755 --- a/testing/gtest/test/gtest_output_test.py +++ b/testing/gtest/test/gtest_output_test.py @@ -32,7 +32,7 @@ """Tests the text output of Google C++ Testing Framework. SYNOPSIS - gtest_output_test.py --gtest_build_dir=BUILD/DIR --gengolden + gtest_output_test.py --build_dir=BUILD/DIR --gengolden # where BUILD/DIR contains the built gtest_output_test_ file. gtest_output_test.py --gengolden gtest_output_test.py @@ -240,7 +240,7 @@ SUPPORTS_STACK_TRACES = False CAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and SUPPORTS_TYPED_TESTS and - SUPPORTS_THREADS) + (SUPPORTS_THREADS or IS_WINDOWS)) class GTestOutputTest(gtest_test_utils.TestCase): diff --git a/testing/gtest/test/gtest_output_test_.cc b/testing/gtest/test/gtest_output_test_.cc index 273e8e9..1ac439c 100644 --- a/testing/gtest/test/gtest_output_test_.cc +++ b/testing/gtest/test/gtest_output_test_.cc @@ -87,6 +87,20 @@ TEST(PassingTest, PassingTest1) { TEST(PassingTest, PassingTest2) { } +// Tests that parameters of failing parameterized tests are printed in the +// failing test summary. +class FailingParamTest : public testing::TestWithParam<int> {}; + +TEST_P(FailingParamTest, Fails) { + EXPECT_EQ(1, GetParam()); +} + +// This generates a test which will fail. Google Test is expected to print +// its parameter when it outputs the list of all failed tests. +INSTANTIATE_TEST_CASE_P(PrintingFailingParams, + FailingParamTest, + testing::Values(2)); + // Tests catching a fatal failure in a subroutine. TEST(FatalFailureTest, FatalFailureInSubroutine) { printf("(expecting a failure that x should be 1)\n"); @@ -1085,9 +1099,7 @@ class BarEnvironment : public testing::Environment { } }; -GTEST_DEFINE_bool_(internal_skip_environment_and_ad_hoc_tests, false, - "This flag causes the program to skip test environment " - "tests and ad hoc tests."); +bool GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = false; // The main function. // diff --git a/testing/gtest/test/gtest_output_test_golden_lin.txt b/testing/gtest/test/gtest_output_test_golden_lin.txt index ec60437..2f3994a 100644 --- a/testing/gtest/test/gtest_output_test_golden_lin.txt +++ b/testing/gtest/test/gtest_output_test_golden_lin.txt @@ -7,7 +7,7 @@ Expected: true gtest_output_test_.cc:#: Failure Value of: 3 Expected: 2 -[0;32m[==========] [mRunning 60 tests from 25 test cases. +[0;32m[==========] [mRunning 61 tests from 26 test cases. [0;32m[----------] [mGlobal test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -411,7 +411,7 @@ Value of: TypeParam() Actual: 0 Expected: 1 Expected failure -[0;31m[ FAILED ] [mTypedTest/0.Failure +[0;31m[ FAILED ] [mTypedTest/0.Failure, where TypeParam = int [0;32m[----------] [m2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char [0;32m[ RUN ] [mUnsigned/TypedTestP/0.Success [0;32m[ OK ] [mUnsigned/TypedTestP/0.Success @@ -422,7 +422,7 @@ Value of: TypeParam() Expected: 1U Which is: 1 Expected failure -[0;31m[ FAILED ] [mUnsigned/TypedTestP/0.Failure +[0;31m[ FAILED ] [mUnsigned/TypedTestP/0.Failure, where TypeParam = unsigned char [0;32m[----------] [m2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int [0;32m[ RUN ] [mUnsigned/TypedTestP/1.Success [0;32m[ OK ] [mUnsigned/TypedTestP/1.Success @@ -433,7 +433,7 @@ Value of: TypeParam() Expected: 1U Which is: 1 Expected failure -[0;31m[ FAILED ] [mUnsigned/TypedTestP/1.Failure +[0;31m[ FAILED ] [mUnsigned/TypedTestP/1.Failure, where TypeParam = unsigned int [0;32m[----------] [m4 tests from ExpectFailureTest [0;32m[ RUN ] [mExpectFailureTest.ExpectFatalFailure (expecting 1 failure) @@ -564,6 +564,13 @@ gtest_output_test_.cc:#: Failure Failed Expected non-fatal failure. [0;31m[ FAILED ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[0;32m[----------] [m1 test from PrintingFailingParams/FailingParamTest +[0;32m[ RUN ] [mPrintingFailingParams/FailingParamTest.Fails/0 +gtest_output_test_.cc:#: Failure +Value of: GetParam() + Actual: 2 +Expected: 1 +[0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [0;32m[----------] [mGlobal test environment tear-down BarEnvironment::TearDown() called. gtest_output_test_.cc:#: Failure @@ -573,9 +580,9 @@ FooEnvironment::TearDown() called. gtest_output_test_.cc:#: Failure Failed Expected fatal failure. -[0;32m[==========] [m60 tests from 25 test cases ran. +[0;32m[==========] [m61 tests from 26 test cases ran. [0;32m[ PASSED ] [m21 tests. -[0;31m[ FAILED ] [m39 tests, listed below: +[0;31m[ FAILED ] [m40 tests, listed below: [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInSubroutine [0;31m[ FAILED ] [mFatalFailureTest.FatalFailureInNestedSubroutine [0;31m[ FAILED ] [mFatalFailureTest.NonfatalFailureInSubroutine @@ -615,8 +622,9 @@ Expected fatal failure. [0;31m[ FAILED ] [mExpectFailureWithThreadsTest.ExpectFatalFailure [0;31m[ FAILED ] [mExpectFailureWithThreadsTest.ExpectNonFatalFailure [0;31m[ FAILED ] [mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread +[0;31m[ FAILED ] [mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -39 FAILED TESTS +40 FAILED TESTS [0;33m YOU HAVE 1 DISABLED TEST [mNote: Google Test filter = FatalFailureTest.*:LoggingTest.* diff --git a/testing/gtest/test/gtest_output_test_golden_win.txt b/testing/gtest/test/gtest_output_test_golden_win.txt index 313c3aa..fb69710 100644 --- a/testing/gtest/test/gtest_output_test_golden_win.txt +++ b/testing/gtest/test/gtest_output_test_golden_win.txt @@ -5,7 +5,7 @@ gtest_output_test_.cc:#: error: Value of: false Expected: true gtest_output_test_.cc:#: error: Value of: 3 Expected: 2 -[==========] Running 61 tests from 27 test cases. +[==========] Running 62 tests from 28 test cases. [----------] Global test environment set-up. FooEnvironment::SetUp() called. BarEnvironment::SetUp() called. @@ -369,7 +369,7 @@ gtest_output_test_.cc:#: error: Value of: TypeParam() Actual: 0 Expected: 1 Expected failure -[ FAILED ] TypedTest/0.Failure +[ FAILED ] TypedTest/0.Failure, where TypeParam = int [----------] 2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char [ RUN ] Unsigned/TypedTestP/0.Success [ OK ] Unsigned/TypedTestP/0.Success @@ -379,7 +379,7 @@ gtest_output_test_.cc:#: error: Value of: TypeParam() Expected: 1U Which is: 1 Expected failure -[ FAILED ] Unsigned/TypedTestP/0.Failure +[ FAILED ] Unsigned/TypedTestP/0.Failure, where TypeParam = unsigned char [----------] 2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int [ RUN ] Unsigned/TypedTestP/1.Success [ OK ] Unsigned/TypedTestP/1.Success @@ -389,7 +389,7 @@ gtest_output_test_.cc:#: error: Value of: TypeParam() Expected: 1U Which is: 1 Expected failure -[ FAILED ] Unsigned/TypedTestP/1.Failure +[ FAILED ] Unsigned/TypedTestP/1.Failure, where TypeParam = unsigned int [----------] 4 tests from ExpectFailureTest [ RUN ] ExpectFailureTest.ExpectFatalFailure (expecting 1 failure) @@ -479,6 +479,12 @@ Failed Expected non-fatal failure. [ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads +[----------] 1 test from PrintingFailingParams/FailingParamTest +[ RUN ] PrintingFailingParams/FailingParamTest.Fails/0 +gtest_output_test_.cc:#: error: Value of: GetParam() + Actual: 2 +Expected: 1 +[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 [----------] Global test environment tear-down BarEnvironment::TearDown() called. gtest_output_test_.cc:#: error: Failed @@ -486,9 +492,9 @@ Expected non-fatal failure. FooEnvironment::TearDown() called. gtest_output_test_.cc:#: error: Failed Expected fatal failure. -[==========] 61 tests from 27 test cases ran. +[==========] 62 tests from 28 test cases ran. [ PASSED ] 21 tests. -[ FAILED ] 40 tests, listed below: +[ FAILED ] 41 tests, listed below: [ FAILED ] FatalFailureTest.FatalFailureInSubroutine [ FAILED ] FatalFailureTest.FatalFailureInNestedSubroutine [ FAILED ] FatalFailureTest.NonfatalFailureInSubroutine @@ -529,8 +535,9 @@ Expected fatal failure. [ FAILED ] ExpectFailureTest.ExpectNonFatalFailure [ FAILED ] ExpectFailureTest.ExpectFatalFailureOnAllThreads [ FAILED ] ExpectFailureTest.ExpectNonFatalFailureOnAllThreads +[ FAILED ] PrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2 -40 FAILED TESTS +41 FAILED TESTS YOU HAVE 1 DISABLED TEST Note: Google Test filter = FatalFailureTest.*:LoggingTest.* diff --git a/testing/gtest/test/gtest_test_utils.py b/testing/gtest/test/gtest_test_utils.py index e0f5973..e7ee9d9 100755 --- a/testing/gtest/test/gtest_test_utils.py +++ b/testing/gtest/test/gtest_test_utils.py @@ -63,8 +63,8 @@ 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 = {'gtest_source_dir': os.path.dirname(sys.argv[0]), - 'gtest_build_dir': os.path.dirname(sys.argv[0])} +_flag_map = {'source_dir': os.path.dirname(sys.argv[0]), + 'build_dir': os.path.dirname(sys.argv[0])} _gtest_flags_are_parsed = False @@ -111,13 +111,13 @@ def GetFlag(flag): def GetSourceDir(): """Returns the absolute path of the directory where the .py files are.""" - return os.path.abspath(GetFlag('gtest_source_dir')) + 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('gtest_build_dir')) + return os.path.abspath(GetFlag('build_dir')) _temp_dir = None @@ -161,7 +161,7 @@ def GetTestExecutablePath(executable_name, build_dir=None): if not os.path.exists(path): message = ( 'Unable to find the test binary. Please make sure to provide path\n' - 'to the binary via the --gtest_build_dir flag or the GTEST_BUILD_DIR\n' + 'to the binary via the --build_dir flag or the BUILD_DIR\n' 'environment variable. For convenient use, invoke this script via\n' 'mk_test.py.\n' # TODO(vladl@google.com): change mk_test.py to test.py after renaming diff --git a/testing/gtest/test/gtest_unittest.cc b/testing/gtest/test/gtest_unittest.cc index 199b254..40049ae 100644 --- a/testing/gtest/test/gtest_unittest.cc +++ b/testing/gtest/test/gtest_unittest.cc @@ -132,23 +132,28 @@ using testing::Message; using testing::ScopedFakeTestPartResultReporter; using testing::StaticAssertTypeEq; using testing::Test; -using testing::TestEventListeners; using testing::TestCase; +using testing::TestEventListeners; using testing::TestPartResult; using testing::TestPartResultArray; using testing::TestProperty; using testing::TestResult; using testing::UnitTest; using testing::kMaxStackTraceDepth; +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::FormatTimeInMillisAsSeconds; using testing::internal::ForEach; +using testing::internal::FormatTimeInMillisAsSeconds; using testing::internal::GTestFlagSaver; using testing::internal::GetCurrentOsStackTraceExceptTop; using testing::internal::GetElementOr; @@ -157,9 +162,17 @@ using testing::internal::GetRandomSeedFromFlag; using testing::internal::GetTestTypeId; 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::RemoveConst; +using testing::internal::RemoveReference; using testing::internal::ShouldRunTestOnShard; using testing::internal::ShouldShard; using testing::internal::ShouldUseColor; @@ -171,7 +184,9 @@ using testing::internal::TestEventListenersAccessor; using testing::internal::TestResultAccessor; using testing::internal::UInt32; using testing::internal::WideStringToUtf8; +using testing::internal::kCopy; using testing::internal::kMaxRandomSeed; +using testing::internal::kReference; using testing::internal::kTestTypeIdInGoogleTest; using testing::internal::scoped_ptr; @@ -184,6 +199,10 @@ using testing::internal::GetCapturedStdout; using testing::internal::ThreadWithParam; #endif +#if GTEST_HAS_PROTOBUF_ +using ::testing::internal::TestMessage; +#endif // GTEST_HAS_PROTOBUF_ + class TestingVector : public std::vector<int> { }; @@ -323,7 +342,7 @@ TEST(NullLiteralTest, IsFalseForNonNullLiterals) { } #ifdef __BORLANDC__ -// Restores warnings after previous "#pragma option push" supressed them +// Restores warnings after previous "#pragma option push" suppressed them. #pragma option pop #endif @@ -1353,7 +1372,7 @@ void DoesNotAbortHelper(bool* aborted) { } #ifdef __BORLANDC__ -// Restores warnings after previous "#pragma option push" supressed them +// Restores warnings after previous "#pragma option push" suppressed them. #pragma option pop #endif @@ -1371,7 +1390,7 @@ static int global_var = 0; #define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++ TEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) { -#ifndef __BORLANDC__ +#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 // ICE's in C++Builder 2007. EXPECT_FATAL_FAILURE({ GTEST_USE_UNPROTECTED_COMMA_; @@ -3490,10 +3509,13 @@ TEST(AssertionTest, ASSERT_TRUE) { // Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult. TEST(AssertionTest, AssertTrueWithAssertionResult) { ASSERT_TRUE(ResultIsEven(2)); +#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 + // ICE's in C++Builder 2007. 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" @@ -3513,10 +3535,13 @@ TEST(AssertionTest, ASSERT_FALSE) { // Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult. TEST(AssertionTest, AssertFalseWithAssertionResult) { ASSERT_FALSE(ResultIsEven(3)); +#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 + // ICE's in C++Builder 2007. 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" @@ -3628,13 +3653,15 @@ void ThrowNothing() {} // Tests ASSERT_THROW. TEST(AssertionTest, ASSERT_THROW) { ASSERT_THROW(ThrowAnInteger(), int); -#if !defined(__BORLANDC__) || __BORLANDC__ >= 0x600 || defined(_DEBUG) - // ICE's in C++Builder 2007 (Release build). + +#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" @@ -6256,8 +6283,17 @@ TEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) { 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", "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 } @@ -6695,3 +6731,347 @@ TEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) { 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"); +} + +// 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 +// ProtocolMessage or a sub-class of it. +TEST(IsAProtocolMessageTest, ValueIsTrueWhenTypeIsAProtocolMessage) { + EXPECT_TRUE(IsAProtocolMessage< ::proto2::Message>::value); + EXPECT_TRUE(IsAProtocolMessage<ProtocolMessage>::value); +#if GTEST_HAS_PROTOBUF_ + EXPECT_TRUE(IsAProtocolMessage<const TestMessage>::value); +#endif // GTEST_HAS_PROTOBUF_ +} + +// 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 String&, const 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) { + 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]; + CopyArray(a, &b); + EXPECT_TRUE(ArrayEq(a, b)); + + 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]; + CopyArray(a, &b); + EXPECT_TRUE(ArrayEq(a, b)); + + 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, kReference); + 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, kCopy); + 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, kCopy); + 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, kReference); + 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, kReference)); + EXPECT_FALSE(na == NativeArray<int>(b2, 4, kCopy)); +} + +TEST(NativeArrayTest, WorksForTwoDimensionalArray) { + const char a[2][3] = { "hi", "lo" }; + NativeArray<char[3]> na(a, 2, kReference); + ASSERT_EQ(2U, na.size()); + EXPECT_EQ(a, na.begin()); +} diff --git a/testing/gtest/test/run_tests_util.py b/testing/gtest/test/run_tests_util.py index 9e57931..a123569 100755 --- a/testing/gtest/test/run_tests_util.py +++ b/testing/gtest/test/run_tests_util.py @@ -171,7 +171,7 @@ class TestRunner(object): def __init__(self, script_dir, - build_dir_var_name='GTEST_BUILD_DIR', + build_dir_var_name='BUILD_DIR', injected_os=os, injected_subprocess=subprocess, injected_build_dir_finder=_GetGtestBuildDir): diff --git a/testing/gtestmain.target.mk b/testing/gtestmain.target.mk index 86208d7..e1db871 100644 --- a/testing/gtestmain.target.mk +++ b/testing/gtestmain.target.mk @@ -18,6 +18,7 @@ CFLAGS_Debug := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O0 \ -g @@ -49,6 +50,7 @@ CFLAGS_Release := -pthread \ -Wno-missing-field-initializers \ -D_FILE_OFFSET_BITS=64 \ -fvisibility=hidden \ + -pipe \ -fno-strict-aliasing \ -O2 \ -fno-ident \ @@ -92,11 +94,12 @@ $(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD # End of this set of suffix rules ### Rules for final target. LDFLAGS_Debug := -pthread \ - -Wl,-z,noexecstack \ - -rdynamic + -Wl,-z,noexecstack LDFLAGS_Release := -pthread \ -Wl,-z,noexecstack \ + -Wl,-O1 \ + -Wl,--as-needed \ -Wl,--gc-sections LIBS := |